content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _transpose_batch_time(x):
"""Transposes the batch and time dimensions of a Tensor.
If the input tensor has rank < 2 it returns the original tensor. Retains as
much of the static shape information as possible.
Args:
x: A Tensor.
Returns:
x transposed along the first two dimensions... | dfd4640b576f900e28027700eceed0daa0cf5fc3 | 81,221 |
import copy
def repeat(network_or_layer, n):
"""
Function copies input `n - 1` times and connects everything in sequential
order.
Parameters
----------
network_or_layer : network or layer
Layer or network (connection of layers).
n : int
Number of times input should be rep... | 44096c1f6f13876bb5ef36c610c775825f60df8d | 81,222 |
def normder(n,m):
"""coefficient of d^m / dx^m x^n"""
c=1
for i in range(m):
c*=n-i
return c | a57afadd4bccff28471e30654473e05265ebdeb1 | 81,223 |
def yices_bvsub(t1, t2):
"""Constructs the bitvector term (t1 - t2), returning return NULL_TERM (-1) if there's an error.
bvsub(t1, t2):
Both arguments must be bitvector terms of the same size.
Error reports
if t1 or t2 is not valid
code = INVALID_TERM
term1 = t1 or t2
if t1 o... | 83c0293aae6c781a89024751b38458baae64be98 | 81,225 |
def _safe_decode(output_bytes: bytes) -> str:
"""
Decode a bytestring to Unicode with a safe fallback.
"""
try:
return output_bytes.decode(
encoding='utf-8',
errors='strict',
)
except UnicodeDecodeError:
return output_bytes.decode(
encoding... | 0f4b3d9e04b910d0ccfa2fde12e209901cadf52c | 81,226 |
def DeleteDeployment(deployment_full_name):
"""Calls into the DeleteDeployment API.
Args:
deployment_full_name: the fully qualified name of the deployment.
Returns:
A messages.OperationMetadata representing the long-running operation.
"""
client = GetClientInstance()
messages = client.MESSAGES_MOD... | 322e14575791999dc468b2a739938b75a74d508a | 81,227 |
import json
def heartbeat():
"""heartbeat"""
print("heartbeat called")
return (json.dumps({
"success": True,
"config": {
"name": SERVICE_RECOMMENDATION_NAME,
"url": SERVICE_RECOMMENDATION_HOST,
"port": SERVICE_RECOMMENDATION_PORT
}
})) | d1575d15d85804c9b84fd31f5f808c1523272d57 | 81,228 |
def check_have_space(data, _):
"""An attacker has space if there is no defender in the same grid square"""
for opponent in data["opposition"]:
if opponent["coordinates"] == data["attacker"]["coordinates"]:
print(f"{opponent['name']} is closing down {data['attacker']['name']}.")
r... | a4e734f41b1b6c93351501a0bf29e3b7a2c430c0 | 81,230 |
def send_publisher_update_request_inprogress_email(application):
"""Tell the publisher the UR is underway"""
journal_title = application.bibjson().title
owner = models.Account.pull(application.owner)
send_list = [
{
"name" : owner.name,
"email" : owner.email,
... | 5df5520770b8f5a19e603d2f70f719339b5832fe | 81,231 |
def get_current_image() -> str:
"""Returns the current image tag"""
return f"{IMAGE}:{get_current_tag()}" | a10e4258543926da8268269453c798c9f07582ea | 81,232 |
from typing import List
import csv
def tokenize_comments(ruddit: str) -> List[List[str]]:
"""
Reads ruddit(csv), tokenizes the comments and removes the stop words
from them and returns a list containing the tokenized comments.
:param ruddit: Path to the csv containing the dataset.
:return tokeniz... | be71efd186f1a0b09862f41ed016006888f164cc | 81,233 |
def extract_description_for(values, ranks, thresholds, comparison_string):
""" Report values from df_with_ranks[col] by thresholds.
:param values: Series containing values, indexed by probe_id
:param ranks: Series containing ranks, indexed by probe_id
:param thresholds: Thresholds for reporting out tho... | 8ff4dc7454c91e30b7dc2bc1b79b934169b946c5 | 81,234 |
def hub(hub_pod):
"""Return the jupyterhub Hub object for passing to Spawner constructors
Ensures the hub_pod is running
"""
return Hub(ip=hub_pod.status.pod_ip, port=8081) | ef66a50547a7f30c4727b7261e1eac44544d3cfb | 81,235 |
def example_batch_to_list(example_batch, num_templates):
"""Convert a single batch item in a dataset to a list of items.
Say you have a dataset where each item is shape {question: (), answer: ()}.
An example_batch will be a batched example with shape {question: (None,),
answer: (None,)}.
This will convert th... | c0eba5fee52ba59de2d59844810ccc58ace9a805 | 81,236 |
import types
def detect_face(face_file, max_results=1):
"""Uses the Vision API to detect faces in the given file.
Args:
face_file: A file-like object containing an image with faces.
Returns:
An array of Face objects with information about the picture.
"""
# [START vision_face_detec... | be1b9fab9907cd4b51a6394ff1d74f5279949ec4 | 81,237 |
from typing import Sequence
def get_rank_upto(
ranks: Sequence[str], ter_rank: str, include_terminal: bool = False
) -> Sequence[str]:
"""Generates list of ranks from `ranks` terminated at `ter_rank`
Parameters
----------
ranks
List of ranks
ter_rank
Terminal rank
include_... | 9f5e21dbc80652c444e3f049d7e0bb40aca76203 | 81,239 |
import torch
def advantage(rewards, values):
"""
Computes the advantage of the given returns as compared to the estimated values, optionally using GAE.
"""
if GAE_LAMBDA == 0:
returns = discounted(rewards, GAMMA)
advantage = returns - values
else:
# Generalized Advantage Es... | ba96171fd1c88ee02aa0cba4c542820fe9fa34e6 | 81,240 |
import re
import io
from zipfile import ZipFile
def get_dflo(url, syspath):
"""Return a Delayed FLO """
if url.is_archive:
# Create a DelayedFlo for the file in a ZIP file. We might have to find the file first, though
def _open(mode='r', encoding=None):
zf = ZipFile(syspath)
... | b9428bf2932fca08c7b42d9bfd97bff2947e280c | 81,242 |
import re
def StripColor(string):
"""Returns string with color escape codes removed."""
regex = re.compile(r'\x03(?:\d{1,2}(?:,\d{1,2})?)?', re.UNICODE)
return regex.sub('', string) | 04a253edf0842a2bda44d8c124445158588215e7 | 81,244 |
def getImageFilePathName(annotationDict, newWidth, newHeight):
"""
getImageFilePathName returns the file path and file name for the
new cropped and resized image.
Given image 'n02085620_7' resized to 64 x 64,
it will return:
'F:/dogs/images/n02085620-Chihuahua/boxes_64_64/n02085620_7_box_6... | a59c6980d540826568bc673fabf0d3fb91d4b0ea | 81,245 |
def sumar(a, b):
""" Sumar dos números a y b """
z = a+b
return z | 40c820dcddeb4b97d8de0f111313b37e47c5002c | 81,246 |
import socket
from typing import Tuple
import time
import struct
import errno
def recvfrom_blob(sock: socket.socket,
timeout: int = SOCKET_OPERATION_TIMEOUT) -> Tuple[bytes, str]:
"""
Receive DNS message from TCP/UDP socket.
"""
# deadline is always time.monotonic
deadline = tim... | 3af8bff7a2267aa4adedde84ef86613b1547c618 | 81,247 |
def rd(line_number, row, col, key, default = None):
""" Return Row data by column name """
if key in col:
if col[key] >= len(row):
LOG.warning("missing '%s, on line %d" % (key, line_number))
return default
retval = row[col[key]].strip()
if retval == "":
... | 4c545e0fd316d2a783599e49f71560976ba698cb | 81,248 |
def controlseq(s): #was the_controlseq
"""Parser for a particular control sequence 's'.
s includes the backslash."""
return any_controlseq().if_value(s) | 301422b78138dbdb6cc095936a661261976f0d81 | 81,249 |
def create_ffphenotype(chromo):
""" Receives a chromosome and returns its phenotype (a neural network) """
# first create inputs
neurons_list = [Neuron('INPUT', ng.id, 0, 0) \
for ng in chromo.node_genes[:chromo.sensors] if ng.type == 'INPUT']
# Add hidden nodes in the right order
... | 3f32d500bfcc6fbfbed9f0ab945edc6e1054dec5 | 81,250 |
def get_xModel() -> "XModel":
"""
Gets xModel
Returns:
object: Gets xModel for current LibreOffice instance
"""
global _star_xmodel
if _star_xmodel == None:
bas: SF.SFScriptForge.SF_Basic = SF.CreateScriptService("Basic")
bas.ThisComponent.CurrentController.Frame
... | 815939d785ac8587412bc25524b3771dbb86234e | 81,251 |
from typing import List
from typing import Tuple
from typing import Dict
def _load_variables_impl(
config: Text,
hosts: List[Tuple[int, Text]],
variables: Dict[Text, Dict[Text, tf_variables.Variable]],
table_config: tpu_embedding_v2_utils.TableConfig):
"""Load embedding tables to onto TPU for each t... | b7811d7e00f9b6a574097767bbae722c835832ff | 81,253 |
def landau_spectrum(x, fs, detrend_ord=1):
"""
Get the spectrum of behavioral data as in Landau & Fries (2012)
The paper doesn't specifically mention detrending, but A.L. says they
always detrend with a 2nd-order polynomial. That matches the data --
without detrending, there should have been a peak... | c3d8d61f769ce2ddefee422bde8cbcb7a4662f35 | 81,254 |
def get_runtime_stats() -> RuntimeStats:
"""Computer and return the runtime statistics object."""
return RuntimeStats(
len(db['active-targets']),
len(db['sublemon'].running_subprocesses)) | d557a022102630c67a7c0f47dea12baa41508a75 | 81,255 |
from typing import List
def scan_to_point_equivalency(points_per_scan: int) -> List[EquivalencyType]:
"""Astropy units equivalency, between scan and point.
Parameters
----------
points_per_scan
Number of observation points per 1 scan.
Examples
--------
>>> eq = neclib.units.scan_... | c1dc5b442b04258fc1cb69736b537f14831e02cb | 81,257 |
def read_ply(fname):
""" Reads the vertex and triangle data stored in a .ply file.
Parameters
----------
fname: str
Name of the file to read from.
Returns
-------
P : (num_verts,3) float array
The coordinates of the vertices of the me... | 0e17746464a9b85ac2cf0813ec259bae61a5ca42 | 81,258 |
def whats_my_color_handler(handler_input):
"""Check if a favorite color has already been recorded in
session attributes. If yes, provide the color to the user.
If not, ask for favorite color.
"""
# type: (HandlerInput) -> Response
if color_slot_key in handler_input.attributes_manager.session_att... | aacd7a9817595f9de3c515580839f5f38d471dfd | 81,259 |
def list_srvs(package, rospack=None):
"""
List srvs contained in package
:param package: package name, ``str``
:param rospack: an optional rospack instance to be reused, ``rospkg.RosPack``
:returns: list of srvs in package, ``[str]``
"""
return list_types(package, mode=MODE_SRV, rospack=rosp... | d7e163bcb987ba8cf95b923dc1b05b6555e3ddac | 81,260 |
from datetime import datetime
def sweep_chart(config_id):
""" Generates sweep charts for given config ID.
User can also provide "sweep" that is one of the following:
* network - Sweeps across network types.
* p_mutate
"""
start = datetime.datetime.now()
sweep = request... | 7ac00e727e2c62cee9f4d2f87f1900a3ce595d43 | 81,261 |
def derive_key(data, salt, length=32):
"""
Derive key from given data and salt.
Example:
```
print(i6.crypto.derive_key(i6.crypto.uuid(), os.urandom(16)))
```
"""
if isinstance(data, str):
data = data.encode()
if isinstance(salt, str):
salt = salt.encode()
kdf ... | 17367d6b1fb9020a014c4ebd9317e485fd08797d | 81,263 |
import numpy
from pathlib import Path
import uuid
def execute(out_dir, wkt, product):
"""
Inputs:
wkt -- wkt -- 92/WKT String
product -- product -- 45/User String
Outputs:
result -- result -- 45/User String
Main Dependency:
mep-wps/uc-bundle-1
Software Dependencies:
pywps-4
... | 52c54f175a2e467a682fac24ceb8699b06fad8d8 | 81,265 |
async def metadata_name(name: str):
"""
Returns the all the metadata from the named commons.
"""
res = await datastore.get_all_named_commons_metadata(name)
if res:
return res
else:
raise HTTPException(
HTTP_404_NOT_FOUND,
{"message": f"no common exists wit... | 71e18535a32b52887a87500434e574a568ab7c61 | 81,266 |
def indent(string, nspaces):
""" Indents a multiline string. Required for Python 2,
import textwrap textwrap.indent works for Python 3
"""
pad = nspaces * ' '
indented_string = ''.join(pad+line for line in string.splitlines(True))
return indented_string | 531ce33bdf62a220bfddb02228953b424495919c | 81,267 |
from typing import Any
def new_token(**kwargs: Any) -> str:
"""Url to request a new token."""
return _NEW_TOKEN.format(**kwargs) | b11712867f749153df7cfe05593b45cfe4f12e01 | 81,268 |
import torch
def default_output_fn(prediction, accept):
"""A default output_fn for PyTorch. Serializes predictions from predict_fn to JSON, CSV or NPZ format.
Args:
prediction: a prediction result from predict_fn
accept: type which the output data needs to be serialized
Returns: output d... | 02aeaf928f6418fc80b00d5321e64ed4ec4acb9c | 81,269 |
import torch
from typing import Optional
from functools import reduce
def _dice_from_confmat(
confmat: torch.Tensor,
num_classes: int,
ignore_index: Optional[int] = None,
absent_score: float = 0.0,
reduction: str = "elementwise_mean",
) -> torch.Tensor:
"""Computes Dice coefficient from confus... | 2a3b3583ed917bde4ef34effc1a39072b14c726d | 81,270 |
def init():
"""
Return name/link dict
@return: name-to-link dict
"""
with open('table.json') as data_file:
url_table = json.load(data_file)
if url_table is None or len(url_table) <= 0:
print('\033[91m' + ' There is no item in table.json ' + '\033[0m')
os.sys.exit(0)
... | 970a5bcfdeb0b087b3cbaa397d43a79c78bc3d06 | 81,271 |
def get_auc(classification_type, y_true, y_pred, num_classes=None):
"""
Compute the AUC (Area Under the receiver operator Curve).
:param classification_type: the type of classification.
:param y_true: the true labels.
:param y_pred: the scores or predicted labels.
:return: AUC score.
"""
... | c8962b9c4b17e200bee8b42d8bc1af778dbac2b4 | 81,272 |
def getlocal():
"""
This return default machine ip address.
>> from IPToolz import getIP
>> getIP('www.instagram.com')
127.0.0.0
"""
return Web('localhost') | 826d2e051b37427a34b05e53a3f5b44c354da990 | 81,273 |
def fdr_by(alpha, pvals, I):
"""False discovery rate of Benjamini-Yekutieli"""
L = I * (I - 1) / 2.
pvals_rank = rank.rankdata(pvals, reverse=True)
denom = 1 / np.arange(1, L + 1)
fdr = pvals_rank * alpha / denom
return fdr | f1d4a032ced376945b88281854abe2b65086efdb | 81,274 |
def byteswap_array(array):
""" FITS files are stored in big-endian byte order. All modern CPUs are
little-endian byte order, so at some point you have to byteswap the data.
Some FITS readers (cfitsio, the fitsio python module) do the byteswap when
reading the data from disk to memory, so we get numpy ar... | ac667cfb40ec021ae83236705d5445cb6c81bdc6 | 81,275 |
def int_to_c(k, x_width):
"""
Takes an integer and a width and returns a complex number.
"""
ik = k >> x_width
qk = k % pow(2, x_width)
maxint = pow(2, x_width)-1
i = int_to_f(ik, x_width)
q = int_to_f(qk, x_width)
return i + (0+1j)*q | 11b83045e51ea23e37c1143a66c55ed198d26f84 | 81,276 |
def mutate_json(obj, path, func, ask_permission=False, **kwargs):
"""Mutates a nested iterable object in-place by applying func to obj[path].
*obj*: an object containing arbitrarily nested iterables.
*path*: a tuple of keys or indices to follow through the object.
*func*: a function to apply to the c... | 2ebac16e5b8db56a28db5e82035b0a0e9c02762f | 81,277 |
def max_filter(seq, default=None):
"""Returns the max value from the sequence."""
if len(seq):
return max(seq)
return default | 0d2205e49b3c795dda1429e6e698f7a3366c0085 | 81,278 |
def hex_to_bin(hex_str: str, width: int = 32) -> str:
"""Converts hex string to binary string
Parameters
----------
hex_str : str
hexadecimal string to convert
width : int, optional
width of binary output (used for zero padding), default=32
Returns
-------
str
... | 4ad8046e2cd97e04824239feb997381108d67e37 | 81,279 |
def classinstmethod(func):
""" Allows the wrapped method to be called both ways - as class's method or as instance's method """
@wraps(func)
def wrapper(*args, **kwargs):
klass = None
klassname = func.__qualname__.split('.')[0]
if args:
firstarg = args[0]
if f... | f23cdc292ddcb5858dab27a204468c955650d6b8 | 81,280 |
import google
import json
def register_model_id(credentials, model_id=None):
"""Register a Model ID for use with the Google Assistant SDK.
If no Model ID is given, one is generated based on the project name. The
Model ID will be registered if it has not been already registered for this
project. To ch... | a0df1ab678182ed159f08473aae5967368c6667a | 81,281 |
def test_valid_substitutions():
"""Test the perform_substitutions() function with valid input."""
context = LaunchContext()
class MockSubstitution(Substitution):
def perform(self, context):
return 'Mock substitution'
mock_sub = MockSubstitution()
sub_mock_sub = perform_substit... | 7ac9c8d2d0ac6cbb2ba09e2e37ec4c861a277722 | 81,282 |
import math
def cramers_V_calc(phi_square, classes):
"""
Calculate Cramer's V.
:param phi_square: phi_squared
:type phi_square: float
:param classes: confusion matrix classes
:type classes: list
:return: Cramer's V as float
"""
try:
return math.sqrt((phi_square / (len(clas... | 0a0091234a80a7085b46cc46569521cef127cbc8 | 81,283 |
def now():
"""
Returns:
int: Current timestamp
"""
return int(t.time()) | d878c1af9c84b64c38ef98d80dab127af5799bd0 | 81,284 |
def load_broombridge(file_name: str) -> Broombridge:
"""
Loads a Broombridge data file.
"""
logger.info(f"Loading broombridge data from '{file_name}'.")
data = qsharp.client._execute(f'%chemistry.broombridge {file_name}', raise_on_stderr=True)
return Broombridge(data) | e9835bdba2c124f2855e77dced4de78bb06b567f | 81,286 |
from typing import Union
from pathlib import Path
def calculate_release_number(spec_or_path: Union[str, Path]) -> int:
"""Calculate release number of a package.
This number can be passed into the %autorelease macro as
%_rpmautospec_release_number.
:param spec_or_path: The spec file or directory it i... | 8a26fe2dd721f005e1da57fd332ef4aec06579d8 | 81,287 |
def get_boto_session(region_name=None):
""" Get session with correct region
"""
if region_name is None:
region_name = auto_find_region()
return botocore.session.Session(session_vars=dict(
region=('region', 'AWS_DEFAULT_REGION', region_name, None))) | e39281e2edd2e52612d59855a7e8347fa48618f8 | 81,288 |
def update():
"""
not currently in use, previously was used to have a user update
their username despite the name of the endpoint
if their id was in session and logged_in and is_authenticated were True
"""
form = Update()
if request.method == 'POST':
g.user = User.query.get(session['... | a4114365234782048e841107dd26ab0bb7eab508 | 81,289 |
def draw(atom, width=300, height=300):
""" Draw a 2D and 3D viewer with this atom highlighted (notebook only)
Args:
width (int): width of viewer in pixels
height (int): height of viewer in pixels
Returns:
HBox: viewer object
"""
viz2d = atom.draw2d(width=width, height=heigh... | 6c15e5f8ad978829b3ce1863981cee49e1991123 | 81,290 |
def flatten_list(alist, howdeep=1):
"""Flattens nested sequences."""
if howdeep > 0:
newlist = []
for nested in alist:
try:
newlist.extend(nested)
except TypeError:
newlist.append(nested)
howdeep -= 1
alist = flatten_list(ne... | 93eb5734d979c0fc32ead0c43893b898f63b7929 | 81,291 |
def SSE(y: np.ndarray, y_hat: np.ndarray) -> float:
"""
Computes the sum of squared errors.
:param y: real data
:param y_hat: prediction
:return: sum of squares errors
"""
e = y - y_hat
return float(np.sum(e * e)) | cfd09084817603c9b2c48b7a1e9a563a5820f551 | 81,292 |
import itertools
def _test_int_sparse_tensor_types() -> bool:
"""Tests the supported integer sparse tensor type combinations.
Checks the supported combination of (type, pointer-bitwidth, index-bitwidth)
where type is an integer type.
For integer types, we only support the cases where pointer-bitwidth and
... | 7a63b7e77cae321e180f9538e93dc536522021bf | 81,293 |
def inside_triangles(tris, points, check=True, surface_offset=False, cloth=None):
"""Can check inside triangle.
Can find barycentric weights for triangles.
Can find multiplier for distance off surface
from non-unit cross product."""
origins = tris[:, 0]
cross_vecs = tris[:, 1:] - origins[:, ... | 230b36ca46f7bf5635b3840b89415684f0c955c4 | 81,294 |
def to_list(ret, get_all=False, start=0, end=GlobalValues.query_limit, values=list()):
"""
将指定QuerySet转换为列表。
:param ret: 指定QuerySet
:param get_all: 是否取切片
:param start: 查询结果切片的起点
:param end: 查询结果切片的终点
:param values: 查询结果切片的终点
:return: 转换后的列表,列表中的对象均为字典对象
"""
if ret is None:
... | de38b8e0eca8d5175ec02d860de898bc63c4cd41 | 81,297 |
def get_private_vocabulary(corpus_path, dataset_distance, budget):
"""create a private vocabulary
This function combines get_bounded_vocabulary and privatize_vocabulary
The constituent functions are separate to facilitate integration with popular tokenizers
"""
word_counts = get_bounded_vocabulary(c... | 18d433aafdf9b56216ae3eeb958fcb528c90b6ba | 81,298 |
def _ExpandExpression(stack):
"""Expands the postfix versions of stack into an expression.
This whole recursive function depends on a very complex data structure that
is used to represent any linear expression. The data structure is as follows:
[list of pairs, constant]
For example the polynomial, ax + by ... | b7b76a577fd2dee1144042105ff669cdb7f05e58 | 81,299 |
def velocity_contour(
adata,
ptkey='pseudotime',
rank_transform=True,
use_ends=False,
fill=True,
levels=10,
basis=None,
vkey='velocity',
density=None,
smooth=None,
pt_smooth=None,
min_mass=None,
arrow_size=None,
... | 4003f63356054140745a6a5ed6fd8bce7da333ac | 81,300 |
def test_annotated_input_func_5a_except(use_validator):
""" the function with annotated more complex input type (ty.Dict in ty.Dict)
list is provided as a dict value (instead a dict), so error is raised
"""
@mark.task
def testfunc(a: ty.Dict[str, ty.Dict[str, float]]):
return sum(a["el1... | b01c308907aff3642a136b3e8777c2344fa43fa5 | 81,301 |
def hinge_loss(f_x,y_true,margin=1):
"""
Compute the hinge loss given the returned value from
a linear discrimination function on the feature x and its label y
"""
return max(0,margin-y_true*f_x) | aa0f938e623c08c78ffad3d27f9a7e0e229d99fc | 81,302 |
def _configure_learning_rate(num_samples_per_epoch, global_step):
"""Configures the learning rate.
Args:
num_samples_per_epoch: The number of samples in each epoch of training.
global_step: The global_step tensor.
Returns:
A `Tensor` representing the learning rate.
Raises:
ValueError: if
... | ce1752738712f7f351bc761abc135718f71a7c71 | 81,303 |
def delete_by_id(
group_id: int,
preset_id: int,
member: MemberModel = Depends(get_active_member),
db: Session = Depends(get_db),
):
"""
Delete preset by id
"""
service.delete_by_id(db, id=preset_id)
return preset_id | 80552cd62e3fa92e60c3427d0dcb0baf27280fd6 | 81,304 |
def wwPDBServer(*key):
"""Set/get `wwPDB`_ FTP/HTTP server location used for downloading PDB
structures. Use one of the following keywords for setting a server:
+---------------------------+-----------------------------+
| wwPDB FTP server | *Key* (case insensitive) |
+================... | c37b6a2a41ac1efea419ff39964c8fa86adf693d | 81,305 |
def getType(polygonID):
"""getType(string) -> string
Returns the (abstract) type of the polygon.
"""
return _getUniversal(tc.VAR_TYPE, polygonID) | 18c06878b4b8f8533717b2d47d12b10b7fa80b77 | 81,306 |
def _exception_to_nan(func):
"""Decorate function to return nan if it raises an exception"""
def wrap(*a, **kw):
try:
return func(*a, **kw)
except Exception:
return np.nan
return wrap | 95d4b5fd6297f1fab41e92513c62e23b295ba3dd | 81,307 |
def create_model():
"""Creates a BERT model"""
op = a.Adam(learning_rate=0.00001)
# Use the BERT transformer
# Then use a dense layer as the output
input_ids = Input(shape=(MAX_LEN,), dtype=tf.int32, name="input_ids")
BERT_layer = TFBertModel.from_pretrained("bert-large-uncased")
BERT_outpu... | c1f6d2b01bd08111683010643b06ebcb286a58b5 | 81,308 |
def send_email_api():
"""
:return:
"""
# 如果前端不关注结果,只是把任务发到中间件,那就使用 send_email.push(msg='邮件内容') 就可以了。
async_result = send_email.publish(dict(msg='邮件内容'), priority_control_config=PriorityConsumingControlConfig(is_using_rpc_mode=True)) # type: RedisAsyncResult
return async_result.task_id
# re... | 7758713b08cc499ebb456e719a9b829839f479ef | 81,309 |
def calc_theta(r, z):
"""Zenith angle ranging from [0, pi]"""
return np.arctan2(r, z) | f09cc277dffc099d71a9a84dd59c69e02401e4b1 | 81,310 |
import re
def find_potential_topics(sentence):
"""
sentence: a list of words/punctuation as returned by gutenberg.sents
First pass: Remove stopwords
"""
def is_word(w):
return re.match('\w+', w)
no_stopwords = [word for word in sentence if word not in stopwords.words('english') and i... | e443160a27593212d92cb90f06ef179af250d588 | 81,311 |
def make_toy_data(data_name, n_samples=1000, random_state=None, **maker_kwargs):
"""Make simple toy datasets.
Useful for illustrating density destructors.
Parameters
----------
data_name : str
Should be one of the following strings: ``{'concentric_circles',
'grid', 'gaussian_grid',... | cd13764df0906596499d65c0ea6191f826b68ee8 | 81,312 |
def is_light_node(node: HomeeNode):
"""Determine if a node is controllable as a homee light based on it's profile and attributes."""
return (
node.profile
in [
NodeProfile.DIMMABLE_LIGHT,
NodeProfile.DIMMABLE_COLOR_LIGHT,
NodeProfile.DIMMABLE_EXTENDED_COLOR_LI... | 52ee583093d6a2194a79f002865b6fe86ab992a5 | 81,313 |
def location_refinement(st1, st2, ontology, entities_refined):
"""Return True if there is a location-aware refinement between stmts."""
if type(st1) != type(st2):
return False
if isinstance(st1, Event):
event_ref = event_location_refinement(st1, st2, ontology,
... | cc3548ff831777652807f80e18e4ed05e125488e | 81,314 |
def interpolate_coordinates(old_coord, new_coord, brush_size):
"""Interpolates coordinates depending on brush size.
Useful for ensuring painting is continuous in labels layer.
Parameters
----------
old_coord : np.ndarray, 1x2
Last position of cursor.
new_coord : np.ndarray, 1x2
... | 98c70fffe82fbbba05f6fe63424402ebd908691c | 81,315 |
def create_http_input_channels(channel, credentials_file):
# type: (Optional[Text], Optional[Text]) -> List[InputChannel]
"""Instantiate the chosen input channel."""
if credentials_file:
all_credentials = read_yaml_file(credentials_file)
else:
all_credentials = {}
if channel:
... | 9aaae797d10ed27eb8b667649a940df1079f4391 | 81,316 |
def get_scopes(token_id):
"""Returns the scopes of an application.
Args:
token_id (int): ID of the OAuth Token.
Returns:
scopes: (list).
"""
with db.engine.connect() as connection:
result = connection.execute(sqlalchemy.text("""
SELECT scopes
FROM o... | 7129e2a8c2ed8e3b5b9e0cac1754e6b352d01767 | 81,317 |
import requests
def trp_get_fulldoc_md(doc_id, base_url=base_url, col_id=col_id, page_id="1", user=user, pw=pw):
""" Helper function to interact with TRANSKRIBUS document endpoint
:param user: Your TRANSKRIBUS user name, e.g. my.mail@whatever.com
:param pw: Your TRANSKRIBUS password
:param... | 4fd6288f131bf17c78ab5a4a0b8aefcc2acd430a | 81,318 |
def read_tile(bundle, offset):
"""
Read tile bytes at offset position in bundle.
Parameters
----------
bundle: ArcGIS tile bundle file
offset: offset in bytes to beginning of tile data block (first 4 bytes are length)
Returns
-------
tile_bytes: bytes (may be empty)
"""
bu... | 208615a53cd878c1ce9b371fd835b2628a0957d8 | 81,319 |
def tile_2d_over_nd(feature_vector, feature_map):
""" Repeat the same feature vector over all spatial positions of a given feature map.
The feature vector should have the same batch size and number of features as the feature map.
"""
n, c = feature_vector.size()
spatial_size = feature_map.dim() - 2
tiled ... | 0d6810b943d6ed62b7981e738a7d3f30ba27d4f7 | 81,320 |
from typing import List
import re
def get_folder_structure(path: str) -> List[PathElement]:
"""Parse a folder path string into path elements.
A path element example is::
{
"folder_name": "Some string",
"object_type": "cmis:folder"
}
:param path: The folder path s... | 71f051965482f6bd0ed6b126e287c841061b2688 | 81,321 |
def find_p4_point(a: float, b: float, c: float, n: float, h: float, p7: Point) -> Point:
"""
:param a:
:param b:
:param c:
:param n:
:param h:
:param p7:
:return:
"""
x = p7.x + (a * h) / n
y = p7.y + (b * h) / n
z = p7.z + (c * h) / n
return Point(x, y, z) | e25eec8efac521b7ef6de5244394ed9aa9dafe67 | 81,322 |
def compute_DtD(D, n_channels=None):
"""Compute the DtD matrix
"""
if D.ndim == 2:
return _compute_DtD_uv(D, n_channels)
return _compute_DtD_D(D) | 0d71f4000e2c004399d72348d7d1a2b02b16945f | 81,323 |
import scipy
import numpy
def hesstocov(matrix):
"""Convert Hessian matrix to covariance matrix estimate."""
hessfac = scipy.linalg.cho_factor(matrix, check_finite=False)
covh = lmultiply_inv(hessfac, numpy.eye(matrix.shape[0]))
return covh + covh.T | fa2e8a45854659ba54b70a8b6fca723009842fab | 81,325 |
def get_memory(pid=None,virtual=False):
"""This function uses '/proc/pid/status' to get the memory consumption of a process """
try:
if pid is None: pid = os.getpid()
mem,units = shell_command('cat /proc/%s/status | grep Vm%s'%(pid,'Size' if virtual else 'RSS')).lower().strip().split()[1:3]
... | 075c389d2b465addf76bfe78fb9f644bde27a382 | 81,326 |
import re
def _all_metadata(path, num):
"""
processes metadata from a (RESEDA) PAD or TOF file
"""
valuereo = re.compile("[+-]?\d+[\.e+-]{0,2}\d*")
unitreo = re.compile("\s[A-Za-z]{1,4}$") # strip " "
currentkey = "binarydump"
metadict = {currentkey : {}}
with open(path(num))... | a43091691597093df188ca600db16b92a13d6b28 | 81,327 |
def fortune():
"""Simple wrapper for 'fortune'. No args"""
return exec_proc(["fortune"]) | 159d1e44becbb7b22480aace098409c323c7fb85 | 81,328 |
def _apply_version_patches(qt_version):
"""
Apply version-only specific stylesheet patches for the same binding.
Args:
qt_version (str): Qt string version.
Returns:
str: stylesheet string (css).
"""
version_fix = ""
major, minor, patch = qt_version.split('.')
major, mi... | bacf51b7e6b3b08df3c23f5bd26568d6cb032585 | 81,330 |
def split3(text, pat1, pat2):
"""Split text in 3 parts: before pat1, between, and after pat2."""
part1, text = text.split(pat1, 1)
part2, part3 = text.split(pat2, 1)
return part1, part2, part3 | 5b8bff3b7214a1ac4999bfdc913082a98d1ed1b7 | 81,331 |
def re_tag(name, remote=False, commit=None):
"""Add a local tag with that name at that commit
If no commit is given, at current commit on cuurent branch
If remote is true, also push the tag to origin
If tag already exists, delete it, then re-make it
"""
if remote:
tags = run('ls-remote... | 17d783fa4103af3497619b9fc4f1993095a1d71b | 81,332 |
import json
def loads(json_string, encoding='utf-8'):
"""json.loads returns `unicode object` for a string, you can use this function to do encoding
:param json_string: a well-formed string
:param encoding: a string that represents the encoding you want, like 'utf-8', 'gbk'...
:return: an object that ... | 37f088ac7c2317e89480913ba8946d04b9c5739c | 81,333 |
from typing import Collection
def to_json(record, extraneous=True, prop=None):
"""JSON conversion function: a 'visitor' function which implements marshall
out (to JSON data form), honoring JSON property types/hints but does not
require them. To convert to an actual JSON document, pass the return value
... | da6763b77aac08980e474b7b27b5de06d55437cd | 81,334 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.