content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getfeed(user):
"""Test post
:user: Stuff from the interwebs
:returns: stuff to the interwebs
"""
response = jsonify({'result_count': 'This is ' + user + '\'s feed!'})
response.headers.add('Access-Control-Allow-Origin', '*')
return response | 687e9d723f8a2037aeafbf457411134bab5f54d2 | 3,631,494 |
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
# i... | c18270860e090810a1a7d7aabbd1d2f2957609a2 | 3,631,495 |
def variables_and_orphans(i, o):
"""
Extract list of variables between i and o nodes via
dfs traversal and chooses the orphans among them
Parameters
----------
i : list
Input variables.
o : list
Output variables.
"""
def expand(r):
if r.owner and r not in... | 34ec8ba9b92442462c15d00e0401a71b12de6551 | 3,631,496 |
def get_collected_quotas():
"""获取我的收藏"""
form = PaginationForm().validate_for_api()
per_page = current_app.config['COUNT_DEFAULT']
current_uer = get_current_user()
paginate = paginate_data(current_uer.not_deleted_collected_quotas, form.page.data, per_page)
return jsonify(paginate) | 802ed5593163fbc5c4bffd30d1a8dc2685709438 | 3,631,497 |
import requests
def image_from_url(url):
"""
Download image from url
:param url: url of image
:return: image Pillow object
"""
response = requests.get(url)
return Image.open(BytesIO(response.content)) | d666ba001045eb7bb34d3c37930c97739d9c01d6 | 3,631,499 |
def vect3_scale(v, f):
"""
Scales a vector by factor f.
v (3-tuple): 3d vector
f (float): scale factor
return (3-tuple): 3d vector
"""
return (v[0]*f, v[1]*f, v[2]*f) | 94902cad0a7743f8e3ed1582bf6402229b8a028d | 3,631,500 |
from typing import Optional
def segment_max(data: Array,
segment_ids: Array,
num_segments: Optional[int] = None,
indices_are_sorted: bool = False,
unique_indices: bool = False,
bucket_size: Optional[int] = None,
mode: Opti... | 2e98814bd37be39cc7abadd0cb795471e267d050 | 3,631,501 |
from typing import List
from typing import Any
from typing import Optional
def _recursive_pad(nested: List[Any], fill_value: Optional[Any] = None) -> np.array:
"""Pads a jagged nested list of lists with the given value such that a proper multi-dimensional array can be
formed with rectangular shape. The paddin... | 2ab19444f0b3e2e865d51f24b590de5a1d814c96 | 3,631,502 |
def create_trigger_body(trigger):
"""Given a trigger, remove all keys that are specific to that trigger
and return keys + values that can be used to clone another trigger
https://googleapis.github.io/google-api-python-client/docs/dyn/tagmanager_v2.accounts.containers.workspaces.triggers.html#create
:p... | 3b324407e77c1f17a5f76f82181db4976966e21b | 3,631,503 |
from typing import Union
def is_less_or_equal(hash_1: Union[str, bytes],
hash_2: Union[str, bytes]) -> bool:
"""check hash result."""
if isinstance(hash_1, str):
hash_1 = utils.hex_str_to_bytes(hash_1)
if isinstance(hash_2, str):
hash_2 = utils.hex_str_to_bytes(hash_2)... | 1633aa11587669d67ddd49eae9d73ab061e7e69b | 3,631,504 |
def get_video_id(url):
""" Get YouTube video ID from YouTube URL
Args:
url (str): YouTube URL.
Returns:
YouTube id
"""
if not url:
return ""
# If URL is embedded
if "embed" in url:
return url.split("/")[-1]
parse_result = urlparse(url)
query = par... | 9253bb3c11a4ed0ceaddfcb5b848de9157d9b290 | 3,631,505 |
def _tile_to_image_size(tensor, image_shape):
"""Inserts `image_shape` dimensions after `tensor` batch dimension."""
non_batch_dims = len(tensor.shape) - 1
for _ in image_shape:
tensor = tf.expand_dims(tensor, axis=1)
tensor = tf.tile(tensor, [1] + image_shape + [1] * non_batch_dims)
return tensor | 57b460e58e3e9c705af62c87479ce6d4c81c787b | 3,631,507 |
def icp3d(src, trgt, abs_tol=1e-8, max_iter=500, verbose=True):
"""
Parameters
----------
src : numpy array
Source object. Each row should be a point with (X, Y, Z) columns.
trgt : numpy array
Target object. Each row should be a point with (X, Y, Z) columns.
abs_tol : float, opt... | 969dc9bc2b0fce2933c7a31d45ab98089619e7d1 | 3,631,508 |
def event_type(event):
"""
.. function:: event_type(event)
Return pygame event type.
"""
return getattr(pygame, event) | de49421703a98df43ac57a5beea7acb042eaa8ff | 3,631,509 |
def ULA(step, N, n):
""" MCMC ULA
Args:
step: stepsize of the algorithm
N: burn-in period
n: number of samples after the burn-in
Returns:
traj: a numpy array of size (n, d), where the trajectory is stored
traj_grad: numpy array of size (n, d), where the gradients of t... | 36772e2988f35e408fc72da8bb71a78de602aee8 | 3,631,510 |
def get_display_name(record):
"""Get the display name for a record.
Args:
record
A record returned by AWS.
Returns:
A display name for the bucket.
"""
return record["Name"] | a34c1c416cc41ae5f0087ba471d75b4bc5c87216 | 3,631,513 |
import math
def RadialToTortoise(r, M):
"""
Convert the radial coordinate to the tortoise coordinate
r = radial coordinate
M = ADMMass used to convert coordinate
return = tortoise coordinate value
"""
return r + 2. * M * math.log( r / (2. * M) - 1.) | 1bbfad661d360c99683b3c8fbe7a9c0cabf19686 | 3,631,514 |
from typing import Set
def extract_leaves(
tree_dict: StrDict,
) -> Set[str]:
"""
Extract a set with the SMILES of all the leaf nodes, i.e.
starting material
:param tree_dict: the route
:return: a set of SMILE strings
"""
def traverse(tree_dict: StrDict, leaves: Set[str]) -> None:
... | c932426f8d308a840690347bdd41af402bf6880a | 3,631,515 |
def station_matcher(
data_stream_df,
ses_directory="../data/seattle_ses_data/ses_data.shp"):
""" Matches Purple Air data with census tracts
This function reads in the census-tract-level socioenconomic
dataset and joins it with the input Purple Air DataStreams.
Args:
data_stream_df... | 9b4c1293d7987138d17c9ec6606fff18d4a6e8c6 | 3,631,516 |
def running(pid):
"""
pid: a process id
Return: False if the pid is None or if the pid does not match a
currently-running process.
Derived from code in http://pypi.python.org/pypi/python-daemon/ runner.py
"""
if pid is None:
return False
try:
os.kill(pid, signal.SIG_DFL)
... | 622951e6d5c2f832516e00a607e6ac612ce365a9 | 3,631,517 |
import requests
import json
def get_pulls_list(project, github_api=3):
"""get pull request list
github_api : version of github api to use
"""
if github_api == 3:
url = f"https://api.github.com/repos/{project}/pulls"
else:
url = f"http://github.com/api/v2/json/pulls/{project}"
... | 891c99d53faa5fb89960e5bb52c85e42f6003c42 | 3,631,518 |
import urllib
import json
def get_articles(id):
"""
Function that gets the json response to our url request
"""
get_sources_news_url = source_url.format(id,api_key)
with urllib.request.urlopen(get_sources_news_url)as url:
get_news_data = url.read()
get_news_response = json.loads(ge... | 5a2e2410561302b4023746559edd28102ccaa527 | 3,631,520 |
def read_chunk(path, start_offset, end_offset, delete_me_entire_func_maybe):
"""
Return only if 100% successful.
"""
try:
with open(path, 'rb') as f:
f.seek(start_offset)
return f.read(end_offset - start_offset)
except FileNotFoundError as e:
raise e | e45c948bcb7f75fdf0eecac8289e4323b2d88dfe | 3,631,521 |
def returnBestAddress(genes, loop):
"""Searches for available genes matching kegg enzyme entry.
This function searches 'sequentially'. It returns the best available model
organism genes. Organisms phylogenetically closer to Cricetulus griseus are
preferred, but they are chosen by approximation. A detai... | af38d9456120dbbe99a243764dea20e52d0ba3c1 | 3,631,522 |
from typing import Any
def is_name_like_value(
value: Any, allow_none: bool = True, allow_tuple: bool = True, check_type: bool = False
) -> bool:
"""
Check the given value is like a name.
Examples
--------
>>> is_name_like_value('abc')
True
>>> is_name_like_value(1)
True
>>> i... | f465c0e660399c4c330dc08d24cde479dfd0ff47 | 3,631,523 |
def get_uptime(then):
"""
then: datetime instance | string
Return a string that informs how much time has pasted from the provided
timestamp.
"""
if isinstance(then, str):
then = dt.datetime.strptime(then, "%Y-%m-%dT%H:%M:%SZ")
now = dt.datetime.now()
diff = now - then.replace(... | b1110c9c3edfd4960405b74da8da57e5f455775d | 3,631,524 |
import torch
def gaussian2kp(heatmap, kp_variance='matrix', clip_variance=None):
"""
Extract the mean and the variance from a heatmap
"""
shape = heatmap.shape
#adding small eps to avoid 'nan' in variance
heatmap = heatmap.unsqueeze(-1) + 1e-7
grid = make_coordinate_grid(shape[3:], heatmap... | 5953e9ef4e0717341f01555e227868a5a4b2fc2d | 3,631,526 |
def BRepBlend_HCurve2dTool_Circle(*args):
"""
:param C:
:type C: Handle_Adaptor2d_HCurve2d &
:rtype: gp_Circ2d
"""
return _BRepBlend.BRepBlend_HCurve2dTool_Circle(*args) | e3087d0e9e1505b47d10066b2a4ab25d72b15de2 | 3,631,527 |
import inspect
import math
def patchMath():
""" Overload various math functions to work element-wise on iterables
>>> A = Array([[0.0, pi/4.0], [pi/2.0, 3.0*pi/4.0], [pi, 5.0*pi/4.0], [3.0*pi/2.0, 7.0*pi/4.0]])
>>> print(round(A,2).formated())
[[0.0, 0.79],
[1.57, 2.36],
... | da29f21ee08bfee29d9cd62148384fbd0fa9ede7 | 3,631,528 |
def iddr_rid(m, n, matvect, k):
"""
Compute ID of a real matrix to a specified rank using random matrix-vector
multiplication.
:param m:
Matrix row dimension.
:type m: int
:param n:
Matrix column dimension.
:type n: int
:param matvect:
Function to apply the matri... | 7878a49dfa4e0c7c4530e16fb904a6778ee2aa3d | 3,631,529 |
def MediumOverLong(lengths):
"""
A measure of how needle or how plate-like a molecules is.
0 means perfect needle shape
1 means perfect plate-like shape
ShortOverLong = Medium / Longest
"""
return lengths[1]/lengths[2] | 48a053b55b39a50d7b0f618f843d370a55220765 | 3,631,530 |
import base64
from pathlib import Path
def cbase64(obj, mode: int = 1, to_file: t.Union[str, Path] = None, altchars=None, validate=False):
"""
base64加密与解密
使用示例:
# 1)针对字符
obj = b'这是一个示例'
cobj = crypto.cbase64(obj)
# 2)针对文件
obj = 'D:/tmp/t.txt'
to_file = 'D:/t... | bb70ddb23185e8934c2c31400f4eb0c0adaee202 | 3,631,531 |
def segment_objects(white_cloud):
"""
Cluster extraction and create cluster mask
"""
tree = white_cloud.make_kdtree()
# Create a cluster extraction object
ec = white_cloud.make_EuclideanClusterExtraction()
# Set tolerances for distance threshold
# as well as minimum and maximum cluster ... | 590c3d75a1739128d97e998a601e92e335507915 | 3,631,533 |
def form():
"""Dummy endpoint for demonstration purposes."""
return [
ActionFormField(
name='email_address',
label='Email Address',
description='Email address to send PowerPoint document',
required=True,
),
ActionFormField(
name... | 9b10b3621f39d061c448d3e3d0c512dc0d1639fe | 3,631,535 |
import cmd
def task_pgtune_tune():
"""
pgtune: Apply Greg Smith's pgtune.
"""
def alter_sql():
with open(PGTUNE_CONF, "r") as f:
for line in f:
if "=" in line:
key, val = [s.strip() for s in line.split("=")]
sql = f"ALTER SYS... | 489e8ab45b139620ca621be5600f6c61dbf81210 | 3,631,536 |
def rescale_exchange(exc, value, remove_uncertainty=True):
"""Dummy function to rescale exchange amount and uncertainty.
This depends on some code being separated from Ocelot, which will take a bit of time.
* ``exc`` is an exchange dataset.
* ``value`` is a number, to be multiplied by the existing amo... | b3fee3bc20632563722b624dd35e4fa6a3a5b9c8 | 3,631,537 |
def merge_channels(channels):
""" Takes a list of channels as input and outputs the image obtained by merging the channels """
return channels[0] if len(channels) == 1 else cv2.merge(tuple(channels)) | 7eff099248f40d8c166c711d341834d5db0c1b7f | 3,631,540 |
import warnings
def rng(spec=None, *, legacy=False):
"""
Get a random number generator. This is similar to :func:`sklearn.utils.check_random_seed`, but
it usually returns a :class:`numpy.random.Generator` instead.
.. warning::
This method is deprecated. Use :func:`seedbank.numpy_rng` instea... | 63b6cfa03c336c31f47da7b215888335b37da5e4 | 3,631,541 |
def create_sdcard_tar (adb,tarpath):
"""
Returns the remote path of the tar file containing the whole WhatsApp directory from the SDcard
"""
tarname = '/sdcard/whatsapp_' + ''.join(random.choice(string.letters) for i in xrange(10)) + '.tar'
print "\n[+] Creating remote tar file: %s" % tarname
cm... | 4d01bedc86c18cb43d53ce4c53be06e1eb7b1232 | 3,631,542 |
def roll_zeropad(a, shift, axis=None):
"""
Roll array elements along a given axis.
Elements off the end of the array are treated as zeros.
Args:
a: array_like
Input array.
shift: int
The number of places by which elements are shifted.
axis (int): optional... | 97d29b4aff48580367d6c0ed474ca1ba020e2cf8 | 3,631,544 |
from typing import Callable
from typing import Any
from typing import Coroutine
def callable_to_coroutine(func: Callable, *args: Any, **kwargs: Any) -> Coroutine:
"""Transform callable to coroutine.
Arguments:
func: function that can be sync or async and should be transformed into
corouin... | 44fc48295f61ac0b7c74cfa9d9724473afb272ea | 3,631,545 |
def array_to_binary(array, start=None, end=None):
"""Create binary search tree from `array` values via recursion."""
start = 0 if start is None else start
end = len(array) - 1 if end is None else end
if start > end:
return ''
mid = (start + end) // 2
node = Node(array[mid])
node.left... | 263fc8869961b3412d61288bd5aa562b8221ae37 | 3,631,547 |
async def handle_slack_command(*, db_session, client, request, background_tasks):
"""Handles slack command message."""
# We fetch conversation by channel id
channel_id = request.get("channel_id")
conversation = conversation_service.get_by_channel_id_ignoring_channel_type(
db_session=db_session, ... | 890db0570da2782482c4c1a2aa2772fbada48278 | 3,631,548 |
def load_cert_files(
common_name, key_file, public_key_file, csr_file, certificate_file,
crl_file
):
"""Loads the certificate, keys and revoked list files from storage
:param common_name: Common Name for CA
:type common_name: str, required when there is no CA
:param key_file: key file full path... | fe8a3765e020e91880f6b44791e37b59002eb13e | 3,631,549 |
def parse_note(note: Note) -> MetaEvent:
"""
Parse a single non system note.
"""
attributes = {}
attributes["event"] = "note"
attributes["note_id"] = note["id"]
attributes["content"] = note["body"]
attributes["event_id"] = note["id"]
attributes["noteable_id"] = note["noteable_id"]
... | 8105ca5da84a1fc85fae0351d446b9d1dd9fae4b | 3,631,550 |
def get_mvdr_vector(atf_vector, noise_psd_matrix):
"""
Returns the MVDR beamforming vector.
:param atf_vector: Acoustic transfer function vector
with shape (..., bins, sensors)
:param noise_psd_matrix: Noise PSD matrix
with shape (bins, sensors, sensors)
:return: Set of beamforming ... | 70249a7795c07ed15f351b158cbf6dc1b83895ec | 3,631,551 |
def get_numpy(required=True):
"""Tries to import numpy.
If `required` is False, don't ask again if the user already declined;
return None if numpy is not available.
If `required` is True, do ask to install, and raise ImportError if numpy
can't be set up.
"""
global _numpy
if _numpy is ... | 1cb4486de4231f93b73f1bc649a1a05454faf530 | 3,631,552 |
def norm_pdf(x, mu, sigma):
"""
Return probability density of normal distribution.
"""
z = (x - mu) / sigma
c = 1.0 / np.sqrt(2 * np.pi)
return np.exp(-0.5 * z ** 2) * c / sigma | 12db092dad01331b15366b4819d4fde9e631b8de | 3,631,553 |
import sqlite3
def delete_diagnosis(request):
"""
This method is used to delete diagnosis data in diagnosis table.
Query Explanation:
- Delete data in diagnosis table.
:param request:
:return:
"""
if request.method == 'POST':
con = sqlite3.connect("Hospital.db")
con.row... | 53cf92845c2df00f0fced044bb8faf95530deba6 | 3,631,554 |
def chip_calibration(
data,
mol="O2",
F_cal=None,
primary=None,
tspan=None,
tspan_bg=None,
t_bg=None,
gas="air",
composition=None,
chip="SI-3iv1",
):
"""
Returns obect of class EC_MS.Chip, given data for a given gas (typically air) for which
one component (typically O... | 321ccc5a229c4a9ebf4be80614340e32aef6231c | 3,631,555 |
import string
def tamper(payload, **kwargs):
"""
Unicode-escapes non-encoded characters in a given payload (not processing already encoded) (e.g. SELECT -> \u0053\u0045\u004C\u0045\u0043\u0054)
Notes:
* Useful to bypass weak filtering and/or WAFs in JSON contexes
>>> tamper('SELECT FIELD FRO... | ef293a5be9698dea8f01186a38794ff9c3482c94 | 3,631,556 |
def to_axis_aligned_ras_space(image):
""" Transform the image to the closest axis-aligned approximation of RAS
(i.e. Nifti) space
"""
return to_axis_aligned_space(image, medipy.base.coordinate_system.RAS) | c7bb77a1e141672f2d8ea4ecb76c3b3dd0a00d66 | 3,631,557 |
def _fixParagraphs(element):
"""
moves paragraphs so they are child of the last section (if existent)
"""
if isinstance(element, advtree.Paragraph) and isinstance(element.previous, advtree.Section) \
and element.previous is not element.parent:
prev = element.previous
parent ... | 0875e08afe27171a0bd8773298a320acd93a0382 | 3,631,558 |
def dice_loss(label, target):
"""Soft Dice coefficient loss
TP, FP, and FN are true positive, false positive, and false negative.
.. math::
dice &= \\frac{2 \\times TP}{ 2 \\times TP + FN + FP} \\\\
dice &= \\frac{2 \\times TP}{(TP + FN) + (TP + FP)}
objective is to maximize the d... | 526104e7ba1fd974444b1141913d593e4ee4efb1 | 3,631,559 |
from typing import Union
from typing import List
def no_subseqs(x_tokens: Union[List[str], str]) -> bool:
"""
Checks to see whether a string lacks the subsequences ab, bc, cd,
and dc.
:param x_tokens: A string
:return: True iff x_tokens does not have any subsequences
"""
letters = set()
... | 434dade2ca1801bed0895a79ba281f90e6b78177 | 3,631,560 |
import torch
def _get_random_R():
""" random angle-axis -> Rodrigues """
random_angle_axis = torch.tensor(np.random.rand(1, 3))
return RodriguesBlock()(random_angle_axis).numpy()[0] | 69fd6cfe7a8338941b67b77448941d17cc2c16d0 | 3,631,561 |
from datetime import datetime
def timestamp_to_iso(timestamp):
"""
Converts an ISO 8601 timestamp (in the format `YYYY-mm-dd HH:MM:SS`) to :class:`datetime`
Example:
>>> timestamp_to_iso(timestamp='2020-02-02 02:02:02')
datetime(year=2020, month=2, day=2, hour=2, minute=2, second=2)
... | 7de7ea8b1fd5bd4d854c43b9818bf6f8f58da279 | 3,631,562 |
def rename_category_for_flattening(category, category_parent=""):
"""
Tidy name of passed category by removing extraneous characters such as '_' and '-'.
:param category: string to be renamed (namely, a category of crime)
:param category_parent: optional string to insert at the beginning of the str... | 360e87da0a8a778f32c47adc58f33a2b92fea801 | 3,631,563 |
import math
def billing_bucket(t):
"""
Returns billing bucket for AWS Lambda.
:param t: An elapsed time in ms.
:return: Nearest 100ms, rounding up, as int.
"""
return int(math.ceil(t / 100.0)) * 100 | 87b9963c1a2ef5ad7ce1b2fac67e563dcd763f73 | 3,631,564 |
import hashlib
def filename_to_int_hash(text):
"""
Returns the sha1 hash of the text passed in.
"""
hash_name_hashed = hashlib.sha1(text.encode("utf-8")).hexdigest()
return int(hash_name_hashed, 16) | b5cb53b921146d4ae124c20b0b267acc80f6de43 | 3,631,565 |
def export():
"""Export all components and connected nets, as a netlist in KiCad pcbnew compatible format.
This also saves a database with all captured internal information about
schematic, components and nets. These information are used in subsequent
runs to ensure stable designators.
"""
return export_(_... | 141c670b43f831cc4374692370f5f651445486fb | 3,631,566 |
def dropout(x, rate, training=None):
"""Simple dropout layer."""
if not training or rate == 0:
return x
if compat.is_tf2():
return tf.nn.dropout(x, rate)
else:
return tf.nn.dropout(x, 1.0 - rate) | 77ba40883e76366de27d15fc03f601d7efdcae0b | 3,631,567 |
import re
def readFastQ(fastq_path):
"""
Reads fastq file and returns a dictionary with the header as a key
"""
with open(fastq_path,'r') as FASTQ:
fastq_generator = FastqGeneralIterator(FASTQ)
readDict = {re.sub('/[1-2]','',header).split(' ')[0]:(seq,qual) for header,
... | 4dbcbb8d7ba8a6b5d77c2477c2b97d00d4a9a19c | 3,631,568 |
def dilation(args) -> list:
"""Compute dilation of a given object in a segmentation mask
Args:
args: masks, obj and dilation kernel
Returns:
"""
mask, obj, kernel = args
dilated_img = binary_dilation(mask == obj, kernel)
cells = np.unique(mask[dilated_img])
cells = cells[cells... | f9edc59e4db7e8774916542be887e0ad3a82ec78 | 3,631,569 |
def adjust_lr_on_plateau(optimizer):
"""Decrease learning rate by factor 10 if validation loss reaches a plateau"""
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr']/10
return optimizer | 615631fd4853e7f0c0eae59a3336eb4c4794d3a3 | 3,631,570 |
from typing import List
from typing import Dict
from typing import Any
from typing import Union
def get_partial_match_metrics(
preds: List[List[str]], labels: List[List[str]]
) -> Dict[Any, Any]:
"""
Suppose there are N such pairs in the gold data and the system predicts M such pairs. Say a ‘partial match... | 05eaf9fce152e6266698e9b5613a2770a000c48d | 3,631,572 |
def find_submission_id_command(
client: Client,
limit: int = 50,
filter: str = "",
offset: str = "",
sort: str = "",
) -> CommandResults:
"""Find submission IDs for uploaded files by providing an FQL filter and paging details.
:param client: the client object with an acce... | e7e285c8d2b10af6ab7d0337cb0db7bea2664478 | 3,631,573 |
def chain(node1, node2, include_ids=False, only_ids=False):
"""
Find a chain of dependency tags from `node1` to `node2` (if possible)
:param node1: The node 1
:type node1: udon2.Node
:param node2: The node 2
:type node2: udon2.Node
"""
node, chain = node2, ... | bcfe1497ea731ad902bc5760542c8ce6f3286b60 | 3,631,575 |
def parallax(sc, d2p=True, **kw):
"""Parallax.
Parameters
----------
sc: SkyCoord
** warning: check if skycoord frame centered on Earth
d2p: bool
if true: arg = distance -> parallax_angle
else: arg = parallax_angle -> distance
Returns
-------
parallax_angle o... | d2d79dd67a07e71ef6a411fd4567c591335cbe83 | 3,631,576 |
def dense(x, output_dim, reduced_dims=None, expert_dims=None,
use_bias=True, activation=None, name=None):
"""Dense layer doing (kernel*x + bias) computation.
Args:
x: a mtf.Tensor of shape [..., reduced_dims].
output_dim: a mtf.Dimension
reduced_dims: an optional list of mtf.Dimensions of x t... | 1303b164c266759f617f6abf3cfba07fdeff5ccd | 3,631,577 |
import select
def requires_cuda_enabled():
"""Returns constraint_setting that is not satisfied unless :is_cuda_enabled.
Add to 'target_compatible_with' attribute to mark a target incompatible when
@rules_cuda//cuda:enable_cuda is not set. Incompatible targets are excluded
from bazel target wildcards ... | aec9d4c9ed55c44aaf0f6d3e6862bf6b0c24471e | 3,631,579 |
from typing import Union
from typing import Any
from typing import Callable
import warnings
def add_activated_handler(parent : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True) -> Union[int, str]:
"""
Adds... | d3b107b0cd1d1fef195590a01d923adf8e84ee24 | 3,631,580 |
def application(service, custom_app_plan, custom_application, request):
"""First application bound to the account and service_plus"""
plan = custom_app_plan(rawobj.ApplicationPlan(blame(request, "aplan")), service)
return custom_application(rawobj.Application(blame(request, "app"), plan)) | dc27ecd53a276bf194e92c6ee716b94fa2cf1445 | 3,631,583 |
def printf_line(*args):
"""printf_line(int indent, char format, v(...) ?) -> bool"""
return _idaapi.printf_line(*args) | a1a9214f6c4013d3654187724839b6aeed1c4220 | 3,631,584 |
import logging
def baseline_correction_using_plane(coh_ab,uw_phase,kz):
""" Baseline correction based on a plane
WARNINGS:
- From choi idl code
- We should really check with TAXI the baseline correction for a better processing
Parameters
----------
coh_ab : 2D numpy array
... | f8d812bb019d0d96d23440d51315aaa40448a5b2 | 3,631,585 |
def variable(default=None, dependencies=(), holds_data=True):
"""
Required decorator for data_dict of custom structs.
The enclosing class must be decorated with struct.definition().
:param default: default value passed to validation if no other value is specified
:param dependencies: other items (string or ... | fdc11425beddaf47985cea7729244ac073922794 | 3,631,587 |
def define_circle(p1, p2, p3):
"""
Returns the center and radius of the circle passing the given 3 points.
In case the 3 points form a line, returns (None, infinity).
"""
temp = p2[0] * p2[0] + p2[1] * p2[1]
bc = (p1[0] * p1[0] + p1[1] * p1[1] - temp) / 2
cd = (temp - p3[0] * p3[0] - p3[1] *... | aedb4bc6173df09962ab81a4124acbd245af7612 | 3,631,588 |
def create_upload_token(self, request, form):
""" Create a new upload token. """
layout = ManageUploadTokensLayout(self, request)
if form.submitted(request):
self.create()
request.message(_("Upload token created."), 'success')
return morepath.redirect(layout.manage_model_link)
... | feba475900a01e3984fed7d49b3c6709e8b82bd8 | 3,631,589 |
def vertical_channel_region_detection(image):
"""
:param image:
:return:
"""
f = spectrum_bins_by_length(image.shape[1])
ft_h_s = tunable('channels.vertical.recursive.fft_smoothing_width', 3,
description="For channel detection (recursive, vertical), spectrum smoothing widt... | f70b702df3ab52c1d0c538c55cb1df180b003df2 | 3,631,590 |
def image_output_size(input_shape, size, stride, padding):
"""Calculate the resulting output shape for an image layer with the specified options."""
if len(size) > 2 and input_shape[3] != size[2]:
print("Matrix size incompatible!")
height = size[0]
width = size[1]
out_depth = size[3] if le... | 77665f8304570bd5ba805241131a96d5d6908587 | 3,631,592 |
import re
from typing import Tuple
def _info_from_match(match: re.Match, start: int) -> Tuple[str, int]:
"""Returns the matching text and starting location if none yet available"""
if start == -1:
start = match.start()
return match.group(), start | 3599c6345db5ce2e16502a6e41dda4684da2f617 | 3,631,593 |
def otherICULegacyLinks():
"""The file `icuTzDir`/tools/tzcode/icuzones contains all ICU legacy time
zones with the exception of time zones which are removed by IANA after an
ICU release.
For example ICU 67 uses tzdata2018i, but tzdata2020b removed the link from
"US/Pacific-New" to "America/Los_Ang... | bfacf0d8b5a31c5edbd69f93c4d55d8857599e1a | 3,631,594 |
def _postprocess_gif(gif: np.ndarray):
"""Process provided gif to a format that can be logged to Tensorboard."""
gif = np.clip(255 * gif, 0, 255).astype(np.uint8)
B, T, C, H, W = gif.shape
frames = gif.transpose((1, 2, 3, 0, 4)).reshape((1, T, C, H, B * W))
return frames | c9adb9c2d56dc437ee0e6b0aa7482da4e430aa2e | 3,631,595 |
def format_meta(metadictionary):
"""returns a string showing metadata"""
returntext = EMPTYCHAR
returntext += 'SIZE' + BLANK + COLON + BLANK + str(metadictionary['size'])+EOL
returntext += 'USER' + BLANK + COLON + BLANK + str(metadictionary['user'])+EOL
returntext += 'DATE' + BLANK + COLON + BLAN... | e24f6846a8d9470899e74099a56780b0a16a7e76 | 3,631,596 |
def accumulating_income():
"""
Real Name: Accumulating Income
Original Eqn: Income
Units: Month/Month
Limits: (None, None)
Type: component
Subs: None
"""
return income() | 9753c68223f351629deefbb46266b051952e31e5 | 3,631,598 |
def fake_map_matrix_T_without_enemy(map, mySide):
"""
伪造一个没有敌方坦克的地图类型矩阵
WARNING:
首先检查是不是对方 tank ,因为可能遇到对方已经死亡或者两方坦克重合
这种时候如果己方坦克恰好在这个位置,就会被删掉,assert 不通过
"""
map_ = map
oppSide = 1 - mySide
cMatrixMap = map_.matrix_T.copy()
for oppTank in map_.tanks[oppSide]:
if (... | 3930ce8bf3dffb2f5f0edac44afa5f8d112a6cac | 3,631,600 |
def dict_factory(cursor, row):
"""
Factory function to convert a sqlite3 result row in a dictionary
:param cursor: cursor object
:param row: a row object
:return: dictionary representation of the row object
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row... | 133ac7df43b8bf2b173257c3ca2ed095def84a90 | 3,631,601 |
def ndcgREval(data, gt, gf):
"""
Compute NDCG@R, where R is the number of relevant documents
"""
ideal = generate_ideal(gt,gf)
dcgScore = dcg(data[:(gt)])
norm = dcg(ideal[:(gt)][:len(data)])
if(norm == 0): print('norm=0 in ndcgREval')
return dcgScore / norm | 4583fb030ab9548bbc30726090e4ea9ad31f9dca | 3,631,602 |
def create_modifiers(y_position):
"""Create all creatable modifiers"""
def create():
for mod in rt.modifier.classes:
try:
created = mod()
print(created)
box = create_box()
rt.addModifier(box, created)
yield box
... | 2eb8f02304d79ce3f948a8150c1de51f8cfb8dcb | 3,631,603 |
from typing import List
def queue_busy_workers(queue: str) -> List[str]:
"""
This function counts the number of busy workers for a given queue.
"""
return [
worker.name
for worker in rq.Worker.all(queue=queue)
if worker.state == "busy"
] | 77de2195323420a664f2a3e16aad7200c5317b49 | 3,631,604 |
def coste(theta, X, Y):
"""
cost function
computes J(theta) for a given dataset
"""
m = np.shape(X)[0]
H = sigmoid((np.dot(X,theta)))
J = -1/m * ( np.log(H).transpose().dot(Y)
+ np.log(1-H).transpose().dot(1-Y))
return J | 21de5da396c5778842eb81abda8a7ab2a974426b | 3,631,605 |
import re
def replace_php_define(text, define, value):
"""
Replaces a named constaint (define) in PHP code.
Args:
text (str) : The PHP code to process.
define (str) : Name of the named constant to modify.
value (int,str) : Value to set the 'define' to.
Returns:
... | 02e3194d6fb83958d525651cdca6e3cec1cf3bb7 | 3,631,607 |
def data_method(func):
"""
Decorate object methods by tagging them as data methods.
The generated data class will have the decorated methods in them.
.. code:: python
>>> from objetto.applications import Application
>>> from objetto.objects import Object, attribute, data_method
... | 2a41d343265c0f745242c0e8a369473e22413f8f | 3,631,609 |
def get_frontend_names():
"""Return the names of all supported frontends
Returns
-------
list : list of str
A list of frontend names as strings
"""
return [frontend.name() for frontend in ALL_FRONTENDS] | c251ea7361987d8f9acaa31e3dbfd805a965d94c | 3,631,610 |
from gkutils.commonutils import getColour, getColourStats
import json
def getColourPlotData(g, r, i, z, y):
"""Collect the colour info from input filter data for plotting"""
colourPlotLimits = {}
coloursJSON = []
grColour = []
riColour = []
izColour = []
colourPlotLabels = [{'label': 'g-... | 37192d4d10ff2cc454d41ae7c91b2e9e87b98d4e | 3,631,612 |
def show(*args, **kwargs):
"""Wrapper for make_figure()"""
return make_figure(*args, **kwargs) | 143d1778fd3dbf1e63612bafafa596d86632c969 | 3,631,613 |
def set_title(node, title):
"""Sets the title of a link or image node. Returns 1 on success, 0 on failure.
Args:
node (cmark_node): The node to set the title attribute on
title (string): Title as string
Returns:
int: 0 on failure, 1 on success
"""
title=to_c_string(... | b6d1b289e22a768914436ab9a30e2f7036415ad1 | 3,631,614 |
def get_image(filename, convert_rgb=True):
"""Returns numpy array of an image"""
image = Image.open(filename)
# sometime image data is gray.
if convert_rgb:
image = image.convert("RGB")
else:
image = image.convert("L")
image = np.array(image)
return image | e7d760515cae8309dd7c5fe65c27eeaf0759391d | 3,631,615 |
def find_order_to_apply_confirmation(domain, location):
"""
Tries to find the EmergencyOrder that the receipt confirmation applies to.
:param domain: the domain to search
:param location: the SQLLocation that the confirmation is coming from
:return: the EmergencyOrder that the confirmation should ap... | 8ec732ae4338ff6fdde73096127f6bafb66f41bb | 3,631,616 |
def tiny(tmpdir):
"""Create a tiny fake brain."""
# This is a minimal version of what we need for our viz-with-timeviewer
# support currently
subject = 'test'
subject_dir = tmpdir.mkdir(subject)
surf_dir = subject_dir.mkdir('surf')
rng = np.random.RandomState(0)
rr = rng.randn(4, 3)
... | 9cf3999cf343f2d2005613e668223183e57d4955 | 3,631,617 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.