content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def formatters(m) -> str:
"""One or more text formatters, as a space-separated string."""
if hasattr(m, "standalone_formatters"):
return m.standalone_formatters
else:
return " ".join(m.chainable_formatters_list) | 42fdd3a351e7c37328f49749defd7086a46ab17a | 640,603 |
import aiohttp
def get_session(limit=100, ttl_dns_cache=10, use_dns_cache=True, loop=None) -> aiohttp.ClientSession:
"""
https://docs.aiohttp.org/en/stable/client_reference.html
:return: properly configured tcp/http session with
- asyncronous dns resolving enabled
- dns cache enabled with proper t... | c658cbfd2638a4b0a6d319a128d19df9e7b59184 | 640,604 |
import operator
def function_factory(given_operator, immediate_A=False, immediate_B=False):
"""
Generates a function for the given operator and a boolean indicating which inputs to consider
as immediate or from register
"""
def f(register, A, B, C):
result = register.copy()
# Read... | cd186326646419905867da970816fccfd7b12e35 | 640,605 |
import sys
import os
def get_maven_user_dir():
"""
Return the path to the user's .m2 directory.
Create the directory if it does not already exist.
Returns:
The path to the user's .m2 directory.
"""
if sys.platform == 'cygwin':
user_dir = cygpath_to_unix(os.enviro... | e4318879bef5aeb8e493c55e93be4efd5b9a6bc5 | 640,606 |
def empty_prep_nb(context, *args):
"""Preparation function that forwards received arguments down the stack."""
return args | 8f7c11f24aef5ab039bf3d2f870844d0203dd066 | 640,607 |
def subproc_env(d):
"""Set environment variables for the @insubprocess decorator"""
def decorator(f):
f.subproc_env = d
return f
return decorator | 743d6e4c1d5bb120fb6cb0335e42207cff32f2e2 | 640,608 |
def inverses(k):
""" calculates the inverses of each number in k space """
inverse_numbers = dict()
for i in range(k):
if i in inverse_numbers:
continue
for j in range(i, k):
if (i * j) % k == 1:
inverse_numbers[i] = j
inverse_numbers[j... | 8986c4d08a50f90359641b036e9061b4776e00a8 | 640,609 |
def outline(text: str, outline_clr=[10,10,10], text_clr=[250,250,250]) -> str:
""" Creates a colored outline around the given text.
Requires the "contour" package in the preamble, preferably with the [outline] option. That is:
\usepackage[outline]{contour}
Currently, this package is not included by de... | cd6851d842a589228a7a41e3f3f771b2239a3d31 | 640,612 |
def fetch_licenses(fw_conn):
"""Fetch Licenses
Args:
fw_conn (PanDevice): A panos object for device
"""
try:
fw_conn.fetch_licenses_from_license_server()
print('Licenses retrieved from Palo Alto Networks')
return True
except:
print('WARNING: Not able to retri... | 52b62f45895f3a3a211d034dca491e2d8efab230 | 640,613 |
import re
def squashed(s):
"""Remove all of the whitespace from s."""
return re.sub(r"\s", "", s) | a6172c1cb1cfe796d23515e42ec6545fadbfbe14 | 640,616 |
def add_two(num):
"""Add two to num"""
return num + 2 | fb1bd640c0e4787c74ebdd2f503cf0170629fd8c | 640,618 |
from pathlib import Path
import pkg_resources
def get_path_of_data_dir() -> Path:
"""
get the path of the package data directory
:returns:
"""
file_path: str = pkg_resources.resource_filename(
"{{ cookiecutter.project_slug }}", "data")
return Path(file_path) | 4f4bc73003d1545ffdd9bce85bb3862ea39aa538 | 640,619 |
def get_ref_db_versions(ir_json_v6):
"""
This returns a dictionary that can be submitted for the referenceDatabasesVersions field of clinical report
When closing a case through the interpretation portal, only the genomeAssembly is included in this dictionary
This function will pull out the genomeAssembl... | 258dfdef14ccbcb59cb1dee303e3db0726a44686 | 640,620 |
def m_max_flight_class(seq):
"""
一年内飞机出行中最多机舱类型
:param seq: [商务舱乘机次数、公务舱乘机次数、经济舱乘机次数]
:return: 乘机次数==0 返回0 乘坐商务舱最多 返回business_class 乘坐公务舱最多 executive_class 乘坐经济舱最多 返回tourist_class
example:
:seq [2, 2, 3]
:return tourist_class
"""
temp_in... | 014777af7e4897699280f14a0ef9709f81656089 | 640,621 |
import argparse
from pathlib import Path
def _get_parser():
"""Set up argument parser for scripts."""
DESC = """
BIDS conversion and anonymization.
This workflow (1) runs heudiconv to convert dicoms to nifti BIDS format,
(2) defaces anatomical scans, (3) completes relevant metadata in the
dat... | aed3929f5f8cbcb5cb262a184f3a50e335072c0e | 640,623 |
def _DictToString(dictionary):
"""Convert a dictionary to a space separated 'key=value' string.
Args:
dictionary: the key-value dictionary to be convert
Returns:
a string representing the dictionary
"""
dict_str = ' '.join(' {key}={value}'.format(key=key, value=value)
for key, ... | 43579b56919fba318654d4d8bce25e093a67c687 | 640,625 |
import os
def cloud_init_installed():
"""Verify cloud-init installed"""
if os.path.exists('/etc/cloud/cloud.cfg'):
return True
return False | a042a160f4d7c568f3555746d775dfc332fd8d1f | 640,626 |
def validate_rages(ranges):
"""
Validates if weight ranges are feasible
:param ranges: dict
{
"assignment_name": [minimum_percentage, maximum_percentage]
}
:return: True if its feasible else False
"""
min_possible = 0
max_possible = 0
for assignment, range_item in rang... | c95651eb18d18ede5a1b8ff87bc8403056b03a55 | 640,627 |
def inverse(m):
"""Return matrix inverse.
@param m: matrix
@rtype:matrix
"""
return m.inverse() | 991478aa1dc62778dcb07b47fdc1250f98c985f0 | 640,629 |
def getAddrPort(host):
"""The host address may be entered in the format <address>:<port>
Return a tuple with host and port"""
elems = host.split(":")
if len(elems) > 1:
host = elems[0]
port = int(elems[1])
else:
port = 22
return [host, port] | 4a6ecd63b59d8cd71ebcec864b6073b8f282844d | 640,630 |
def join_url(url, *paths):
"""
Joins individual URL strings together, and returns a single string.
Usage::
>>> util.join_url("example.com", "index.html")
'example.com/index.html'
"""
to_rstrip = [url] + list(paths[:-1])
parts = [path.rstrip('/') for path in to_rstrip] + [paths[... | 872a894d9550ff60bafb22d809f1b407c6ea55a6 | 640,631 |
import platform
import sys
import struct
import os
import logging
def get_sys_info():
"""
平台基本信息收集
eg:
[('python', '3.6.0.final.0'),
('python-bits', 64),
('OS', 'Darwin'),
('OS-release', '15.6.0'),
('machine', 'x86_64'),
... | e5c1342b8243e858bb35f3d5d4835118a2808109 | 640,632 |
def create_edges(dc):
"""
Create edges (lines) connecting each pair of stars
Arguments
---------
dc : dictionary of constellations
Returns
-------
edges : list of all edges
"""
edges = []
for k,v in dc.items():
for i in v:
edges.append(i)
... | 7cb856f08abbf7c412d94449bfef17cf453e274c | 640,633 |
from typing import Union
from typing import List
def get_verbalization_ids(word: str, tokenizer, force_single_token: bool) -> Union[int, List[int]]:
"""
Get the token ids corresponding to a verbalization
:param word: the verbalization
:param tokenizer: the tokenizer to use
:param force_single_tok... | 9989d3489b1ba5d528303d0dc64179526749e086 | 640,634 |
def _create_message(problems: list, meta: dict) -> dict:
"""
Create Message to be sent
"""
HELLO_MESSAGE_TEMPLATE = 'Hi ! I hope you are doing well :) \nHere is some stuff you can do on your website to improve the performance of the *{} page* of *{}*: '
problems_formatted = ['*' + problem['rule'] + ... | eabaccace903b9b50b6afdf581aed6ca7742ba4c | 640,635 |
import re
def normalize_reference(s):
"""
Normalize reference label: collapse internal whitespace
to single space, remove leading/trailing whitespace, case fold.
"""
return re.sub(r'\s+', ' ', s.strip()).upper() | 15ff7e40ba318c2ac6de8cd3548f5c1980bd7be6 | 640,636 |
import json
import re
def generate_suppression(filepath: str) -> str:
"""Generate an example suppression document for the given file."""
return json.dumps(
{
"include": [],
"ignore": [
{
"pattern": f"{re.escape(filepath)}$",
... | 8ed58de36eba53e33f3029850fc67072f711b1d8 | 640,637 |
def token_to_bow(token, uniques):
"""
Returns the BoW representation of a NER token.
"""
vector = [-1]*len(uniques)
for i in range(len(uniques)):
if token != '' and token != 'nan' and uniques[i] in token:
vector[i] = 1
return vector | 3a66aa9113642c9aadbc2ab561879d28b17418e0 | 640,638 |
def update_bathrooms_slider(area):
"""
Update bathrooms slider to sensible values.
"""
return [1, min(int(area / 40) + 1, 5)] | ffb63e4ec0ff00d6bb6ab4105c816d688cf403ab | 640,639 |
def _clean_qp(query_params):
"""
Strip 'event.' prefix from all query params.
:rtype : QueryDict
:param query_params: dict self.request.query_params
:return: QueryDict query_params
"""
query_params = query_params.copy() # do not alter original dict
nspace = 'event.'
for key in query... | 4a0614b79d32b314dc29ad36a722e2a91077e899 | 640,640 |
import os
import shutil
def create_star_tmp(tmp_path:str, tmp_name:str='STAR'):
""" Ensure the specified directory is ready for use as the temp directory
for STAR.
In particular, it ensures that tmp_path exists and that tmp_path/tmp_name
does not exist (so STAR can create it).
N.B. This fun... | 8c8b0cd639ff6302ed4242ed1ad00ee1a99f05ef | 640,641 |
from pathlib import Path
def extend_path(path: Path, extension: str) -> Path:
"""Extends a path by adding an extension to the stem.
Args:
path (Path): Full path.
extension (str): Extension to add. This will replace the current extension.
Returns:
Path: New path with extension.
... | 65df8265b7a5b5896cbab9b13ef6b598b6132227 | 640,642 |
import subprocess
def get_gpu_memory():
"""Get the memory of the GPUs in the system
Examples:
>>> get_gpu_memory()
['8123 MiB', '8123 MiB', '8123 MiB', '8123 MiB']
"""
try:
out_str = subprocess.run(["nvidia-smi", "--query-gpu=memory.total", "--format=csv"], stdout=subprocess.P... | 1d491e36f0c6ee355048b5e8a862ee94f88c05c3 | 640,643 |
def get_html(html: str):
"""Convert HTML so it can be rendered."""
WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""
# Newlines seem to mess with the rendering
html = html.replace("\n", " ")
return WRAPPER.... | be2a2f7fa1d6e3c2643673442028521c796b70d2 | 640,644 |
def _insert_idxs(feature_centre, feature_size, dimensions):
"""Returns the indices of where to put the signal into the signal volume
Parameters
----------
feature_centre : list, int
List of coordinates for the centre location of the signal
feature_size : list, int
How big is the s... | a1e514cfb9625cb2d42055b4284f602e625ee15e | 640,645 |
def get_user_nick(user):
"""Returns the nickname of the passed user, the name otherwise"""
if user.nick is None:
return user.name
return user.nick | 504a233b372644144ece22696140aeb1660e13b1 | 640,646 |
def xdist_molar(xdist_mass, Massl, Massh):
"""
Calculates the molar concetration distilliat of liquid.
Parameters
----------
xdist_mass : float
The mass concetration distilliat of liquid, [kg/kg]
Massl : float
The molar mass of low-boilling component, [kg/kmol]
Massh : float
... | 8737a837f193a44e0028abe144c5f675464f897e | 640,648 |
def dimensionality(self):
"""Unit's dimensionality (e.g. {length: 1, time: -1})
This is a simplified version of this method that does no caching.
returns: dimensionality
"""
dim = self._REGISTRY._get_dimensionality(self._units)
return dim | e47580c83696c93371560a1cc077cfb7cb28f144 | 640,649 |
import math
def get_padding_elem(L_in: int, stride: int, kernel_size: int, dilation: int):
"""This function computes the number of elements to add for zero-padding.
Arguments
---------
L_in : int
stride: int
kernel_size : int
dilation : int
"""
if stride > 1:
n_steps = mat... | 9dc93dc1150ba955414e4210188c30e9ef4324b6 | 640,651 |
def calc_pct_reliability(df_pct):
"""
Calculates percent reliability of interstate and non-interstate network.
Args: df_pct, a pandas dataframe.
Returns: int_rel_pct, % interstate reliability.
non_int_rel_pct, % non interstate reliability.
"""
# Auto, Bus interstate
df_int = d... | e5c0806f21a42cfde5a9fe5d5af3906adfa775b3 | 640,652 |
def get_corr(d):
"""
Calculate correlation between SibSp and Parch
:param d: data frame
:return: rounded correlation
"""
return round(d.filter(items=['SibSp', 'Parch']).corr(method='pearson'), 2) | 2277a6d2d8965bab75b03d6c14fe24bcb112f626 | 640,653 |
def _remove_invalid_char(s):
"""Remove invalid and dangerous characters from a string."""
s = ''.join([i if ord(i) >= 32 and ord(i) < 127 else '' for i in s])
s = s.translate(dict.fromkeys(map(ord, "_%~#\\{}\":$")))
return s | 614fcc1aaf59c3be796ce3b0cbd69d9df6d9350c | 640,655 |
def get_diagnosis(driver):
""" Selects result diagnosis """
return driver.find_elements_by_css_selector("#List11 option") | 120519e64b7ddeb0aac5f8f5a823df361b3b5aa9 | 640,656 |
def lengthOfLongestSubstring(self, s: str) -> int:
"""
s1 = "abcabc"
s2 = 'dvdf'
s3 = 'bbbbb'
s4 = 'pwwkew'
sb = lengthOfLongestSubstring("", s4)
print(sb)
"""
pos = 0
maxlen = 0
curlen = 0
for i in range(len(s)):
"""
a b c a b c
... | 196697e244b3799c935b2de6c2540ee10a169442 | 640,657 |
def add_charge(line, charge):
"""
Add information on the charge to the output lines
"""
new_line = "{} {} {}".format(" ".join(line.split()[:3]), charge, " ".join(line.split()[3:]))
return new_line | 64c660198936808a6c07cef91cd714b29b5142c6 | 640,658 |
import json
import os
def load_hrv_keys_json():
"""Loads the content of the 'hrv_keys.json' file found in the 'pyhrv/files/' directory.
Returns
-------
hrv_keys : dict
Content of the pyhrv/files/hrv_keys.json file in a dictionary
"""
return json.load(open(os.path.join(os.path.split(__file__)[0], './files/hrv... | 371dc4063ec86873be4daef28c100d2bdbb2281b | 640,659 |
def is_prime(n):
"""See if a number is a prime number."""
for i in range(2, int(n**0.5) + 1):
if not n % i:
return False
return True | 5102e8a5822ee8bcd0b37cf9fda40335ef1d1870 | 640,660 |
import argparse
def create_parser():
""" parse the input parameters
:return dict: parameters
"""
# SEE: https://docs.python.org/3/library/argparse.html
parser = argparse.ArgumentParser()
parser.add_argument(
'-e', '--path_experiment', type=str, required=True, help='path to the experime... | ce41db6983fbfce0c7939b478b600a3b799d67b7 | 640,662 |
def _doMatchExcept1(inv, atoms):
""" Helper function to check if two atoms in the list are the same,
and one not
Note: Works only for three atoms
Arguments:
- inv: atom invariants (used to define equivalence of atoms)
- atoms: list of atoms to check
Return: atom that i... | 639774acbc86981ca6a241987ef7a95855793c35 | 640,663 |
import uuid
def case_generator(uuid_val=None):
"""
----
examples:
1) case_generator('a55eff11-ed51-ecb37-ccba') -> 'A55EFF11ED'
----
Use uuid to create test-case unique name
:return:
"""
uuid_val = uuid_val if uuid_val is not None else str(uuid.uuid4())
return str(uuid_val).upp... | 426c28ce3ab5e4be5ccaa4cb9904a9fb807cd29c | 640,664 |
import typing
def unpack_key_value_pair(entry) -> typing.Tuple[object, object]:
"""ensure the given entry can be unpacked into a key/value pair
:param entry: an iterable element with exactly two elements
:return: a tuple containing the key value pair
:raises: ValueError when the entry can't be unpack... | 8094e4d58439c6ea91fafd12b06b3c0104af003c | 640,665 |
import os
def exec_mariadb_stat2(query, db, filename=None, verbose=True):
"""Query MariaDB."""
cmd = 'mysql --host analytics-slave.eqiad.wmnet {0} -e "{1}"'.format(db, query)
if filename:
cmd = cmd + " > " + filename
if verbose:
print(cmd)
ret = os.system(cmd)
return ret | 6d04bb4a0cbbacc6865b564a00aff5ce13624e57 | 640,666 |
import shlex
import subprocess
def valid_system_python():
"""
:return: full path of python executable if a python at /usr/bin/python3 or /usr/bin/python is
available that is version 3.4 or newer, else None if not found
"""
cmd = "import platform; v = platform.python_version_tuple(); "\
... | 3751cdb78603d2f9e1b16777f4090a9f2598eae8 | 640,667 |
def value_if_found_else_key(some_dict, key):
"""Lookup a value in some_dict and use the key itself as fallback"""
return some_dict.get(key, key) | c02f50851908df0aa03c1c850f1e52f710bce3ce | 640,669 |
def unitstep(t):
"""Returns the unit step function: ``u(t) = 1.0 if t>=0 else 0``"""
return 1.0 if t >= 0 else 0.0 | 5f9d39cccdc673cff8f1c691499cc5b3689689f5 | 640,670 |
def getRowMarker(f, year):
""" Get the row marker for given year
(where the most recent update left off) and return.
Returns 0 if doesn't exist. """
dset = f['data']
marker = 0
if "_row_marker" in dset.attrs:
row_marker = dset.attrs["_row_marker"]
# returns [year, row]
... | ccd1857f23d5cb70ab869719b7bc106f182b778e | 640,671 |
def list_to_csv(wlist, outfile):
"""
Writes Python list of lists, tuples, or characters to csv file, one
element per row
"""
if isinstance(wlist[0],list) or isinstance(wlist[1],tuple):
wlist = [(',').join([str(el) for el in r]) for r in wlist]
else:
wlist = [str(el) for el in... | 03d64701963f51c0c35debc76e5749153a099083 | 640,672 |
def strokes_to_lines(strokes):
"""Convert stroke-3 format to polyline format."""
x = 0
y = 0
lines = []
line = []
for i in range(len(strokes)):
if strokes[i, 2] == 1:
x += float(strokes[i, 0])
y += float(strokes[i, 1])
line.append([x, y])
l... | 61eafa7fdc9e010220251fdf3ced0a0bf6286afc | 640,673 |
def report(securify_target_output):
"""Report findings.
"""
return 0 | 6a16162c3f25ec4669390ed3687273ffbbe15020 | 640,674 |
def prepare_parameters(model, optim_args):
"""Produce two groups of parameters:
- the pretrained parameters (PlacesCNN, ResNet50), and
- the other parameters (not pretrained)
This allows us to set the lr of the two groups separately
(other params as the lr given as input, pretrained params a... | 26ed9ab774d191af100bfea800d6cbe59668d2dc | 640,675 |
def calculate_measureland_qualifier_flag_overall(row):
"""Calculate the overall data quality flag taking into account the others that have been assigned."""
mqf_tuple = (row['measureland_qualifier_flag_speed'],
row['measureland_qualifier_flag_distance'],
row['measureland_quali... | ab02c36bc66cfd851addfcc828f1b1aec1264eb2 | 640,676 |
def convert_paypal_row(row):
"""
>>> convert_paypal_row(['02/11/2015', '03:06:30', 'GMT', 'Name', 'Type', 'Status', 'GBP', '-7.3', 'Reciept ID', '0.00'])
['02/11/2015', '-7.30', 'Name']
>>> convert_paypal_row(['02/11/2015', '03:06:30', 'GMT', 'currency conversion', 'Type', 'Status', 'USD', '-7.3', 'Reci... | c15664126b0b255995cd49bda83c79b4cd46f32b | 640,678 |
def df_uniques(df):
"""Find unique values for each dataframe columns"""
result = {}
for x in df.columns:
result[df[x].name] = df[x].unique().tolist()[0:5]
return result | edbb293cddc282ec5f71b04b374b8098031adc8f | 640,679 |
def __chr_hex(c):
"""xx"""
return str(hex(ord(c))) | 1d1ff0ed194c852b2679441566eaf45ebbc0fc62 | 640,680 |
def fake_func_has_metadata(testcase, resource_name):
""" Fake the behaviour of ‘pkg_resources.Distribution.has_metadata’. """
if (
resource_name != testcase.version_info_filename
or not hasattr(testcase, 'test_version_info')):
return False
return True | fa767f719b91256311c82cbe04486eff5bfc8b96 | 640,681 |
def uncomposekey(prefix, key):
"""Remove a prefix from a composite key.
Example: uncomposekey("attr1.attr2", "attr1.attr2.attr3.attr4") == "attr3.attr4"
"""
if " " in prefix or " " in key:
raise NotImplementedError()
prefix, key = prefix.split("."), key.split(".")
while prefix:
a, b = prefix.pop(0)... | 748b1f03dcdb46483d54b3aac44523911b450da0 | 640,682 |
def fw_action(raw):
"""Normalize firewall action
Gives back a value between allow, deny, reject and other
"""
lower = raw.lower()
if lower in ['allow', 'deny', 'reject']:
return lower
return 'other' | 3cc1d93712dba75e501d915a4c6319b038073aec | 640,683 |
def memoize(function):
"""
Simple memoization.
This assumes all arguments implement a.tostring() function.
This holds for numpy arrays.
"""
memo = {}
def new_function(*args, **kwargs):
try:
return memo[tuple([x.tostring() for x in args])]
except KeyError:
... | de782703141211f8ef91632a4954d1469ca50f01 | 640,684 |
import torch
def split_tensor_pos(tensor):
""" Splits tensor into positive and negative terms """
zeros_like = torch.zeros_like(tensor)
pos_tensor = torch.max(tensor, zeros_like)
neg_tensor = torch.min(tensor, zeros_like)
return pos_tensor, neg_tensor | e3f1b013949b38a88185aeaaec45cb60891753a2 | 640,685 |
import random
def randomly_true(probability: float) -> float:
"""
Return True with a given probability, False otherwise.
"""
return random.uniform(0,1) < probability | 835fc2367b8fca9d524aaec110d523d4f55f397f | 640,686 |
import subprocess
def run_cmd_captured(cmd: list[str]):
"""Run a command, echoing it to stdout, capturing command output and returning it"""
print(f"[CMD] {' '.join(cmd)}")
res = subprocess.run(cmd, capture_output=True)
return res.stdout | 0ce259a45c562eaaaead8313b39c8dab5225caca | 640,687 |
import os
def _is_inverse_label_transform():
"""Returns True if if it's running in inverse label transform."""
return os.getenv('TRANSFORM_MODE') == 'inverse-label-transform' | 4c8f4f81054cd94262d094c4b99a7e448ed084ac | 640,688 |
def lrange():
"""Lesion indices."""
return range(1, 5) | e34f68ccff0ca2c8f93439171a967e37103b3f9f | 640,689 |
def GetMetaClass(mc):
""" Shows info about a given OSSymbol
"""
out_string = "{0: <5d}x {1: >5d} bytes {2:s}\n".format(mc.instanceCount, mc.classSize, mc.className.string)
return out_string | defd2b6d35e9581e175374db2ec118a0f9e49ea4 | 640,690 |
import random
def __choose_state(state_map):
"""
Choose the next state randomly
"""
choice = random.random()
probability_reached = 0
for state, probability in state_map.items():
probability_reached += probability
if probability_reached > choice:
return state
ret... | 681c3ef19d3bec7dd8ac3882cf44ce6328e3c3f2 | 640,691 |
def numeric_filter(operation, value, column, df):
"""Filters a data column numerically.
Arguments:
operation: Operator used to filter data (e.g. ">", "<", "==", ">=", "<=", "!=")
value: Operand
column: String for column name
df: DataFrame
Returns: Boolean column that indicates whether each... | 868907d2fed5947c0974896af73a9277fcef0ae8 | 640,693 |
import os
def skip(*filenames):
"""
Detects if the data preparation has been already done.
If the preparation has been done, we can skip it.
Returns
-------
bool
if True, the preparation phase can be skipped.
if False, it must be done.
"""
for filename in filenames:
... | b807ddb9172bf212259c6de5b989119b6800de41 | 640,694 |
def webpage_attribute_setter(attr):
""" Helper function for defining setters for web_page attributes, e.g.
``set_foo_enabled = webpage_attribute_setter("foo")`` sets
a value of ``webpage.foo`` attribute.
"""
def _setter(self, value):
setattr(self.web_page, attr, value)
return _setter | 9c5d0f7ec8d7cec531c414071088a4f848628027 | 640,695 |
def meanOffNadirViewAngle(xmlroot):
"""Get the mean off nadir view angle from the xml."""
return float(xmlroot.find('IMD/IMAGE/MEANOFFNADIRVIEWANGLE').text) | 3df2a26dceabb36d944040fd31541339e1ead183 | 640,696 |
def no_none(decorated):
"""decorator for a generator to discard/filter-out None values"""
def _func(*args, **kwargs):
"""wrap generator"""
for value in decorated(*args, **kwargs):
if value is not None:
yield value
return _func | 8b98fa96646f762a20cc3bc768f5464fd55b37d1 | 640,697 |
def truesi(xs):
""" indices for which x[i] is True """
return [i for i, x in enumerate(xs) if x] | a037f61eddb7a77e536a20843b587ccb62bd7d4e | 640,698 |
def create_event(event_type, data):
"""Return a dictionary containing the properties required when defining an
event.
Keyword arguments:
event_type -- the type of event, used to distinguish multiple events apart.
data -- a dictionary of key/value pairs containing custom data.
"""
return {
... | 5bff5b0b860a56c00ab83928939369a7e339ad73 | 640,699 |
def normalize_port_no(port_no):
"""Normalize port number value to int or string."""
if isinstance(port_no, int):
return port_no
if isinstance(port_no, str):
try:
# Convert decimal and hexadecimal port number strings.
return int(port_no, 0)
except ValueError:
... | dc3ac83e14811d97048c17e1a13662f03171b962 | 640,700 |
def resize_bbox(bbox, in_size, out_size):
"""
Resize bounding boxes according to image resize.
:param bbox (numpy.ndarray): An array that has a shape (R, 4),
'R' is the number of the bounding boxes.
'4' indicates the position of the box, which represents
(y_min, x_min, y_max, x_max)
... | e6d1f97e2625f8dee78fe78fe608087a52701fbe | 640,701 |
import torch
def cosine_dist(x, y):
""" Compute consin dist
Input:
x: embedding of size M x D
y: embedding of size N x D
Output:
dist: pairwise distance of size M x N
"""
xy = x.mm(y.t())
x_norm = torch.norm(x, p=2, dim=1, keepdim=True)
y_norm = torch.norm(y, p=2,... | d5d4a4a197b645d75a67b3f21e41bb06947b3f1f | 640,702 |
def override(interface_class):
"""
Method to implement Java-like derived class method override annotation.
Courtesy of mkorpela's answer at
http://stackoverflow.com/questions/1167617/in-python-how-do-i-indicate-im-overriding-a-method
"""
def override(method):
assert (method.__name__ in ... | 3f2b4f21e7602e58579e2681aa32f4d922466bd2 | 640,703 |
def _add_suffix(params, model):
"""
Add suffixes to a list of parameters.
Suffixes includes derivatives, power2 and full
"""
params_full = params.copy()
suffix = {
"basic": {},
"derivatives": {"derivative1"},
"power2": {"power2"},
"full": {"derivative1", "power2",... | 6f730284243f015741a1cbff8468513511ba9ba5 | 640,706 |
import re
def clean_tweets(s):
"""Lowercase and remove punctuation from a pd.Series object containing text.
Args:
data (pd.Series-like): a series containing text"""
result = s.apply(str.lower)
punct_re = r'[^a-zA-Z0-9\s]'
result = [re.sub(pattern=punct_re, repl=' ', string=i) for i in... | cdc3e56cd9b092ba2f4950cfd2c9566f5b67d2ac | 640,707 |
def attribute(property, *args, **kwargs):
"""Methodcaller, attrgetter logic."""
def attribute(object):
"""Return an attrgetter or methodcaller."""
object = getattr(object, property)
return object(*args, **kwargs) if args or kwargs or callable(object) else object
return attribute | 00530d317860534345923e41b0e82ce59e01cdb4 | 640,708 |
def strip_spaces_list(list_in, strip_method="all"):
"""
Remove spaces from all items in a list
:param list_in:
:param strip_method: Default: 'all' for leading and trailing spaces.
Can also be 'leading' or 'trailing'
:return: List with items stripped of spaces
"""
if strip_method == "all... | f6d60e8a847f7f339784066e39807caaa63c426c | 640,709 |
import os
def describe_os(*paths):
"""Read the Operating System Description from `os-release`
This creates a string describing the running operating-system name and
version. It reads the information from the path array provided as `paths`.
The first available file takes precedence. It must be formatt... | 5802aeec5b8179e3b7cadfc69048a468ff30ca37 | 640,710 |
def LinearReconstruct( u_stencil ):
"""Linear reconstruction with linear weights. This reconstructs u_{i+1/2}
given cell averages \\bar{u}_i at each neighboring location.
See (2.14) in `High Order Weighted Essentially Nonoscillatory Schemes for
Convection Dominated Problems'.
"""
uim2, u... | 9564cedf70dbf59a5997960f4db1153f7a90d21e | 640,711 |
def compute_avg_wmd_distance(contexts1, contexts2, gensim_obj):
"""
Compute an average word metric distance
:param contexts1: List of ContextAndEntities objects extracted from Document 1
:param contexts2: List of ContextAndEntities objects extracted from Document 2
:param gensim_obj: a Gensim object... | 4cf65eab5ff15cb96560d01a5e4268874a9f3c01 | 640,712 |
import re
def clean_emojis(line):
"""Escape custom emojis."""
return re.sub(r"<(a)?:([a-zA-Z0-9_]+):([0-9]+)>", "<\u200b\\1:\\2:\\3>", line) | 62d64f22fc1a105c5eb60ace61e12e7707834696 | 640,713 |
def reaction_has_internal_standard(message):
"""Whether any reaction component uses the internal standard role."""
for reaction_input in message.inputs.values():
for compound in reaction_input.components:
if (compound.reaction_role ==
compound.ReactionRole.INTERNAL_STANDA... | f4ad874683b2822d1c1d801ce2eab0148fb6b563 | 640,714 |
from typing import Dict
import torch
def default_fn(x, models, **kwargs) -> Dict[str, torch.Tensor]:
"""
The default inference function for [BaseAdapter][pytorch_adapt.adapters.BaseAdapter].
"""
features = models["G"](x)
logits = models["C"](features)
return {"features": features, "logits": lo... | b020a629385abf410c30a1850fce4b04c8e181e2 | 640,715 |
def get_indented_block(prefix_lines):
"""Returns an integer.
The return value is the number of lines that belong to block begun
on the first line.
Parameters
----------
prefix_lines : list of basestring pairs
Each pair corresponds to a line of SHPAML source code. The
first e... | 82285e2e249cc7cefe052eebd725b67a182061d7 | 640,716 |
def get_image_id(s,v,i):
"""
image_id = XX(set)XXX(vid)XXXXX(image)
"""
return s*(10**8)+v*(10**5)+i | 29d068a828a298b34c22b47143c12c70c83921c0 | 640,717 |
def merge_dico_in_first(d1, d2):
"""
Merge dictionary d2 in d1.
"""
for k, v in d2.items():
if k in d1:
raise ValueError(f"Key {k} should not be in d1")
else:
d1[k] = v
return d1 | 1de21618882eccf2e6482271cc98497060e43669 | 640,718 |
import torch
def collate_fn_long_range(batch):
"""
Puts each data field into a tensor with outer dimension batch size
:param batch:
:return:
"""
pos, out_input, out_label = zip(*batch)
out_input = torch.stack(out_input, 0)
out_label = torch.stack(out_label, 0)
return pos | 20037ed4286f765dc093ddb3d72faf6ecf80e6a1 | 640,719 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.