content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def lines( *, base_width=0.5, line_base_ratio=2.0, tick_major_base_ratio=1.0, tick_minor_base_ratio=0.5, tick_size_width_ratio=3.0, tick_major_size_min=3.0, tick_minor_size_min=2.0, axisbelow=True, ): """Adjust linewidth(s) according to a base width.""" tick_major_width = ti...
04cfd88f419165f4601e02533bb2def1154de58b
643,913
def stack_template_key_name(blueprint): """Given a blueprint, produce an appropriate key name. Args: blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the key from. Returns: string: Key name resulting from blueprint. """ name = bluep...
d7c52712e8c22ef675380e03ddef60e3557296af
643,914
def _set_log_format(color: bool, include_caller: bool) -> str: """ Set log format :param color: Log message is colored :param include_caller: At the end, put a [caller:line-of-code], e.g. [script:123] :return: string of log format """ level_name = "* %(levelname)1s" time = "%(asctime)s,%...
48e0da162e1633f61ebd787e569d2435f932aa6a
643,917
def bitceil(N): """ Find the bit (i.e. power of 2) immediately greater than or equal to N Note: this works for numbers up to 2 ** 64. Roughly equivalent to int(2 ** np.ceil(np.log2(N))) """ # Note: for Python 2.7 and 3.x, this is faster: # return 1 << int(N - 1).bit_length() N = int(N) ...
33bd75c2a129f7797b8efcb50a3be275918dfd16
643,921
def _loop_action_in_command_line(command_line: str) -> bool: """Does the command line contain a loop statement Args: command_line (str): The command line to test. Returns: bool: True if there's a loop in this command line. """ return any( word in command_line.split() for wo...
8cf6c17805dc25be41ecbc32664bd396d13e3df1
643,925
from datetime import datetime def format_date( date: datetime, base: datetime = datetime.now(), all_day: bool = False ) -> str: """Convert dates to a specified format Arguments: <date>: The date to format [base]: When the date or time matches the info from base, it will be skipped. This helps avoid repeated i...
5e755097dd858b5f37000be113758611076dc59c
643,927
import hmac import hashlib import base64 def authenticate(request, channel_secret): """Validates the incoming HTTP requests. Args: request (flask.Request): HTTP request object. channel_secret (str): channel secret got from LINE developer console. Returns: bool: true when ...
7908d4d9ee6a4ecd4c6ff2e6eafe5f2903fbfe9c
643,933
import base64 def string_to_base64(string): """ Encodes a string in base64 (> str) """ string_bytes = string.encode('ascii') base64_encoded = base64.b64encode(string_bytes) base64string = base64_encoded.decode('ascii') return base64string
d918ad8120331aa62efcc548ff6345cd8c67580b
643,934
import re def get_vcpus_per_osd_from_ironic(ironic, tripleo_environment_parameters, num_osds): """ Dynamically sets the vCPU to OSD ratio based the OSD type to: HDD | OSDs per device: 1 | vCPUs per device: 1 SSD | OSDs per device: 1 | vCPUs per device: 4 NVMe | OSDs per device: 4 | vCPUs p...
a0a88b9e3d29342b16792d56198f7ee0ee7cabf7
643,936
import torch def create_pinhole(fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz): """Creates pinhole model encoded to a torch.Tensor. """ return torch.Tensor([ [fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz]])
2ffa87c9c7b243ff9769329d0e705a245cb52bef
643,944
import base64 def _posh_encode(command): """Encode a powershell command to base64. This is using utf-16 encoding and disregarding the first two bytes :param command: command to encode """ return base64.b64encode(command.encode('utf-16')[2:])
e307c56179b6aa1d5cfa76d7568b7c26f8fe5800
643,947
import six def _convert_str(data, to_binary=False): """Helper to convert str to corresponding string or binary type. `data` has `str` type (in both Python 2/3), the function converts it to corresponding string or binary representation depending on Python version and boolean `to_binary` parameter. ...
10d16fbe6be8148299969f7f455f3f54089cec45
643,949
import re def _is_valid_import(source_module, target_module, disallowed): """ Return whether an import is allowed. Parameters ---------- source_module : str Name of the module where the import statement is. target_module : str Name being imported. disallowed : str Regu...
e943da982133f168810ce219571e00f94c811937
643,950
import torch def extract_indices(seq, which_one): """ Helper method to extract the indices of elements which have the specified label. :param labels: (torch.tensor) Labels of the context set. :param which_class: Label for which indices are extracted. :return: (torch.tensor) Indices in the form of ...
a9865c58bd05fe2e818091a0c1e7f1dc62962064
643,953
import random def decision(probability: float): """Function that gives you a decision based on a given probability :param probability: float between 0 and 1 :type: float :return: True or False :rtype: bool """ if random.random() < probability: print("You know what let's do it...") ...
9a4213f1ac7f6bc95d58e9dcb7223a73cdf10fc7
643,954
def speed_ms_to_kmh(speed_ms): """Converts to m/s to km/h""" return speed_ms * 3.6
25dff568fb0edb5f3d7af73cc45b3dfd5ec24e9b
643,957
from pathlib import Path def temp_directory(tmpdir): """Return path to temporary directory, and cleanup afterwards.""" return Path(tmpdir).resolve()
a0a9ec9282414a0187a1e98ba9a58f6beac9b7ee
643,960
def ipv6_mask_to_long(mask): """Convert an IPv6 prefixlen to long >>> ipv6_mask_to_long(64) 340282366920938463444927863358058659840L >>> ipv6_mask_to_long(128) 340282366920938463463374607431768211455L """ mask_binary = ("1" * mask) + ("0" * (128-mask)) return int(mask_binary, 2)
eda598f07220c69238ba4988cbf37f0b7ba9241a
643,963
def normalize_volume(audio, dBFS=-15): """Normalizes the volume of an audio clip. Normalizes the amplitude of and audio clip to match a specified value of decibels relative to full scale. Args: audio (pydub AudioSegment): The audio clip to be normalized. dBFS (int): the desired...
3dde8c64fc5cb4997c17da1596458788b675a6f5
643,968
def findMatching(device, device_arr): """ Check the array of devices to see if there is a matching element. Args: device (string): The name of the device attempting to be added. device_arr (array): An array of the devices attached to a profile. """ matches = [x for x in device_arr i...
388e7ee8c66d91f52935dfe61e9b2ce8cb3ac661
643,970
import re def sanitize_host(host): """ Removes extraneous characters from a hostname, leaves an IP untouched. """ if re.match(r'[a-zA-Z]', host): return host.split()[0].strip().replace('_', '-').replace('.', '') else: return host
fdb33ca216c99ce5de7d33b71bd44cd104ae83c4
643,975
def _insert_token_to_repo_url(url, token): """Insert the token to the Git repo url, to make a component of the git clone command. This method can only be called when repo_url is an https url. Args: url (str): Git repo url where the token should be inserted into. token (str): Token to be ins...
6cf18aded0cbbbe317b9c94cbcf232932e90d4ec
643,982
def indent(input_str, prefix): """ Given a multiline string, return it with every line prefixed by "prefix" """ return "\n".join([f"{prefix}{x}" for x in input_str.split("\n")])
e05f4b133b396bfcb9aecd4549b03397ab04fb7d
643,986
import re from typing import Dict def _parse_group(pr_txt: str, header_pattern: str, entry_regex: re.Pattern) -> Dict[str, int]: """General function to parse and extract a listing from the press release. Args: pr_txt: The text of the press release. header_pattern: A string rep...
b8c8c95636b331aac2963b1259d67eb55dd4e140
643,987
import uuid def create_boundary(prefix, compact=False): """Creates a string that can be used as a multipart request boundary. :param bool compact: :param str prefix: String to use as the start of the boundary string """ if compact: return prefix + str(uuid.uuid4())[:8] else: r...
b80acd4b79886c12d10a323a5b15b9898c7bc7b9
643,988
def check_lru(sc): """ Check LRU replacement of sim_cache. """ sc.reset() # Setup 5 addresses with different tags but in the same set address = [sc.merge_address(i, 0, 0) for i in range(5)] # Write different data to each address for i in range(5): sc.write(address[i], "1111", i + 1) ...
85f1f729e396915ea0388fb96eb9c15d94d5ef6b
643,989
import math def is_prime(n: int) -> bool: """ Check wether a certain number is prime or not. Parameters ---------- n: int The number to check. Returns ------- bool True if the number is prime, False if it isn't. """ if n <= 1: return False if n == ...
6bb394bf24683e4895980ff75a4416fbdb642410
643,992
import re def enclose(s): """Enclose the string in $...$ if needed""" if not re.match(r'.*\$.+\$.*', s, re.MULTILINE | re.DOTALL): s = u"$%s$" % s return s
cead88fbf821337aa0d08145f5422446cc6b298d
643,993
def dot_notation(dict_like, dot_spec): """Return the value corresponding to the dot_spec from a dict_like object :param dict_like: dictionary, JSON, etc. :param dot_spec: a dot notation (e.g. a1.b1.c1.d1 => a1["b1"]["c1"]["d1"]) :return: the value referenced by the dot_spec """ attrs = dot_spec....
ea6c71a7f33dac3e7f1690212493ab7fca1c3962
643,994
def m_hook(self, node): """Alias .mm files to be compiled the same as .cpp files, gcc/clang will do the right thing.""" return self.create_compiled_task('cxx', node)
c5a4fb01c76729cbbb5da496f35ea467bede6b7c
643,995
def parse_pattern(pattern): """Convert a string of 1s and 0s into a pattern of Trues and Falses. >>> parse_pattern('1010010') [True, False, True, False, False, True, False] """ return map(lambda x: True if x == '1' else False, pattern)
58490b1c62e95e25d7bb9b3990c6530ca40b8fd9
643,998
def _check_installed_pkg(module, package, repository_path): """ Check the package on AIX. It verifies if the package is installed and informations :param module: Ansible module parameters spec. :param package: Package/fileset name. :param repository_path: Repository package path. :return: B...
276157ca75ca7397395aa00837dc368d5f2ee0e0
643,999
def cross3D(v1, v2): """Calculates the vector cross product of two 3D vectors, v1 and v2""" return (v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0])
888db7be621be85643eb1b6aa5f29cdefd264f03
644,004
def cubrt(x): """Returns the cubed root of x""" return round(x ** (1/3), 12)
41e500d1ee6ccc61c4442ea618c17daebea76c4e
644,007
import functools def if_true(toggle_attr): """Returns a decorator that executes its method if a condition is met.""" def if_true_decorator(instance_method): """Execute the decorated method conditional on a toggle attribute.""" @functools.wraps(instance_method) def wrapper(self, *args, ...
6cfcb384eb133a8558755136b66329c8ce266af5
644,014
import hashlib def key_sha1(*args): """This method creates an SHA-1 from the input parameters, used for caching filename""" return hashlib.sha1("".join(str(args)).encode("utf-8")).hexdigest()
b38cc450a2714abd3951915ec7d50bcd11f2a892
644,015
def add_to_dict(d, key, base): """Function to add key to dictionary, either add base or start with base""" if key in d: d[key] += base else: d[key] = base return d
a13cbd99956bc551999cf30a39e87fb5dde90ece
644,016
def make_columns_grammar(columns): """Return a lark rule that looks like // These are my raw columns str_0: "[" + /username/i + "]" | /username/i str_1: "[" + /department/i + "]" | /department/i str_2: "[" + /testid/i + "]" | /testid/i """ items = [] for k in sorted(columns.keys()): ...
9ee62b9fee1bfb66ab5ec49b90420d401b1200f7
644,019
def add_model_params_tree(info_dict): """Adds model parameters to `info_dict` for tree models. Only model-related parameter information will be added in this function. A series of these functions are used in a flow to get all information needed in tree model summary. The flow is `~greykite.algo.com...
7e2fdc4e576ee26e3f0f70da2d2d7083369bf35c
644,021
import string def buildGoodSet(goodChars=string.printable, badChar='?'): """Build a translation table that turns all characters not in goodChars to badChar""" allChars = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+...
34e31f3aeb62204572304858c59298f348651b98
644,022
def get_newsentry_meta_description(newsentry): """Returns the meta description for the given entry.""" if newsentry.meta_description: return newsentry.meta_description # If there is no seo addon found, take the info from the placeholders text = newsentry.get_description() if len(text) > 16...
9a0713978e513129ae7487d4d5a34e5b2eedd0c1
644,024
def CleanFCSstring(strFCS): """ If string can be converted to int, then returns clean string with only the int. othervise returns '-1'.""" try: return str(int(strFCS)) except: return "-1"
b14ec6642f6d4bc822059bc7fdaaceaa63e1eeb7
644,027
from typing import Any import ast def _is_lexical_match(matched: Any) -> bool: """Returns whether the match can be a lexical one. Its not well documented what ast objects return token information and which ones don't, and there are known instances of the token information being wrong in certain cases. Arg...
faf8ea20b02e0a38219ab1e9b0495d06fcc0bb54
644,031
def dest_times(t): """Given t1 * t2, return (t1, t2).""" assert t.is_times(), "dest_times" return (t.arg1, t.arg)
ce6c36e5076f4f306e27ec4afd751e34dc4a69a0
644,032
import inspect import warnings def deprecated(func, solution): """ Mark a parser or combiner as deprecated, and give a message of how to fix this. This will emit a warning in the logs when the function is used. When combined with modifications to conftest, this causes deprecations to become fatal...
1b7b8c27cc1eac1695c26181f53d04523874c270
644,033
import torch def image_distance(x: torch.Tensor, y: torch.Tensor, order=2) -> torch.Tensor: """Returns the distance between two batches of images Args: x (torch.Tensor): First batch of images y (torch.Tensor): Second batch of images order (int, optional): Order of the norm. Defaults t...
730704fb1b3e5ba0b748316b4c30102e0888ad7b
644,034
def escape_nmap_filename(filename): """Escape '%' characters so they are not interpreted as strftime format specifiers, which are not supported by Zenmap.""" return filename.replace("%", "%%")
c33a77405caca59d5a0f5ba9eee1acb1e6e6914d
644,037
def shift_and_zero(buf): """Shift 1 -> 0, and zero out 1.""" buf[0, :] = buf[1, :] buf[1, :] = 0.0 return buf
530eb99730d5dbc9964667bd3d3bdfcf6fe9a4c6
644,038
def to_aws_tags(tags): """ Convert tags from dictionary to a format expected by AWS: [{'Key': key, 'Value': value}] :param tags :return: """ return [{'Key': k, 'Value': v} for k, v in tags.items()]
c038d183f2456179d134692d50bfddcd9249b976
644,039
def duplicate_count(text): """ Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric dig...
ef58a9990849b1c52cd7e0236a77730ec794a446
644,040
import time def epoch2iso(timestamp): """Returns the ISO representaton of a UNIX timestamp (epoch). >>> epoch2iso(1620459129) '2021-05-08 09:32:09' """ timestamp = float(timestamp) return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
d8238b50189417db302846f4c194b6d3bd04ce3f
644,044
def convert_to_xs_and_ys(waypoint, lon_min, lon_max, lat_min, lat_max, w, h): """Convert from a list of positions to their x/y coordinates in the image.""" xs = [] ys = [] for step in waypoint: xs.append((step["lon"] - lon_min) / (lon_max - lon_min) * w) ys.append((lat_max - step["lat"...
d61c753c12f058c4332c7dd543fa707e8240f2ec
644,046
import binascii def b64encode(s, altchars=None): """Encode a byte string using Base64. s is the byte string to encode. Optional altchars must be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or f...
0a31ffe5eaf307657e27a77fe7d3859cdeeb068a
644,051
def ensure_str(s): """ Simple conversion of the value `s` to a `str`, that is, a byte string on Python 2 and a unicode string on Python 3. Input is expected to be a byte-string or unicode string in both Py2 or Py3. """ if not isinstance(s, str): return s.decode('utf-8') return s
c1ea872f96043c9be2e3676190e0491a87fd8827
644,052
def get_cli_input_year() -> str: """Get CLI input for the year of the car""" car_year = input("Enter the year of the car: ") return car_year
79e8636cd5f0b58b495f7e7b71b011fa1be35d44
644,056
def argify(argname, argval): """ :param argname: String naming a parameter for a script called from terminal :param argval: Object to assign in string form as the value of the argument :return: String, a parameter assignment for a script called from terminal """ return "--{}={}".format(argname, ...
b22872fa7e3b4ec532b8b5ccf0d09db72fa1aaa6
644,057
def human_size(bytes, units=None): """Returns a human readable string representation of bytes""" if not units: units = [" bytes", "KB", "MB", "GB", "TB", "PB", "EB"] return str(bytes) + units[0] if bytes < 1024 else human_size(bytes >> 10, units[1:])
89d9eb04b0eff0289c4b03960a49840fd0e5be63
644,059
def normalizeHomogenious(points): """ Normalize a collection of points in homogeneous coordinates so that last row = 1. """ for row in points: row /= points[-1] return points
88f6927989e6247784f82ad90b4da979ca129c57
644,060
def count_parameters(net, as_int=False): """Returns total number of params in a network""" count = sum(p.numel() for p in net.parameters()) if as_int: return count return f"{count:,}"
d52db72eced2c536292f4f398485505b95a83578
644,063
def count_chars(template: str, instructions: dict[str, str], n: int) -> int: """ Counts the characters in the would-be string after `n` steps and returns the highest count (most common) - lowest count (least common). Args: template (str): The polymer template e.g. "NNCB" instructions (d...
16b639b0e07eb719d392992d92513c85375a59b2
644,065
def has_blank_ids(idlist): """ Search the list for empty ID fields and return true/false accordingly. """ return not(all(k for k in idlist))
bb25fc94c6ba3bedad1597b21032d8cd998bbccf
644,072
import math def applyPan(min_, max_, panFactor, isLog10): """Returns a new range with applied panning. Moves the range according to panFactor. If isLog10 is True, converts to log10 before moving. :param float min_: Min value of the data range to pan. :param float max_: Max value of the data rang...
152eae9f48a6831c3d2059a074605e35daf5df27
644,074
from typing import List def find(arr: List[int], key: int) -> int: """Modified version of binary search: one half of the array must be already sorted. Therefore check the sorted half to decide whether to search the left or right half. This takes O(lg n) time and O(1) space. """ lo = 0 hi = len...
b4a49cc73009b27344fc403a79c26130339b5d04
644,082
def error_margin_sample(z_star, SE): """ Get the margin of error of a sampling distribution. Parameters ---------- > z_star: the critical score of the confidence level > SE: the standard error of the sample Returns ------- The margin of error, given by z_star/SE. """ return z_star / SE
3574771cd0a7778ff58a9de88c824a2cabf9a5c3
644,085
from typing import Mapping from typing import Any from typing import Union from typing import Sequence import functools import operator def recursive_getitem(d: Mapping[str, Any], keys: Union[str, Sequence[str]]) -> Any: """Recursively retrieve an item from a nested dict. Credit to: https://stackoverflow.com...
290bd14d940da28562883d60c3654d2bbc0e0d3c
644,088
def group_type(type_string): """ Surround a type with parentheses as needed. """ return ( '(' + type_string + ')' if '|' in type_string else type_string )
d1e17463bfec696f19c0009d7d006c7e9672ee74
644,089
from typing import Union from typing import Tuple def get_input(params: Union[dict, list]) -> Tuple[list, dict]: """ Get positional or keyword arguments from JSON RPC params :param params: Parameters passed through JSON RPC :return: args, kwargs """ # Backwards compatibility for old clients t...
563b87ad6f4dde1a5e8021b656efa299567acf35
644,097
import re def search_string(data_fetched): """ Function to search the returned email string for the word 'Hi' and return the words after it. Chose to collect 90 expressions after the keyword to ensure variance in the length of ship names and locations are accounted for. It returns the matched stri...
c12287026d000d7df26c9c82e167d560ddee8203
644,098
def _pseudo_voigt_mixing_factor(width_l, width_g): """ Returns the proportion of Lorentzian for the computation of a pseudo-Voigt profile. pseudoVoigt = (1 - eta) Gaussian + eta * Lorentzian Parameters ---------- width_l, width_g : float FWHM for the Gaussian and Lorentzian parts, r...
7723370d749c62dcddcbf95272727baa9995f23a
644,099
import collections import operator def is_batch_good(batch): """ Checks if a batch of tokens is valid. Parameters ---------- batch : list A list of integer tokens """ my_dict = collections.defaultdict(int) for i in batch: my_dict[i] += 1 sorted_x = sorted(my_...
538af49a20939f3adca6bb4313f07c5fde574c0c
644,101
def odds(nums): """Odds: Given a list of numbers, write a list comprehension that produces a list of only the odd numbers in that list. >>> odds([1, 2, 3, 4, 5]) [1, 3, 5] >>> odds([2, 4, 6]) [] >>> odds([-2, -4, -7]) [-7] """ lst = [a for a in nums if a%2...
253ce5257f102eb65a948d05af025ba4963028b8
644,103
from math import floor def conv_output_dim(input_size, kernel_size, stride=1, padding=0, dilation=1, **kwargs): """Calculate the output dimension of a convolutional layer """ return floor((input_size + 2*padding - dilation*(kernel_size-1) - 1)/stride + 1)
955fd5e69e1ae5b1822fd28000d2db2fa3881f19
644,104
import math def cylinder_plane(F, L, D1, E1, E2): """ Calculate line contact pressure a cylinder and a plane. Arguments; F: Force, e.g. in [N]. L: Contact length, e.g. in [mm]. D1: Diameter of cylinder in e.g. [mm]. E1: Young's modulus of first cylinder in e.g. [MPa]. ...
81cf48127f4f68f805ab10515e4a1b95f2295af7
644,105
def do_if(tag, dictionary): """Removes a tag if its condition is False. :param tag: Tag to be evaluated :type tag: BeautifulSoup :param dictionary: Canonical dictionary of parameters :type dictionary: dict :return: Whether or not the tag was deleted :rtype: bool""" if tag.get("tuscon_if...
4108c6508e3a19bfca46d803fa9d573d2313b379
644,107
import re def find_url(string): """Find if a string contains an URL""" # findall() has been used # with valid conditions for urls in string url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',string) if len(url) > 0: return True
b4d3c42aa2037000f65a7f209ec7fc6a1654e19c
644,111
def parse_header(line, numeric_vals=True): """ Parse a line of the form: #param=val\tparam=val\tparam=val... Return a dictionary of params: vals """ line = line.strip() if line[0] == '#': line = line[1:] params = {} for pair in line.split('\t'): k, v = pair.spli...
98c3ff35a7a86beddd0b6cb4c4315986ed13725f
644,113
def split_string(value, arg=None): """ A simple string splitter So you can do that : :: {% if LANGUAGE_CODE in "fr,en-ca,en-gb,zh-hk,it,en,de"|split:',' %} """ return value.split(arg)
931927e4aaf23806c7d6af4228154ce40bc31eb4
644,117
def resample_prices(close_prices, freq='M'): """ Resample close prices for each ticker at specified frequency. Parameters ---------- close_prices : DataFrame Close prices for each ticker and date freq : str What frequency to sample at For valid freq choices, see http...
a1a5c0e12074680436372aafc0236cc1604e7c8a
644,119
def even(x): """ Returns 1 if x is even, 0 otherwise. """ return x % 2 == 0
a7add035b3a39e2bd7e31a4ede9db1457a085a10
644,120
def dictUpdate(original,newer): """Combine two dictionaries. If duplicate keys exist, use the newer values to overwrite the older ones.""" for k in newer.keys(): original[k]=newer[k] return original
742ad9e4f8c4e05ddc83227e6310aaff649d5a97
644,121
def normalize_minmax(ar): """ Return the array ar scaled so that the min value is 0 and the max value is 1. """ x = ar - min(ar) mmax = max(x) if mmax == 0: return x return x/mmax
6590827e0b33a92e3c772bfd9a9a57f788f6ea10
644,125
def _is_chrome_only_build(revision_to_bot_name): """Figures out if a revision-to-bot-name mapping represents a Chrome build. We assume here that Chrome revisions are always > 100000, whereas WebRTC revisions will not reach that number in the foreseeable future. """ revision = int(revision_to_bot_name.split('...
c40ead84670aaa9435b948e16d7a12591362b5f6
644,126
def me( context, api_client, api_key, output_file, output_format, verbose, ): """Get information about the currently authenticated Sublime user.""" result = api_client.me() return result
8113e3a7f3e45bf41697936415c9ec9cf658a3a4
644,128
import re def parse_line(line,pattern,strict=True): """Matches given input line to regex. Line is stripped of leading/trailing whitespace. Args: line (string) : input line to parse pattern (string) : string containing regex strict (bool) : raise exception if mismatch (default: Tr...
1c73bb48277572ce408848975683c34f8c565f25
644,132
from typing import Any from typing import List def default_value(value: Any, fallback: Any, disallowed: List[Any] = [None]) -> Any: """ Checks whether the provided value is (by default) None or matches any other disallowed value, as provided. If the value is disallowed, the fallback will be returned. ...
70aefaa302e12b611927423a39ecff4dcf9e7990
644,138
import tempfile import base64 def dummy_image(filetype='gif'): """Generate empty image in temporary file for testing""" # 1x1px Transparent GIF GIF = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype) tmp_file.write(base64.b64...
917306b8aca8bcc84ac2e5369c2271fd13b9a312
644,145
def contains_any(string, candidates=[]): """Return True if a string contains any of the given candidate strings.""" for candidate in candidates: if candidate.lower() in string.lower(): return True return False
1c422cbc8f00c07854118784ca54454cdc9085d3
644,147
def vec_div (v,s): """scalar vector division""" return [ v[0]/s, v[1]/s, v[2]/s ]
6e56bb65431616d3ab2e59cddb096bfc579e3894
644,150
def _alpha(n, threshold=30, scale=2000): """ Calculate a rough guess for the best alpha value for a default scatterplot. This is calculated with the equation .. math:: \\alpha = \\frac{0.99}{1 + \\frac{n}{\\text{scale}}} This is done so that is ranges from nearly 1 for small values of n ...
80fc718b1e624bbe91fd2f64e2c58eaa98723b8a
644,168
import numbers import torch def is_identically_zero(x): """ Check if argument is exactly the number zero. True for the number zero; false for other numbers; false for :class:`~torch.Tensor`s. """ if isinstance(x, numbers.Number): return x == 0 if not torch._C._get_tracing_state(): ...
641e57d7b09ffe6623f9f15e769ed33c0354dbea
644,169
import time from datetime import datetime def get_current_chart(charts): """Get the current relevant chart""" current_unix_time = time.mktime(datetime.now().timetuple()) current_chart = charts[-1] for chart in charts: if float(chart.datetimestamp) <= current_unix_time: current_ch...
a136c111c827c22e397ff827158840dec9b4c91d
644,175
import fnmatch def shell_match( namelist, matchlist ): """ Looks for a name in 'namelist' that matches a word in 'matchlist' which can contain shell wildcard characters. """ for n in namelist: for m in matchlist: if fnmatch.fnmatch( n, m ): return 1 return 0
634788e15d63be687945ed7042708b2ec234cf26
644,178
import random def checkMissPlayer(defender): """ Returns a boolean token: if player missed or not. If defenders AC (Armor Class) is above players hit the token will evaluate to False, and the player will respectively miss. """ global currPlayerHitToken missChance = random.randrange(0, 25) if missChance <...
8066865a303d694044b550f96a8c5af25d988d46
644,180
def calculate_precision_recall(TP, TN, FP, FN): """ Calculates the Precision and Recall meassure of the supplied reference and test data, as per https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context) Incase of the denominator being zero for precision/recall, the values are se...
5244e6021c1861e510bfcb927be918e39410c1e4
644,181
def heptagonal_n(n): """Returns the nth heptagonal number""" return int(n * (5 * n - 3) / 2)
80e996d449d19611bf1e220a0f2103d5de9adc00
644,182
def get_minimum_rect_from_contours(contours, padding=2): """ Find the minimum that include all of contour of contours array :param contours: array of contour :param padding: Add padding value for return rect :return: return rect object represent in format of (x_min, x_max, y_...
a58c30b2dc22885aff62198262f6932e982d55f5
644,183
import torch def mixup_data(x, y, l): """Returns mixed inputs, pairs of targets, and lambda""" indices = torch.randperm(x.shape[0]).to(x.device) mixed_x = l * x + (1 - l) * x[indices] y_a, y_b = y, y[indices] return mixed_x, y_a, y_b
063175fe09267684633b329cd4fa315cc1b9c89d
644,184
from pathlib import Path def fixture_db_path(db_dir: Path, db_name: str) -> Path: """Return the path to a database""" return db_dir / db_name
bdc70c3096035296ca2dbda9728b5f143c3e77d2
644,188
def _merge_small_dims(shape_to_merge, max_dim): """Merge small dimensions. If there are some small dimensions, we collapse them: e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if max_dim = 1024 [1, 2, 768, 1, 2048] --> [2, 768, 2048] Args: shape_to_merge: Shape to merge small dimensions. ...
807cdd4682b1387405f1b0f35cb7b1858a763357
644,189
def trimhttp2(url): """ Strip 'http://' or 'https://' prefix to url """ if url[:7] == b'http://': return url[7:] elif url[:8] == b'https://': return url[8:] return url
541d698bf6fffab5f0bdf6b71a44eec48e08e9f9
644,190