content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Union
from typing import List
from typing import Tuple
def deduplicate(x: Union[List, Tuple]):
"""Remove duplicates in a list or tuple; preserves original order."""
return type(x)(dict.fromkeys(x)) | ad47ec846f08feadb6c89be31205be536a469d8f | 689,126 |
def sizeof(bsObj):
""" Size of BotSense object in bytes. Size is contextual by object type. """
return bsObj.__sizeof__() | 70c55a9002e336d2d827ee21d04260dfc328d7fc | 689,127 |
import configparser
import os
def read_config(config_path):
"""
Description: Reads config from config file. Needs to be executed first
Arguments:
config_path: path to config file
Returns:
output_path: Path to the folder of the output data
"""
config = configparser.ConfigPars... | caa15ad03b7d339726698f7051d89b59290c7c49 | 689,128 |
def extract_variable_index_and_name(string):
"""Takes a string of the form variable_name[index] and
returns the variable_name, and index.
The method will return a `ValueError` if the string does not
contain a valid set of access brackets, or if the string contains
multiple bracket accessors.
P... | 0d31763f5ed96ec99b35e3ef94d030c1ddeb6268 | 689,129 |
import json
def json_409():
""" fixture to return 409 body"""
body = json.dumps({'code': 'incompatibleClientVersion',
'message': 'the version of client library used'
' is not compatible with this server',
'versionChecked': True})
... | 891d73b8d7cb15c44bce0f5c9b6fec62cf78ceb8 | 689,130 |
import pickle
def download_pathways(path_to_graphs, path_to_graphs_names, path_to_graphs_classes):
"""
Function loads dict of graph that was saved by docker container to graphs.pickle
:param outdir: path to file with graphs
:return: dict of graphs
dict of names of pathways
di... | 079d4a3c360da0c3f4a65f48ad2d6ec5d1f2177d | 689,131 |
def count_violations_veber(num_rotatable_bonds, tpsa):
"""Veber DF, Johnson SR, Cheng HY, Smith BR, Ward KW, Kopple KD (June 2002).
"Molecular properties that influence the oral bioavailability of drug candidates".
J. Med. Chem. 45 (12): 2615–23.
"""
n = 0
if num_rotatable_bonds > 10:
n ... | 5c672943cd27359f7312a7715e4a96ff25e15c1e | 689,133 |
async def start_entry() -> dict:
"""Create a mock start_entry object."""
return {
"id": "start_entry_1",
"race_id": "race_1",
"startlist_id": "startlist_1",
"bib": 1,
"name": "name names",
"club": "the club",
"scheduled_start_time": ("2021-08-31T12:00:00")... | 3faf34ebd8000e2aafb872a6abf929ed0d9c9543 | 689,134 |
def myfunc(_a, _b):
"""Add two numbers."""
return _a + _b | 7177568b60056ea28b6c880eaba8d05441b14c96 | 689,136 |
def is_one_to_one(table):
"""A staticmethod that takes a codon table as a dictionary and returns
True if it represents a One-To-One genetic code and False otherwise.
A one-to-one code is defined as a code in which every amino acid is
represented with exactly one codon. This defines an unamb... | d90f3cfc69a7ded4b93b8e15e2175234d96ca7a7 | 689,137 |
def shortest_distance(graph, v1, v2):
"""
this function computes the length of the shortest path
in graph between v1 and v2
Parameters:
graph: a graph described as a dictionary of dictionaries
v1: the source vertex
v2: the destination vertex
Returns:
int: the length of the s... | 3d05697103ff97656225e7679d239330fe9abed3 | 689,138 |
def build_udf_path(root, name):
"""
A function to build a complete, valid UDF path based on a root directory
and a name.
Parameters:
root - The root directory name.
name - The name for the UDF entry.
Returns:
A valid, absolute UDF filename.
"""
if root and root[0] == "/":
... | db40db84588d6b69b3d173aa4287d9f9e1fce216 | 689,139 |
def mex(L):
"""Return the minimum excluded value of a list"""
L = set(L)
n = 0
while n in L:
n += 1
return n | c35205dd22ca47e28141ae56aba2827065abf164 | 689,141 |
def sort_tups(seq):
"""Nicely sorts a list of symbolic tuples, in a way we'll describe later."""
return sorted(seq,key=lambda k:(-len(k),k),reverse=True)[::-1] | fc74959bc9a903331ffff1e1d01f52c8ffc25b4f | 689,142 |
import fcntl
import termios
import struct
def terminal_width():
"""Returns the terminal width
Tries to determine the width of the terminal. If there is no terminal, then
None is returned instead.
"""
try:
exitcode = fcntl.ioctl(
0,
termios.TIOCGWINSZ,
... | c3c45dfb6c24d830f15eb3f5e631e5804566d17a | 689,143 |
def clip_by_tensor(t, t_min, t_max):
"""
clip_by_tensor
:param t: tensor
:param t_min: min
:param t_max: max
:return: clipped tensor
"""
t = t.float()
result = (t >= t_min).float() * t + (t < t_min).float() * t_min
result = (result <= t_max).float() * result + (result > t_ma... | 81dacd171c0dbbc39568bd38747813a242d89899 | 689,144 |
import six
def ggb_test(func):
"""Wrapper to test function.
:param func: test function
:return: wrapper function
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
ret = func(*args, **kwargs)
return ret
return wrapper | 230411509cb88f2dce694663338ab64546cf5e47 | 689,145 |
def _get_magnitude(string):
"""
Get the magnitude of the smallest significant value in the string
:param str string: A representation of the value as a string
:returns: The magnitude of the value in the string. e.g. for 102, the magnitude is 0, and for 102.03 it is -2
:rtype: int
"""
split_... | 03a3abc46aca847489431ab86aceab1d59f9c626 | 689,146 |
def __get_pivots(diameter, x, y):
"""
Get the x-intercepts and y-intercepts of
the circle and return a list of pivots which
the coin lies on.
"""
pivots = []
radius = diameter / 2
sqval = radius**2 - y**2
if sqval > 0: # no imaginary numbers!
sqrt = sqval**(0.5)
piv... | a82c465d82e428797bf98d4ab005335005d44368 | 689,148 |
def handle_special(self, req):
"""Mock this on ResponseThreadPool so it doesn't touch anything in
`commands` package.
"""
if "filename" in req.skwargs or "streamed" in req.skwargs or "chunked" in req.skwargs:
return True
return False | 02fa18ebcf582fb893bca0c5bcd0afb90022d7e7 | 689,149 |
def create_filename(lecture_num, title):
"""
Create a filename from a title string.
Converts spaces to dashes and makes everything lowercase
Returns:
lecture filename
"""
return "lecture-{:02d}{}.md".format(int(lecture_num), "" if not title else '-' + title.lower().replace(" ", "-")) | 2370a63fb69b8cf0ddd431745d01201f2bafe6c0 | 689,150 |
def get_line(s3_autoimport):
"""Build a list of relevant data to be printed.
Args:
s3_autoimport (S3ProjectImport): instance of
S3 autoimport
Returns:
list(str): list of relevant data to be printed
"""
return "\t".join(
[
str(s3_autoimport.id),
... | 0624af6e6ce02f23baedda01fb30c4c62c01b7e4 | 689,153 |
def FindPhaseByID(phase_id, phases):
"""Find the specified phase, or return None"""
for phase in phases:
if phase.phase_id == phase_id:
return phase
return None | 5544d47139a00cb6e0e33486031ff49796092907 | 689,154 |
def dataToString(var, data):
"""Given a tuple of data, and a name to save it as
returns var <- c(data)
"""
#convert data to strings
d = [str(d) for d in data]
return "%s <- c(%s)" % (var, ",".join(d)) | dcfb8e443f0a8f8c783047190822c7194104fc44 | 689,155 |
def alt_ternary_handle(tokens):
"""Handle if ... then ... else ternary operator."""
cond, if_true, if_false = tokens
return "{if_true} if {cond} else {if_false}".format(cond=cond, if_true=if_true, if_false=if_false) | d41d4e67f66282648cc13f4e678c8e712c41e01c | 689,156 |
def create_LUT_array(alpha):
"""
Funkcja tablicujaca wartosci pikseli w zaleznosci od parametru alpha.
@param alpha - wspolczynnik kontrastu
@return LUT_array - tablica [lista] LUT
"""
# Przygotuj pusta tablice [liste] LUT
LUT_array = []
# wzor na wartosc i-tego elementu tablicy:
# 0 ... | 8db3b3b14d6f6729ea02887547798f13b8667669 | 689,157 |
def extract_volume_number(value):
"""Extract the volume number from a string, returns None if not matched."""
return value.replace("v.", "").replace("v .", "").strip() | 50b25b9c33ae62f2e61165ca36648cbe09e39883 | 689,158 |
def get_full_exception_name(exception: Exception) -> str:
"""Get the full exception name
i.e. get sqlalchemy.exc.IntegrityError instead of just IntegrityError
"""
module = exception.__class__.__module__
if module is None or module == str.__class__.__module__:
return exception.__class__.__nam... | a188427bbf12d861990c784c65f4d524734ba787 | 689,159 |
def get_winning_party_info(result):
"""Get winning party result."""
return result['by_party'][0] | b4792b6588ecbf26b643f047f624234d789eb6f7 | 689,160 |
def prettyTimeDelta (seconds):
"""
Pretty-print seconds to human readable string 1d 1h 1m 1s
"""
seconds = int(seconds)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
s = [(days, 'd'), (hours, 'h'), (minutes, 'm'), (se... | 9c52730208782c628ddc26ee7b3570b9f962eb7d | 689,161 |
def _convert_snake_to_pascal(snake_case_string: str) -> str:
"""
Convert a string provided in snake_case to PascalCase
"""
return ''.join(word.capitalize() for word in snake_case_string.split('_')) | 41fd25da7fa5b6f120fae63aafb5bed1438256bd | 689,162 |
def read_file_str(file_path: str) -> str:
"""
Read the target file string.
Parameters
----------
file_path : str
Path of target file.
Returns
-------
file_str : str
The target string read.
"""
with open(file_path, mode='r', encoding='utf-8') as f:
file_s... | 01ac8056896b7b40102c032e7a9b132cec0cbb6b | 689,163 |
def cut_year(plain_date):
"""
cut out the first four year number from a 'yyyymmdd' formatted date
write as a separate function because the apply(lambda x) one doesn't
work as expected
"""
return plain_date[4:] | 6524e3ea03d8be4859381949d6bada4f204b6f6c | 689,164 |
def groundStateEnergy(energies):
"""Return the energy of the half-filled ground state.
The list of electronic state energies is assumed to be sorted in ascending
order."""
chain = len(energies)
if chain % 2 == 0:
return 2*sum(energies[0:(chain/2)])
else:
return 2*sum(energi... | 177907b64f74596d4229cba5f22241294eea0f0f | 689,165 |
def get_fs(module, blade):
"""Return Filesystem or None"""
fsys = []
fsys.append(module.params["name"])
try:
res = blade.file_systems.list_file_systems(names=fsys)
return res.items[0]
except Exception:
return None | adfd7117a46c8065baf9b6cd706dbef54748c522 | 689,167 |
def getHlAtt(app, n, highlights, isSlot):
"""Get the highlight attribute and style for a node for both pretty and plain modes.
Parameters
----------
app: obj
The high-level API object
n: int
The node to be highlighted
highlights: set|dict
The nodes to be highlighted.
... | 5e6119cd8fb5622589d84e8831e3e12a02d673c6 | 689,168 |
def dir_tree_find(tree, kind):
"""Find nodes of the given kind from a directory tree structure
Parameters
----------
tree : dict
Directory tree.
kind : int
Kind to find.
Returns
-------
nodes : list
List of matching nodes.
"""
nodes = []
if isinstan... | 935021a2daae3cc53f1e9a44961643171c5a5fc2 | 689,169 |
import base64
def base64_auth(login: str, secret: str) -> str:
"""
The function returns BASE64 encoded string for AUTH.
:param login: login
:param secret: password
:return:
"""
auth_str = f"{login}:{secret}"
auth_b64 = base64.b64encode(auth_str.encode(encoding='utf-8'))
return auth... | 4a0725c95c6e6c439d3e2d717e2e3ad6a0dad47f | 689,170 |
def solve_tridiag(a, b, c, d, overwrite_bd=False):
"""
Solve a tridiagonal equation system using the Thomas algorithm.
The equivalent using scipy.linalg.solve_banded would be:
ab = np.zeros((3, len(a)))
ab[0, 1:] = c[:-1]
ab[1, :] = b
ab[2, :-1] = a[1:]
x = scipy.li... | af25c811fa1b74b571995ddc531e31bda9efbf59 | 689,171 |
def rectangle_centroid(rectangle):
"""
get the centroid of the rectangle
Keyword arguments:
rectangle -- polygon geojson object
return centroid
"""
bbox = rectangle['coordinates'][0]
xmin = bbox[0][0]
ymin = bbox[0][1]
xmax = bbox[2][0]
ymax = bbox[2][1]
xwidth = xmax ... | 25d8028afff308dc06ea033717dd1d02995696d4 | 689,172 |
def intToDBaseTuple(x, dim, D):
"""
Transfer a integer to a base-D fixed-length tuple of digits.
Parameters
----------
x : int
A positive integer to be transformed into base-D.
dim : int
The length of digit tuple as the output.
D : int
The base of the digit tuple.
... | 7f5567aa92602743dfccae026d6c266049092e43 | 689,173 |
def is_device_memory(obj):
"""All CUDA memory object is recognized as an instance with the attribute
"__cuda_memory__" defined and its value evaluated to True.
All CUDA memory object should also define an attribute named
"device_pointer" which value is an int object carrying the pointer
value of th... | 7c4a249813191ba15153ebd5b3ea435b8c13c996 | 689,174 |
def list_product(num_list):
"""Multiplies all of the numbers in a list
"""
product = 1
for x in num_list:
product *= x
return product | 3d6d56f03817f9b4db0e7671f6c95c229a14a042 | 689,175 |
def multiChoiceParam(parameters, name, type_converter = str):
""" multi choice parameter values.
:param parameters: the parameters tree.
:param name: the name of the parameter.
:param type_converter: function to convert the chosen value to a different type (e.g. str, float, int). default = 'str'
:re... | 380c4c2ef7104695b272a407a03fe5d51288f4ad | 689,176 |
import json
def get_params_of_task(task, exclude=[]):
"""
for some reasons luigi encode dict params to json. we revert it here
:param task:
:param exclude:
:return:
"""
# undo encoding of dicts to string
params = task.to_str_params(only_significant=True, only_public=True)
# each va... | d8054811cf9ab72540d6c8d15f22043dbbc3f910 | 689,177 |
def lin_interp(x, x0, x1, y0, y1):
""" Simple helper function for linear interpolation. Estimates the value of y at x
by linearly interpolating between points (x0, y0) and (x1, y1), where x0 <= x < x1.
Args:
x: Float. x-value for which to esrimate y
x0: Float. x-value of point 0
... | 07efe42eda983bb9221c26df73bc260204830c53 | 689,179 |
def output_size(W, F, P, S):
"""
https://adventuresinmachinelearning.com/convolutional-neural-networks-tutorial-in-pytorch/
:param W: width in
:param F: filter diameter
:param P: padding
:param S: stride
:return:width out
"""
return (W-F+2*P)/S + 1 | 06bb0e4c6d8b6d46b7ddc4300dd925a8203e9b16 | 689,180 |
import pickle
import os
def load_statuses():
"""
Loads statuses from pickle
:return: Dictionary of statuses
"""
try:
return pickle.load(open(os.path.join("config", "statuses.p"), "rb"))
except (OSError, IOError) as e:
return {} | 2a75260de51ba94f6c508518cb9b8476a43b5c84 | 689,181 |
import torch
def out_degree(adjacency: torch.Tensor) -> torch.Tensor:
"""Compute out-degrees of nodes in a graph.
Parameters
----------
adjacency
Adjacency matrix.
Shape: :math:`(N_{nodes},N_{nodes})`
Returns
-------
torch.Tensor
Nodewise out-degree tensor.
... | 92eec222cf125135b6bcd711dcef6cb7144f2a59 | 689,182 |
import six
import re
def is_valid_mac(mac):
"""Verify the format of a MAC addres."""
if not mac:
return False
m = "[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$"
return isinstance(mac, six.string_types) and re.match(m, mac.lower()) | 920d6199b9a8b6c6688953257c72bad4966c1654 | 689,183 |
def find_path(start, goal, unit):
"""A very basic path finding algorithm (Breadth First Search) that when given a starting Tile, will return a valid path to the goal Tile.
Args:
start (Tile): the starting Tile
goal (Tile): the goal Tile
unit (Unit): the Unit that will move
Returns:
... | 7930295693cc9d2f35e8b67fa1804104f86bef5c | 689,184 |
def is_fasta_file_extension(file_name):
"""
Check if file has fasta extension
Parameters
----------
file_name : str
file name
Returns
-------
bool
True if file has fasta extension, False otherwise
"""
if file_name[-4:] == ".fna":
return True
elif file_name[-4:] == ".faa":
return True
elif file_nam... | 711267ab304ca188b03f3a7e816a0df70c3f4fa3 | 689,185 |
from typing import Union
def _get_remainder(code: Union[list, int]) -> int:
"""Calculate remainder of validation calculations.
:param Union[list, int] code: input code
:return: remainder of calculations
:rtype: int
:raises TypeError: if code is not a list or an integer
"""
# raise an exc... | c235512d66e1041ab30c376b1e7682a085d27dcc | 689,186 |
def _is_group(token):
"""
sqlparse 0.2.2 changed it from a callable to a bool property
"""
is_group = token.is_group
if isinstance(is_group, bool):
return is_group
else:
return is_group() | 91b8a9a18831c46a878fbbacf72a0ebe9f4f4fdf | 689,187 |
import textwrap
import argparse
def get_argparser():
"""Returns an `ArgumentParser()` for parsing command line options."""
example_text = textwrap.dedent( # ignore common whitespace for all lines
"""
examples:
ghstar gokulsoumya/ghstar
ghstar jlevy/the-art-of-command-line
... | ac288cd265910b30f4e8a0b379418d9c36609b41 | 689,188 |
import warnings
def force_connect(client):
"""
Convenience to wait for a newly-constructed client to connect.
Taken from pymongo test.utils.connected.
"""
with warnings.catch_warnings():
# Ignore warning that "ismaster" is always routed to primary even
# if client's read preferenc... | a9a49ff79108f38a10215aaab3ee371b860f6270 | 689,190 |
def check_for_gold(bag, bag_rules):
"""Check if a shiny gold bag can be inside a bag"""
rule = bag_rules[bag]
if len(rule.keys()) == 1 and 'other bags' in rule.keys():
return False
elif 'shiny gold bags' in rule.keys():
return True
else:
for n in rule.keys():
retu... | 2fbc315d679b0bc72c331e3f45b878da41b690c1 | 689,191 |
def read_names(path):
"""
Read the files with names of classes and returns one array with strings
@param path path to the file
"""
file = open(path, 'r')
return file.readlines() | 5f015bfd7e54a96ca6ff281a1960f8e11bcd0d88 | 689,192 |
def assign_node_sizes(graph, default_size=100, default_scale=25):
"""assign node sizes by total number of friends in whole network."""
sizes = []
for node in graph.nodes_iter(data=True):
try:
node_size = node[1]['friends_total'] / default_scale
node_size += 1
node... | c768d795957b6b6dc46480bb28806fa6366462cc | 689,193 |
def pytest_assertrepr_compare(config, op, left, right):
"""See full error diffs"""
if op in ("==", "!="):
return ["{0} {1} {2}".format(left, op, right)] | 3b47b84ee77a23ad7e6fc2f005304f035a2912c8 | 689,195 |
def get_filedata_strings(data):
"""
Return a dictionary with comma-separated list of LFNs, guids, scopes, datasets, ddmendpoints, etc.
:param data: job [in|out]data (list of FileSpec objects).
:return: {'lfns': lfns, ..} (dictionary).
"""
lfns = ""
guids = ""
scopes = ""
datasets =... | 43a4f184f6f64d35f66a054d09be68604466ef42 | 689,196 |
def int_to_little_endian(n, length):
"""endian_to_little_endian takes an integer and returns the little-endian
byte sequence of length"""
# use the to_bytes method of n
return n.to_bytes(length, "little") | 4e5118d97ae56f4e6486454e6310f706c44628cc | 689,197 |
def unescape(st):
"""
Unescape special chars and return the given string *st*.
**Examples**:
>>> unescape('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\')
'\\t and \\n and \\r and " and \\\\'
"""
st = st.replace(r'\"', '"')
st = st.replace(r'\n', '\n')
st = st.replace(r'\r', '\r... | bce4370ace1162b96a8c4d4e175903b2d8c2e929 | 689,198 |
def get_mapping(gappy_q, gappy_r):
"""
Produces a mapping from a gapped pairwise alignment. A mapping represents a mapped read, and contains all the
information to reconstruct a read sequence based on a reference sequence.
:return: tuple of tuples (basically a list of operations to perform on the refere... | c5abed529c350ca85c0bb6f0b51f8e90e0c2fe9a | 689,199 |
import torch
def batch_project(xyz_tensor, K):
""" Project a point cloud into pixels (u,v) given intrinsic K
[u';v';w] = [K][x;y;z]
u = u' / w; v = v' / w
:param the xyz points
:param calibration is a torch array composed of [fx, fy, cx, cy]
-------
:return u, v grid tensor in image coord... | 21346c1e4121ac622a97edae8c16428fb74752ad | 689,200 |
def makeGetpass(*passphrases):
"""
Return a callable to patch C{getpass.getpass}. Yields a passphrase each
time called. Use case is to provide an old, then new passphrase(s) as if
requested interactively.
@param passphrases: The list of passphrases returned, one per each call.
@return: A call... | bd8a000f4307e29f94e77018c00fb8ccb45097c5 | 689,201 |
import os
import sys
def find_default_qmake():
"""Find a default qmake, ie. the first on the path.
"""
try:
path = os.environ["PATH"]
except KeyError:
path = ""
if sys.platform == 'win32':
base_qmake = "qmake.exe"
else:
base_qmake = "qmake"
for d in path.s... | fbceab6e72945f2a877d615ac827c9f9650488e4 | 689,203 |
import time
def generate_footer():
"""Creates the footer for the bottom of the pages"""
curtime = time.localtime()
time_string = str(curtime.tm_mon) + "/" + str(curtime.tm_mday) + "/" + str(curtime.tm_year)
return_string = "<p>Documentation updated on " + time_string + "</p>"
return_string += "<p>Written in Pyt... | 233822cbe26f421b34610aea42c0d59c29b44096 | 689,204 |
def format_sig(name, args, retv):
"""
Format method signature with Javap's method definition style.
Arguments are: name of method, list of argument types, and type of return value.
>>> format_sig('getSomeValue', ['int', 'java.lang.String'], 'org.mydomain.myapp.SomeData[]')
u'org.mydomain.myapp.... | 5ecb5ed3c38dbf14d5000fb9c8129f785c44bbe1 | 689,205 |
def myfunc(group):
"""helper function"""
#get all players into a set
w_set = set(group['winner_name'])
l_set = set(group['loser_name'])
#u_set contains all names of participating players
group['player_sums'] = len(w_set.union(l_set))
return group | 5f5a0ea7346b5c90086b1e33b0edb401b6d4e0d4 | 689,206 |
def missing(records):
"""Returns a tuple indicating any fields missing from the records
in the set."""
return dict((r.key.key, r.missing()) for r in records if not r.valid()) | b277c0e09a42ddf59a34381149caa4d9f885e7e1 | 689,209 |
import re
def get_consonant_repeat_frequency(words):
"""Check for repeating consonant frequency for a given set of words.
Args:
words (list): A list of words
Returns:
dict: The data and summary results.
"""
count = 0
cons = re.compile(r'[^a|e|i|o|u{6}]')
for val in words:... | bda707e2cfa03c6cf97bb564d163349b9db99d48 | 689,210 |
import os
def module_list(_print=True) -> tuple:
"""
#### Returns a tuple with basic and extra modules.
#### Parameters
* `_print`: if True, prints the modules.
"""
basics = [f for f in os.listdir("ezsgame") if f.endswith(".py")]
extras = [f for f in os.listdir("ezsgame/extra"... | d1bb6cc2ac23e3c785d263da4164071b33152009 | 689,211 |
from typing import Any
from typing import Mapping
def _get_field_value(value: Any, *, params: Mapping[str, Any]) -> Any:
"""
Returns the given value with any converters applied.
"""
converter = params.get("converter", None)
if converter is not None:
return converter(value)
return value | 6cbe572a2add5d2b8c898a0ce702c91276b12245 | 689,212 |
import collections
def GetTurnStats(game_results):
"""Returns a histogram of game lengths (in rounds played)."""
hist = collections.Counter()
for game_result in game_results:
hist[game_result.num_rounds_played] += 1
return hist | 78a4980ffa3a71d0181499f6448c75fa7d56c422 | 689,213 |
def _ParseIssueReferences(issue_ref_list):
"""Parses a list of issue references into a tuple of IDs added/removed.
For example: [ "alpha:7", "beta:8", "-gamma:9" ] => ([ "7", "8" ], [ "9" ])
NOTE: We don't support cross-project issue references. Rather we
just assume the issue reference is within the same pro... | a8c8ebea8ebd289c84bd34bfdc064b8b90daf830 | 689,214 |
import os
import shlex
import subprocess
def execute(cmd,
raise_error=True,
no_venv=False,
exec_env=None,
expect_exit=True,
expected_exitcode=0,
context=None):
"""
Executes a command in a subprocess. Returns a tuple
of (exitcode, out,... | 37d291219b71680e0040f25289161468a639957a | 689,215 |
import os
def meter_info():
"""Get the meter status information, if running in the meter-status-changed
hook."""
return os.environ.get('JUJU_METER_INFO') | 1659a846c3b78b56fa91d9e384868c0a86ed8891 | 689,216 |
def get_lonlat_list(location):
"""Helper to return a list of lonlat tuples of coordinates in a location"""
lonlat_list = []
if hasattr(location, "lon") and hasattr(location, "lat"):
lonlat_list.append((location.lon, location.lat))
if hasattr(location, "point"):
lonlat_list.append((locati... | 4e1f03ee0313f6ffbdd1fcd68c1aa5dd09bd953b | 689,217 |
import base64
def write_to_data_uri(s):
"""
Writes to a uri.
Use this function to embed javascript into the dash app.
Adapted from the suggestion by user 'mccalluc' found here:
https://community.plotly.com/t/problem-of-linking-local-javascript-file/6955/2
"""
uri = (
('data:;base64... | 5b5281119c25c52da1970293e833c18231c0d26e | 689,218 |
def cart2(list1: list, list2: list) -> list:
"""Cartesian product of two lists.
:param list list1: input list 1
:param list list2: input list 2
:return: a new list contains all Cartesian products of
the two lists.
:rtype: list
>>> cart2(['a','b'], [1,2])
[['a',1],['a',2],['b',... | 3deb6106b36dc81ed2b8b4251290c687b591c157 | 689,219 |
def get_sentences(docs, min_words):
"""
Given a set of documents we extract all sentences that pass a minimum word threshold
ARGS: docs(list of Documents), min_words(int)
Returns: sentences(list of Sentences)
"""
sentences = []
[sentences.extend(doc.get_filtered_sentences(min_words)) for doc... | 0f45ecf212d39daa61038a35352def526bb53c2d | 689,221 |
import re
def solution(s):
"""
Complete the solution so that it splits the string into
pairs of two characters. If the string contains an odd
number of characters then it should replace the missing
second character of the final pair with an underscore ('_').
"""
if not len(s) % 2 == 0:
... | 69c1649ca997a98ffdb382d66c26a2c8ce9eeea1 | 689,222 |
def _get_best_results(hparams):
"""Summary of the current best results."""
tokens = []
for metric in hparams.metrics:
tokens.append("%s %.2f" % (metric, getattr(hparams, "best_" + metric)))
return ", ".join(tokens) | d596b3157bb5e8f2dcc5a889f67c14f8e9d05c09 | 689,224 |
import os
def get_filenames(dataset_dir, extension):
""" Returns a list of filenames.
Args:
dataset_dir: A directory containing a set of files.
extension: extension of the file to return.
Returns:
A list of file paths, relative to `dataset_dir and depending on `extension.
"""
... | a8ba81c8254e956f2e4e6be5d46eb52c9ba7bb5a | 689,225 |
def interface_seen(seen, iface):
"""Return True if interface already is seen.
"""
for seen_iface in seen:
if seen_iface.extends(iface):
return True
return False | 2e45195a5191925df04d92960f555f4a8393e622 | 689,227 |
import os
def localise_term_directory(src_dir, st_term_dir, request_type):
"""Localise the terminal directory path."""
if st_term_dir is None:
raise RuntimeError('The {} sphinx config value must be set when '
'loading {} from a file.'.format(*request_type))
# localise th... | 6fe9f53052a1521e489ef35e0953bd91869dc0c5 | 689,228 |
def compute_conv_output_dim(ifm_dim, k, stride, total_pad=0, dilation=1):
"""Returns spatial output dimension size for convolution with given params.
total_pad gives the total amount of padding along the entire axis
(both sides included).
"""
if ifm_dim == 1:
# indicates dummy dimension, kee... | cb401bd2dd6fdce26a5c6b7796edbacdac570237 | 689,229 |
import argparse
def parse_arguments():
"""
Parse arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("number_of_records", help="number of people", type=int)
parser.add_argument("firstname", help="first name off entry")
parser.add_argument("lastname", help=... | 8f3ea99706d75ba079bdb2441489f970e348b74f | 689,232 |
import re
def find_str(string: str, pattern: str) -> list:
"""
Find all indices of patterns in a string
Parameters
----------
string : str
input string
pattern : str
string pattern to search
Returns
-------
ind : list
list of starting indices
"""
i... | e0ec90edfb4c7ea55ee58dd184b67b5966c2728e | 689,233 |
from datetime import datetime
def get_listing_date(listing: dict) -> str:
"""Milliseconds since epoch"""
try:
return datetime.fromtimestamp(
listing["publishData"]/1000).strftime("%Y-%m-%d")
except KeyError:
return datetime.now().strftime('%Y-%m-%d') | 87dcd2c04b29c362e2658602b1ac94c4b9f3bdae | 689,234 |
def search_beam(hdulist):
"""
Will search the beam info from the HISTORY
:param hdulist:
:return:
"""
header = hdulist[0].header
history = header['HISTORY']
history_str = str(history)
#AIPS CLEAN BMAJ= 1.2500E-02 BMIN= 1.2500E-02 BPA= 0.00
if 'BMAJ' in history_str:
... | 766c5610c2e4cf51baddbdc6416fedccf8860c91 | 689,235 |
import pprint
import time
def await_containerrun(session, containerrun):
"""Given a `KiveAPI instance and a container run, monitor the run
for completion and return the completed run.
"""
ACTIVE_STATES = "NSLR"
INTERVAL = 1.0
MAX_WAIT = 300.0
starttime = time.time()
elapsed = 0.0
... | 8ffbac0fbabdeed67e6a2897e3601e64dd56a436 | 689,236 |
def create_token_content_id(iteration):
"""
:param iteration:
:return:
"""
return 'tokenContent' + iteration | f5cc9c5f46ff814e6238c5e424c1f7a3bb49b26b | 689,237 |
import subprocess
def zfs(*arguments):
"""
Run a 'zfs' command with given arguments, raise on non-0 exit code.
@return: stdout bytes.
"""
return subprocess.check_output(["zfs"] + list(arguments)) | a3c293831c04d49571b68efefcc2b0cb916378cb | 689,238 |
def length(value):
"""
Computes indicator from Indicator
:param Numlike values: values to count indicator from
:return: float
"""
return value.upper - value.lower | 0562d9186ac02718b111f06ebe8fde788615c8c8 | 689,239 |
import torch
def log_mean_exp(x, dim=1):
"""
log(1/k * sum(exp(x))): this normalizes x.
@param x: PyTorch.Tensor
samples from gaussian
@param dim: integer (default: 1)
which dimension to take the mean over
@return: PyTorch.Tensor
mean of x
"""
m =... | fad061ec893072003c9e5ab52e759e8e7a74eac6 | 689,240 |
import os
def setup(i):
"""
Input: {
cus/full_path - the path of the found python file (or directory if "soft_can_be_dir")
cus/soft_can_be_dir - set to "yes" if you are looking for a directory, not a regular file
cus/required_depth - how many EXTRA STE... | 7231abd238bcbf1158403b846852eb13e0227fd6 | 689,241 |
from typing import Dict
from typing import List
def _continuous_columns(feature_types: Dict) -> List[str]:
"""
Parameters
----------
feature_types : Dict
Column name mapping to list of feature types ordered by most to least relevant.
Returns
-------
List[str]
List of colum... | d21b02f949a5c658defeaaa67a0abec916373f0d | 689,242 |
import torch
def view_as_real(data):
"""
Returns a view of data as a real tensor.
For an input complex tensor of size (N, ...) this function returns a new real tensor of size (N, ..., 2) where the
last dimension of size 2 represents the real and imaginary components of complex numbers.
Parameter... | 961c34b282d6a98bead941a5a12457074a0c5fc4 | 689,243 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.