content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def label_nodes(node_dataFrame, top_node_size, path, label_file,sep = ','):
"""
根据节点的出入度,对度为top的节点进行打标签。
:param node_dataFrame: 计算了出入度、度的节点文件。
:param top_node_size:每一个社区需要标记的节点个数。
:param path:标签文件的保存路径。
:param label_file:节点标签文件。格式为(user_id, verify, name),csv文件,以sep分隔
:param sep:标签文件中的分隔符。
... | 71a9fcc8605a82eff06c5cdf6c9f1f589a851233 | 60,722 |
import json
def simplify_geometry(
points,
maxpts=None,
mindist=None,
interpolate=False,
keep_activity=False):
"""Simplify location trace by removing geometrically redundant points.
points -- [{
"geojson": json.dumps({"coordinates": [lon, lat]}),
"time"... | 56fc3c411a1f2f22a2488a1c5b8a6a069800bc3b | 60,723 |
from typing import Callable
from typing import Iterable
from typing import Dict
def count_valid_passports(
validation_func: Callable, passports: Iterable[Dict[str, str]]
) -> int:
"""count the valid passports (those who have all keys"""
return sum(map(validation_func, passports)) | 230fd67e9e3bc2b999a5b44141d51f7507de4062 | 60,724 |
from typing import Optional
from typing import Any
def svd(matrix: BlockSparseTensor,
full_matrices: Optional[bool] = True,
compute_uv: Optional[bool] = True,
hermitian: Optional[bool] = False) -> Any:
"""
Compute the singular value decomposition of `matrix`.
The matrix if factorized int... | 04e5b1780c103b3ab27d9ce964403751d49bb006 | 60,725 |
def get_pose_dis(choose_idx, pose_conf, pose_loc, keypoint_width,
delta1, delta2, mu):
"""
<class 'numpy'>
:param choose_idx:
:param pose_conf: [n x 17]
:param pose_loc: [n x 17 x 2]
:return:
"""
# make sure dim
if pose_conf.ndim == 1:
pose_conf = np.expand_d... | 4fa4bf4d3504bd7f3d9086f650744a62f3fec7a6 | 60,727 |
import json
def json_object_to_str(json_obj):
"""
json对象序列化为json串
:param json_obj: json对象
:return: 序列化的json串
"""
return json.dumps(json_obj, ensure_ascii=False) | 935ebc10d412c803d52493cd648cc0c010adb07d | 60,728 |
def is_tokenizer(value):
"""Tokenizers must be valid Regular expressions. see: options.PrefixTokenizers"""
return bool(non_empty_string(value)) | fb836a96a5da041335205ee9fbc0f28f643c00ef | 60,729 |
def to_chi(q_oper):
"""
Converts a Qobj representing a quantum map to a representation as a chi
(process) matrix in the Pauli basis, such that the trace of the returned
operator is equal to the dimension of the system.
Parameters
----------
q_oper : Qobj
Superoperator to be converte... | b6e2eb40c2a83b720dfb0f41c570e5929f1cc118 | 60,733 |
def del_points(**kwargs: dict) -> str:
"""Delete all points record for a user; requires admin."""
user = kwargs.get('user')
score = kwargs.get('message')._kwargs.get('score')
msg = ''
if not kwargs['message'].admin:
return msg
if user in score:
del score[user]
msg = "<@{0}> h... | 1d47ba187b873f2bfad9092113a92d20b6d89aaf | 60,734 |
def check_bounds(bounds, shape=0, min_separation=0.0, dtype=float):
"""Input validation for the ``bounds`` parameter.
Checks that ``bounds`` is composed of a list of tuples of the form (lower, upper), where lower <= upper and both
are numeric. Also checks that ``bounds`` contains the appropriate number of... | 4a3d133605465c7641740b51ee76fcfb4a15268c | 60,735 |
from typing import Union
from typing import Literal
from typing import Callable
import multiprocessing
def RGB_colourspace_volume_MonteCarlo(
colourspace: RGB_Colourspace,
samples: Integer = 1000000,
limits: ArrayLike = np.array([[0, 100], [-150, 150], [-150, 150]]),
illuminant_Lab: ArrayLike = CCS_IL... | f51b6b174fd49319cec6c6ccb2eedaca1bd81e38 | 60,736 |
def dsm_6(api) -> SynologyDSM:
"""Alias for api fixture."""
return api | 4f58af157e655db782c9303b7fa90e5101419573 | 60,737 |
def send_many(kwargs_list):
"""
Similar to push.send(), but this function accepts a list of kwargs.
Internally, it uses Django's bulk_create command for efficiency reasons.
Currently send_many() can't be used to send notifications with priority = 'now'.
"""
if not FIREBASE_APP:
return No... | 70c4d83dfe815f9eb42a0e1aa6d5654c215e40d2 | 60,738 |
def mni2tal(coords):
"""
Python version of BrainMap's icbm_other2tal.m.
This function converts coordinates from MNI space (normalized using
templates other than those contained in SPM and FSL) to Talairach space
using the icbm2tal transform developed and validated by Jack Lancaster at
the Resea... | 2f1b6de079f950565bba33fbd555b6faa2b26b3c | 60,739 |
import struct
def vbkv_loads(s, mapper=dict, merge_duplicate_keys=True):
"""
Deserialize ``s`` (``bytes`` containing a VBKV to a Python object.
``mapper`` specifies the Python object used after deserializetion. ``dict` is
used by default. Alternatively, ``collections.OrderedDict`` can be used if you
... | 6f55f93f1c767872aeeac0c9838baf739a1024c3 | 60,740 |
def sql_not_like(a, b):
"""SQL_NOT_LIKE
DESCRIPTION: Clumsy way of handling NOT LIKE as a SQL operator
INPUT:
OUTPUT:
"""
return not sql_like(a, b) | ad8f5b5fc6bad7fb42454801dc2aea7a725b5e10 | 60,741 |
import requests
def newSDDCPublicIP(proxy_url, sessiontoken, notes):
""" Gets a new public IP for compute workloads. Requires a description to be added to the public IP."""
myHeader = {"Content-Type": "application/json","Accept": "application/json", 'csp-auth-token': sessiontoken}
proxy_url_short = proxy_... | c4dad80fb4b57b456007a33f0f32fdea78bdd246 | 60,742 |
def power_of(x):
"""create a inner function to return the power of x"""
def inner_func(y):
return x**y
return inner_func | 69900b32c50c73365cf6c492f7c0e3b2f5641e01 | 60,743 |
def intersect_line_grid(line, grid):
"""Intersect a line with a grid, returning the smallest set of new lines
which cover the original line and such that each new line segment lies
entirely within one grid cell.
:param line: `((x1,y1), (x2,y2))`
:param grid: Instance of :class:`data.Grid` or sa... | 5b682918c243b645e9ff9edac28b2c0e6f3af66c | 60,744 |
def import_csv(filename):
"""Imports the csv file at a given path
:param filename: Path and name of file to import
:type filename: str
:return: Dataframe of csv file
"""
return pd.read_csv(filename, sep=',') | 9b8d6e8bfefdb1602cce5e1ae1f12b3fdcd2c04e | 60,745 |
import ctypes
def pfaffian(
matrix: np.ndarray,
uplo: str = "U",
method: str = "P",
avoid_overflow: bool = False,
):
"""Compute Pfaffian.
Parameters
----------
matrix : numpy.ndarray
Square skew-symmetric matrix.
uplo : str
If 'U' ('L'), the upper (lower) triangle ... | fa53eda48353793d6a4c256996f17ec6663311c4 | 60,746 |
def tsne_condP(D2=np.array([]), perplexity=30.0,
tol=1e-5,max_iter=50, verbose=0):
"""
Performs a binary search to get P-values in such a way that each
conditional Gaussian has the same perplexity.
"""
# Initialize some variables
(n, n1) = D2.shape
if n != n1:
... | ce05a2bf029cf26da62c13f9395d5747135fbf59 | 60,747 |
def _ln(input_tensor, gain, bias, epsilon=1e-5, axes=None):
"""
Apply layer normalisation.
:param input_tensor: (TensorFlow Tensor) The input tensor for the Layer normalization
:param gain: (TensorFlow Tensor) The scale tensor for the Layer normalization
:param bias: (TensorFlow Tensor) The bias te... | dcc4aabe3bbcaa0408bd1d961c5673a40598efd1 | 60,748 |
import h5py
def read_maxwell(file, well_name='well000', rec_name='rec0000'):
"""
Read a maxwell file and return a Probe object. Maxwell file format can be
either Maxone (and thus just the file name is needed), or MaxTwo. In case
of the latter, you need to explicitly specify what is the well number of
... | b1b8868f80642d3bbe9763ebff44ec71c27c0af8 | 60,749 |
import typing
def key_metrics(
apikey: str,
symbol: str,
period: str = "annual",
limit: int = DEFAULT_LIMIT,
) -> typing.List[typing.Dict]:
"""
Query FMP /key-metrics/ API
:param apikey: Your API key.
:param symbol: Company ticker.
:param period: 'annual' or 'quarter'
:param l... | fde07aa73e33b92ba419f2c3d66abe5310fdf0e8 | 60,750 |
def id_maker(pick_time, net, station, loc, ch, phaseHint, ai_type):
"""Creates the seiscomp Pick PublicID
Parameters
----------
pick_time : Obspy UTCDateTime object
Time for phase pick
Returns
------
str
Seiscomp pick PublicID
"""
dateID = pick_time.strftime(... | d576ed1a98aadda69b1354e25d77425cd386ce6b | 60,751 |
def kan_være_købstadsnummer(s: str) -> bool:
"""
Returnerer sand, hvis `s` matcher købstadsnummermønsteret.
Procedure minder om dén for landnumre.
"""
return KØBSTADSNUMMERMØNSTER.match(s.strip()) | 740aa5438168e8148b3917b4a2ad792d05dfc7f1 | 60,752 |
def get_time_for_display(display):
"""
Provide a reader-friendly time string for any time parse-able by get_astropytime -
if that results in None, then the string None is displayed.
"""
d = get_astropytime(display)
if d is None:
d = 'None'
elif isinstance(d, Time):
d = "{:%Y... | 54eba2a07c6f2703ad12031aab29a240871ec276 | 60,753 |
import re
def RetriveEMDBIDFromCIFFile(Infile):
"""Retrieve EMDB ID from CIF file. """
InfileFH = open(Infile, "r")
if InfileFH is None:
MiscUtil.PrintError("Couldn't open input file: %s.\n" % (Infile))
MiscUtil.PrintInfo("\nRetrieving EMDB ID from input file %s..." % Infile)
EMDBID... | 2c5bc5df6778ea1fd9d3996a66c0b8c1b6594aca | 60,754 |
import math
def resize3d_linear(data_in, scale, coordinate_transformation_mode):
"""Trilinear 3d scaling using python"""
dtype = data_in.dtype
d, h, w = data_in.shape
new_d, new_h, new_w = [int(round(i * s)) for i, s in zip(data_in.shape, scale)]
data_out = np.ones((new_d, new_h, new_w))
inde... | 015fc90b649f50d69359b95990b44ed361f7d9cf | 60,755 |
def obtener_cantidad_turistas_y_pais_origen_en_ciudad_en_mes_en_anio(PaisDestino, CiudadDestino, Mes, Anio): #OK
"""
Dado un pais, una ciudad destino, un mes y un año obtiene la cantidad total de personas que llegan a esa ciudad separando por pais de origen
Dado un pais, una ciudad destino, un mes y un año ... | 4e6eddf2f6b5499b5b0916ba8def0f53a91245b7 | 60,756 |
def to_hex_with_size(value, bit_size):
"""Converts a value to hex with given bit_size:"""
return pad_hex(to_hex(value), bit_size) | 9aaa174de1f89f96040328177172875d4e841d6a | 60,757 |
def quantile_with_mask(
values: np.ndarray,
mask: np.ndarray,
fill_value,
qs,
interpolation: str,
axis: int,
) -> np.ndarray:
"""
Compute the quantiles of the given values for each quantile in `qs`.
Parameters
----------
values : np.ndarray
For ExtensionArray, this i... | 6f461aa662bda45cd7998ab0d609dc3557543edd | 60,758 |
def get_positions(console):
"""
Compute a dictionary keyed by button names with horizontal alignment,
and column/row location to show each choice on the EV3 LCD console.
Parameter:
- `console` (Console): an instance of the EV3 Console() class
returns a dictionary keyed by button names with colum... | ba9df0c2ea189e146d5cf123354c283dd6e2b280 | 60,759 |
import inspect
from ..log import PCG_ROOT_LOGGER
def create_object(tag, **kwargs):
"""Factory method for `Link` subclasses.
> *Input arguments*
* `tag` (*type:* `str`): Name identifier of the object class
* `kwargs` (*type:* `dict`): Input arguments for the object class
> *Returns*
`Link`:... | 0760fbb675a29f7ca5057c7e87ac3c9e50486faa | 60,760 |
def add_sample_group(authn): # pylint: disable=too-many-locals
"""Add sample group."""
# Validate input
try:
data = request.get_json()
name = data['name']
organization = Organization.query.filter_by(name=data['organization_name']).first()
except TypeError as exc:
current... | 4aa1473637ee579b87cff8a4dfc12990d7d86a5b | 60,761 |
def convert_to_tenfive(ch_names=None):
"""Convert channel names to 10-5 system
This function aims to convert the channel labeling (in number) to the standardized 10-5 electrode labeling.
Examples
--------
>>> import TruScanEEGpy
>>> import mne
>>>
>>> ch = TruScanEEGpy.convert_to_tenfi... | ea1b4f282cf4c31a8ddd41319a208146cf4d3e58 | 60,762 |
def rotate_point_y(xyz, theta, radians=False):
"""
Rotates a 3D vector by the angle theta about the y axis
Args:
xyz: x, y, z tupple or array
theta: float, angle in degrees unless radians is True
radians: bool, if true then theta is treated as radians
Returns:
a, b, c: ro... | 606509a36c10869bb0ecc084f6c332fa6f14f253 | 60,763 |
from typing import Callable
from typing import Any
def attrs_assert_type(expected_type: type) -> Callable[[Any, Any, Any], None]:
"""
Convenience function for attrs to easily check for a given type by using a validator.
Remark: typing types like Union[...], List[...] are supported.
Examples:
... | 38f7a99ea9058a2ce743804f374a1db84ea42b29 | 60,765 |
def _createTaperedBox( proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh ):
"""
Private function.
Use createTaperedBox() or createArticulatedTaperedBox() instead.
"""
taperedBox = _createBox( proxy, size, colour, moiScale = moiScale, withMesh = False )
if wi... | 45d955ee012e6d3bc02779a36087c985be5fe3f6 | 60,766 |
def generate_patch_transfer_job_message(messages, job):
"""Generates Apitools patch message for transfer jobs."""
project_id = job.projectId
job.projectId = None
if job.schedule == messages.Schedule():
# Jobs returned by API are populated with their user-set schedule or an
# empty schedule. Empty sched... | 5330f3e248ad57b69045b54f1c46c32219d1dde5 | 60,767 |
import logging
def parse_requirements(file_):
"""Parse a requirements formatted file.
Traverse a string until a delimiter is detected, then split at said
delimiter, get module name by element index, create a dict consisting of
module:version, and add dict to list of parsed modules.
Args:
... | 958ff91957667e3783e9971b2f2d0c04e4cd2a61 | 60,770 |
import torch
def find_lengths(messages: torch.Tensor) -> torch.Tensor:
"""
:param messages: A tensor of term ids, encoded as Long values, of size (batch size, max sequence length).
:returns A tensor with lengths of the sequences, including the end-of-sequence symbol <eos> (in EGG, it is 0).
If no <eos... | 32e1eaadedb69ad0b3ea3339b8d326f7a4bcfaf8 | 60,771 |
def duplicate(somelist):
"""
biore binary search na srodku listy
sprawdzam
:param somelist:
:return:
"""
emptylist = []
for i in somelist:
if len(emptylist) == 0:
emptylist.append(i)
else:
if i in emptylist:
return i
em... | aad005e7a2b2fe2f4874673dd93ad6eaf982b13a | 60,772 |
def get_handler_filename(handler):
"""Shortcut to get the filename from the handler string.
:param str handler:
A dot delimited string representing the `<module>.<function name>`.
"""
module_name, _ = handler.split('.')
return '{0}.py'.format(module_name) | 4e6d464e83e4a6557d03ebabbb4f275fc4784d8f | 60,774 |
def eval(dataloader, head_detector):
"""
Given the dataloader of the test split compute the
average corLoc of the dataset using the head detector
model given as the argument to the function.
"""
test_img_num = 0
test_corrLoc = 0.0
for _, (img, bbox_, scale) in enumerate(dataloader):
... | 7b31b365e2f37f4087b5f58c59e7bfe5ab7b66a8 | 60,775 |
def read_AtomName_ChargeGroup(file_name, ase2pmd):
"""
Function to read in csv file of atom names and associated charge groups with
the help of pandas. Expects dictionary of ASE indices pointing at atom and
residue name tyuples and constructs vector of associated charge
group. The vectors are all ... | 70a19130d06d99bd171943c5e38330a3218858ea | 60,776 |
def build_quadratic_function(x, a, b, c):
""" Returns the function f(x) = ax^2 + bx + c """
return a*x*x + b*x + c | 4b6bec7f9329c515afc94a8ea090c3886d7a6e46 | 60,777 |
def connect_host(host, pid):
"""连接主机"""
host_error = False
hostname, port, username, password = host
client = paramiko.SSHClient() # 创建客户端
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, port, username, password, timeout=3)
except paramik... | 6ae4db4c35fa8b86c0424ba3f7c3b0b1445c4c09 | 60,778 |
def parseEPSGCode(string, parsers):
""" parse EPSG code using provided sequence of EPSG parsers """
for parser in parsers:
epsg = parser(string)
if epsg is not None:
return epsg
return None | b85e2d69952cc16d7f5f3b9e22009d14432a014f | 60,779 |
def big_brain_algorithm(word_list=None):
"""
Checks if a word can be made out of the elements that are contained in it.
:param word_list: A list with where index 0 is the word and index 1 is all possible elements that are in the word.
:return: All possibilities to create the word out of elements.
""... | f26bf23e5ca1215445e230556e720514d477ee0f | 60,780 |
from typing import Optional
from typing import Type
from typing import Callable
def group(
name: Optional[str] = None, cls: Type[GroupCommand] = GroupCommand, **attrs
) -> Callable[["CommandFunctionType"], GroupCommand]:
"""Register a coroutine as a :class:`GroupCommand`.
Parameters
----------
na... | e4017c2c9122004350849d316118715424389912 | 60,781 |
def req_rheader(r):
"""
Resource Header for Needs
"""
if r.representation != "html":
# RHeaders only used in interactive views
return None
record = r.record
if not record:
# RHeaders only used in single-record views
return None
if r.name == "need":
... | 07bcb4f8bd5c91de970633e613e447e13c03de32 | 60,782 |
def sum_intersection(map_list):
"""
Sum a list of HealSparseMaps as an intersection. Only pixels that are valid
in all the input maps will have valid values in the output.
Parameters
----------
map_list : `list` of `HealSparseMap`
Input list of maps to sum
Returns
-------
r... | a7a10bb47210cca4488a8145a90aa9708f8c91b2 | 60,783 |
def colorspace(im, bw=False, replace_alpha=False, **kwargs):
"""
Convert images to the correct color space.
A passive option (i.e. always processed) of this method is that all images
(unless grayscale) are converted to RGB colorspace.
This processor should be listed before :func:`scale_and_crop` s... | 7680bbaa1db5527eb845c2f4cb52f7b66ac75a33 | 60,784 |
def make_tiles(in_data, tile_path, tile_width=256, tile_height=256, tile_overlap=32):
"""Split input images into tiles
Parameters
----------
in_data: iterable
The input images, to split into tiles
tile_path: str
Filepath where the tiles should be saved
tile_width: int
Ti... | 059b3c83bf3b46ffeeaec500abc7075516aabf46 | 60,785 |
def int32(name, description, default=None):
# type: (AName, ADescription, AInt32Default) -> AAnno
"""Add an int32 parameter to be passed when instantiating this YAML file"""
args = common_args(name, default)
return Anno(description, typ=int, **args) | ff44435a9ee735d2840893026d98efe2b881ea7e | 60,786 |
def make_test_data(filename, taiObs, dataType, camera=1, filter="g2", shape=(30, 50), bias=32,
ra=100, dec=-30, exposure_time=30):
"""Make a fake FITS image with a realistic header, returning the header."""
# Make the fake image data
if dataType == "science":
data = np.ones(shape)... | 65ce95b755f7fa9d719df61a5fa69e28a9051694 | 60,789 |
def user_has_pending_game_actions(ctx, u):
""" Returns True if this user has any pending 'actions' in the current game. Actions is currently
defined as unprocessed targets, future chips or future deferred actions, but this definition might change. """
actions = 0
actions += db._run_query_string(ctx,... | 39eef1aa67ba0095d9b1cf87bc75548b284f64b5 | 60,790 |
def project_to_plane(points,
plane_normal=[0, 0, 1],
plane_origin=[0, 0, 0],
transform=None,
return_transform=False,
return_planar=True):
"""
Projects a set of (n,3) points onto a plane.
Parameters
... | 1276c06556e42e3da905a144944761edac8e23bc | 60,791 |
import re
def get_value_for_key(text_buffer, key):
"""Parsing value from a line with key=value"""
for match in re.finditer("%s=(?P<value>.*)" % key, text_buffer):
return match.group('value')
return "" | 86865f806adc3fa5f78671d8a686389cc5f0f353 | 60,792 |
def join_longways(list_of_dataframes):
"""Join the supplied dataframes along the long axis - appending them one after another to make a longer table"""
df = pd.concat(list_of_dataframes,axis=0)
return df | 9334076130673ad2ff84d1958058bd5a4bb6b67b | 60,795 |
import six
def py2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
"""
if six.PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
... | 914ac3fed6aab80fe61edef368478c58751ebd7a | 60,796 |
import numpy
def _problem_for_numerical_trainable_transform_cl(dtype=numpy.float32, n_features=None):
"""
Returns *X, intial_types, method, name, X runtime* for a
transformation problem.
It is based on Iris dataset.
"""
data = load_iris()
X = data.data
state = numpy.random.RandomState(... | ca162d2c1e29ab0c572581b20f865f7b10f5e7c8 | 60,797 |
def find_base_url(html_document, fallback_base_url):
"""Return the base URL for the document.
See http://www.w3.org/TR/html5/urls.html#document-base-url
"""
first_base_element = next(iter(html_document.iter('base')), None)
if first_base_element is not None:
href = first_base_element.get('h... | 86501904c5982cfe1402b049b404a67dede6e26d | 60,798 |
import pathlib
def _is_valid_doc_version(folder: pathlib.Path) -> bool:
"""
Test if a version folder contains valid documentation.
A version folder contains documentation if:
- is a directory
- contains an `index.html` file
"""
if not folder.is_dir():
return False
if not (fold... | 5dadea657b717373e8e84360f1f3a9e8b8adc1f8 | 60,799 |
def get_original_dword(*args):
"""
get_original_dword(ea) -> uint64
Get original dword (that was before patching) This function works for
wide byte processors too. This function takes into account order of
bytes specified in \inf{is_be()}
@param ea (C++: ea_t)
"""
return _ida_bytes.get_original_dwo... | 7edbc0dfbd42d14c199be76ce2f99cfdc22aad45 | 60,800 |
def within_refresh_interval(now, last_info_pull):
"""
This is so we don't flood the server with overly frequent HTTP traffic
"""
return now - last_info_pull < INFO_REFRESH_INTERVAL | e4e98311bc6178c7fe9cebf12890ea86aab62ce1 | 60,801 |
def polar2rect(mag, phase_angle):
"""Convert polar-form complex number to its rectangular form."""
mag = tf.complex(mag, tf.convert_to_tensor(0.0, dtype=mag.dtype))
phase = tf.complex(tf.cos(phase_angle), tf.sin(phase_angle))
return mag * phase | 303673654125d1de94428db6e0afddd92a92d746 | 60,802 |
def gen_explicit_map_one_delta(params_pt, args_pt, k_ms, k_pt):
"""
Generate explicit_map for which include mapping relationship is `1 - k_ms = k_pt`.
Args:
params_pt (dict): Params for APIPt.
args_pt (dict): Args for APIPt.
Returns:
dict, map between frames.
"""
value ... | 841d81c0095dadf7e62c32fca5a3d9e6007b6032 | 60,803 |
from typing import Any
from contextlib import suppress
def catch_timeout_error(return_value: Any = False):
"""
This decorator will catch TimeoutException and return `return_value`.
"""
@wrapt.decorator
def wrapper(wrapped, _, args, kwargs) -> Any:
with suppress(TimeoutException):
... | fd758f93f97f41a40d9bbad6659e8740676aaaf5 | 60,804 |
def calc_uniform_log_prob(spec):
"""Given an action spec, calculate the uniform log prob.
Args:
spec (BoundedTensorSpec): action spec must be a bounded spec
Returns:
The uniform log probability
"""
assert isinstance(spec, BoundedTensorSpec)
zeros = np.zeros(spec.shape)
min_... | 0af627357e2fa598ceaa2adc1211a4259c533d7e | 60,805 |
def reward_qvals(rewards, discount):
"""
Same as qvals but accepts traces of observed rewards.
"""
all_qvals = []
for reward_trajectory in rewards:
# numerically stable cumulative reward sum
path_qvals = np.empty_like(reward_trajectory, dtype=np.float64)
future_qval = 0
... | 8b7cc893858221a2503e65f92bab66345a93c9ca | 60,807 |
def strip_comments(l: str) -> str:
"""
Strip any ``#`` comments from a line.
:param str l: A string line, which may contain ``#`` comments
:return str clean_line: The line ``l`` - stripped of any comments and excess whitespace.
"""
return l.split('#', 1)[0].strip() | 0587cb5e2a986c9d0bb4c610c289186b8c184942 | 60,808 |
def shengbte_code(aiida_local_code_factory):
"""Get a shengbte code.
"""
shengbte_code = aiida_local_code_factory(executable='diff',
entry_point='shengbte')
return shengbte_code | de9f6bba763c4bfe7f6a1153927f73542a83dc6a | 60,809 |
import mimetypes
def get_content_type(content, name):
"""
Checks if the content_type is already set. Otherwise uses the mimetypes
library to guess.
"""
if hasattr(content.file, "content_type"):
return content.file.content_type
else:
mime_type, encoding = mimetypes.guess_type(na... | 838d11c2660e0d76c813961498ab0ebcc25c1f3c | 60,810 |
def switch_backend(*args, **kwargs):
"""
Call `matplotlib.pyplot.switch_backend`.
%(ui.pyplot)s
Parameters
----------
*args, **kwargs
Passed to `matplotlib.pyplot.switch_backend`.
"""
return plt.switch_backend(*args, **kwargs) | be925a389cc795d2db0e2b48103823f0310391ef | 60,811 |
def parse_content(content):
"""
:param content:
:return: converted text
"""
try:
text = convert_text(content, settings.TO_FORMAT_EXT, format='html',
extra_args=["+RTS", settings.HEAP, "-RTS"])
except:
text = 'too big'
return text | 824cac81497ddfe6eeac488ce6af881c4f8a9dcb | 60,812 |
from pathlib import Path
def combine_cfgs(path_cfg_data: Path=None, path_cfg_override: Path=None):
"""
An internal facing routine thaat combined CFG in the order provided.
:param path_output: path to output files
:param path_cfg_data: path to path_cfg_data files
:param path_cfg_override: path to p... | 8ce12f970d6c06a3b86cc9144c761b44d5ec2832 | 60,813 |
import socket
from typing import cast
def find_available_port() -> int:
"""Finds a local random unoccupied TCP port."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
_, port = s.getsockname()
return cast(int, port) | 53d98f1a9e6c98d7ad608af53600007bc93f2af8 | 60,814 |
def in_or_none(x, L):
"""Check if item is in list of list is None."""
return (L is None) or (x in L) | bc3e4ef5a8daf7669e7430940e361d4c7ec1a240 | 60,815 |
def recoverDoc(cur):
"""parse an XML in-memory document and build a tree. In the
case the document is not Well Formed, a attempt to build a
tree is tried anyway """
ret = libxml2mod.xmlRecoverDoc(cur)
if ret is None:raise treeError('xmlRecoverDoc() failed')
return xmlDoc(_obj=ret) | 14a8b5031e6f8b3e64730452095656ebc7855a4b | 60,816 |
async def list_keys(request: web.Request) -> web.Response:
"""List keys in the authorized_keys file.
GET /server/ssh_keys
-> 200 OK {"public_keys": [{"key_md5": md5 hex digest, "key": key string}]}
(or 403 if not from the link-local connection)
"""
return web.json_response(
{
... | 0dd5e23b1ef128f436bb61559f5c77420bc2a2f2 | 60,817 |
def score(results, in_label, out_labels, w=1.0, col="probability", neg_only=False):
"""Score kmer from kmer family probabilities.
The scoring method used is as follows:
Score = P(in family) - (w_out * P(out of family)) - P(bg)
Parameters
----------
results : dict or pandas.DataFrame
... | e182d1c0ebd7f8cff7f6e6d982412d549f3a670a | 60,818 |
def patch_forces(patch_ids, forces):
"""
Return a list containing patch forces
"""
return np.bincount(patch_ids.reshape((-1,)),
weights=forces.reshape((-1,)))[1:] | 3aa7b1238216cd35e683b36fdddb94844b28a2d3 | 60,819 |
def get_vaccine_general_summary():
"""Returns DataFrame with a synthesis of COVID-19 vaccines deliveries and administrations in Italy.
Parameters
----------
None
Raises
------
ItaCovidLibConnectionError
Raised when there are issues with Internet connection.
Returns... | 5bf64105648685653941d76a30bed6338b2651e6 | 60,821 |
def r_array_register(line_str, line_pos, line_num):
"""
Read an array of registers.
Args:
line_str (str): The code line.
line_pos (int): The code line position to start reading.
line_num (int): The code line number in the parsed text file.
Returns:
label_array (str): Th... | 6248f51209491889b1356b29a014296200d16a65 | 60,823 |
from .exceptions import error_for
def requires_app_credentials(func):
"""Require client_id and client_secret to be associated.
This is used to note and enforce which methods require a client_id and
client_secret to be used.
"""
@wraps(func)
def auth_wrapper(self, *args, **kwargs):
cl... | 2d43115aba27c8dfb9f210025d6bcdae24504835 | 60,824 |
def reverse_causal(effective_kernel_size: int):
"""Post-padding such that output has no dependence on the past."""
return [0, effective_kernel_size - 1] | 9a09069304376efe72f4e72a2f18b9c0e5d62b1c | 60,825 |
def long_text_filter(row, column, user_data=None):
"""
Uses the format_long_text helper function to trim and prettify some text.
"""
text = row[column]
cols = user_data["cols"]
if text:
text = rabbitvcs.util.helper.format_long_text(text, cols)
return text | 353388dc5614942f74e544de2bc5a9e33a617c99 | 60,826 |
def inceptionresnetv1(**kwargs):
"""
InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for mod... | 4b924256e21096a785d913cce820baeca8209841 | 60,827 |
def _is_pixel_list(data):
"""
Returns True if data is a pixel list, False otherwise.
A pixel list is a 1-dimensional list of pixels where a pixel is a tuple
of 3 ints in the range 0..255
Parameter data: The data to check
Precondition: NONE (data can be anything)
"""
if type(data) != li... | 821fdb166e467a483290312d8bebd22d8cb95922 | 60,829 |
def _clean_timeformat(text):
"""returns an ISO date format from a funny calibre date format"""
if text.endswith("+00:00"):
text = text[:-6] + "+0000"
if text[10] == " ":
text = text.replace(" ", "T", 1)
return text | 03f908e8cc85485496d627248e9dfce2e2ab08f2 | 60,832 |
def statistic_color(color_array):
"""
主要是获取box内的hsv值中h的方差
:param color_array: box对应的矩阵
:return: 返回box的hsv值中h的方差
"""
h_value = color_array[:, :, 0]
s_value = color_array[:, :, 1]
variance = np.var(h_value) + np.var(s_value)
return variance | a6652d56f91bc7b59808cfe00ccb0b662ca46f20 | 60,835 |
import itertools
import json
def create_resources(key_combination, values):
"""
key_combination: a tuple containing a key names' combination (e.g. ('name',) or ('description',) or ('name', 'description'))
values = a list of values which will be combined against key_combination's items (e.g. ['null', '[]']... | 7563cb1eb9758e0ea57494974561192e6c6eef9b | 60,836 |
def build_scheduler(
optimizer: Optimizer,
iters_per_epoch: int,
cfg: CN,
) -> Scheduler:
"""Build learning rate scheduler.
Parameters
----------
optimizer : Optimizer
Target optimizer
iters_per_epoch : int
Number of iterations per epoch
cfg : CN
Global con... | 1c56211504a6573cc19ed772d8370568e87f2bfc | 60,837 |
def resnext50d_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
"""Constructs a ResNeXt50d-32x4d model. ResNext50 w/ deep stem & avg pool downsample"""
default_cfg = default_cfgs["resnext50d_32x4d"]
model = ResNet(
Bottleneck,
[3, 4, 6, 3],
cardinality=32,
bas... | a934cd6947b5efbb53607ac46363894261623693 | 60,838 |
def color_text(text, color_name, bold=False):
"""
This command can be used to colorify command line output. If the shell
doesn't support this or the --disable-colors options has been set, it just
returns the plain text.
Usage:
print "%s" % color_text("This text is red", "RED")
"""
if... | 69f2f4ae7cb07e0bd6e5b99e0adecedf164c49b2 | 60,839 |
def get_previous_non_blank_line(clean_lines, line_number):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
line_number: The number of the line to check.
Returns:
A tuple with two elements. The first ... | 90d29a9bf6914babc69757a9809174e9c4bb6bae | 60,840 |
def get_ssid() -> str:
"""Gets SSID of the network connected.
Returns:
str:
WiFi or Ethernet SSID.
"""
process = Popen(
['/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport', '-I'],
stdout=PIPE)
out, err = process.communicate()
... | d9c158fa5daf5c4c3e327bd9791ccf0448ddce4c | 60,842 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.