content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def gelu(input_tensor):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
input_tensor: float Tensor to perform activation.
Returns:
`input_tensor` with the GELU activation applied.
"""
#... | fd6de5888839521118c42d2e046b526f7025c70d | 18,018 |
import torch
def KPConv_ops(query_points,
support_points,
neighbors_indices,
features,
K_points,
K_values,
KP_extent,
KP_influence,
aggregation_mode):
"""
This function creates a graph of op... | 29fbb193fef31cdd3bdfcf4df212c56eae32cb3e | 18,019 |
def kerneleval(X_test, X_train, kernel):
"""
This function computes the pariwise distances between
each row in X_test and X_train using the kernel
specified in 'kernel'
X_test, X_train: 2d np.arrays
kernel: kernel parameters
"""
if kernel is None:
return X_train
fn = kernel... | 7cdba3af72dab288c9efac757905c51ed5f9a5f6 | 18,020 |
def aks_show_snapshot_table_format(result):
"""Format a snapshot as summary results for display with "-o table"."""
return [_aks_snapshot_table_format(result)] | 174deb4bdbe1da27826c89b4bd187e5aa8a00216 | 18,021 |
def poly_prem(f, g, *symbols):
"""Returns polynomial pseudo-remainder. """
return poly_pdiv(f, g, *symbols)[1] | 4360e2bb4afc7d49f12b411aa18d2d5a1786306b | 18,023 |
def gen_input_code(question, id):
"""
Returns the html code for rendering the appropriate input
field for the given question.
Each question is identified by name=id
"""
qtype = question['type']
if qtype == 'text':
return """<input type="text" class="ui text" name="{0}"
... | b76bea45c0ce847d664a38694732ef0b75c2a53c | 18,024 |
def orbit_position(data, body='sun'):
"""calculate orbit position of sun or moon for instrument position at each time in 'data' using :class:`ephem`
Args:
data: :class:`xarray.Dataset`, commonly Measurement.data
body (optional): name of astronomical body to calculate orbit from ('sun' or 'moon'... | 98ab63c20026d83010b10db7ef141d6f1c9bf55f | 18,025 |
def list_inventory (inventory):
"""
:param inventory: dict - an inventory dictionary.
:return: list of tuples - list of key, value pairs from the inventory dictionary.
"""
result = []
for element, quantity in inventory.items():
if quantity > 0:
result.append ((element, qua... | 264f8cde11879be8ace938c777f546974383122c | 18,026 |
def wsd_is_duplicated_msg(msg_id):
"""
Check for a duplicated message.
Implements SOAP-over-UDP Appendix II Item 2
"""
if msg_id in wsd_known_messages:
return True
wsd_known_messages.append(msg_id)
if len(wsd_known_messages) > WSD_MAX_KNOWN_MESSAGES:
wsd_known_messages.popl... | acd0c1b7de00e6e5ef2a04ff15c1906a5c543089 | 18,027 |
import json
def sliding_tile_state():
"""
Return the current state of the puzzle
:return: JSON object representing the state of the maze puzzle
"""
json_state = {'sliding_tile': sliding_tile.array(), 'solver': sliding_tile_str_solver, 'steps': sliding_tile_steps,
'search_steps': ... | 8438ab4066e4a70b33873fee39667251da0823fc | 18,029 |
import json
def _json_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a JSON object to a numpy array.
Args:
string_like (str): JSON string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
... | accdb28572ed13e6e977d569a69e4dfe27e22e21 | 18,030 |
import json
import time
def connect(**kwargs):
"""
A strategy to connect a bot.
:param kwargs: strategy, listener, and orders_queue
:return: the input strategy with a report
"""
strategy = kwargs['strategy']
listener = kwargs['listener']
orders_queue = kwargs['orders_queue']
asset... | fd2c2637e9eb02356e441994d214d86ec77f56f1 | 18,031 |
def create_env(env, render=False, shared=False, maddpg=False, evaluate=False):
"""Return, and potentially create, the environment.
Parameters
----------
env : str or gym.Env
the environment, or the name of a registered environment.
render : bool
whether to render the environment
... | 8c43a177418b7b9317d2ebcd4155edf5a58b5afe | 18,032 |
def measure_approximate_cost(structure):
""" Various bits estimate the size of the structures they return. This makes that consistent. """
if isinstance(structure, (list, tuple)): return 1 + sum(map(measure_approximate_cost, structure))
elif isinstance(structure, dict): return len(structure) + sum(map(measure_approx... | 8adbd962e789be6549745fbb71c71918d3cc8d0c | 18,033 |
def make3DArray(dim1, dim2, dim3, initValue):
"""
Return a list of lists of lists representing a 3D array with dimensions
dim1, dim2, and dim3 filled with initialValue
"""
result = []
for i in range(dim1):
result = result + [make2DArray(dim2, dim3, initValue)]
return result | c4972ff72fe751d131e4d840b12905d2383299c2 | 18,034 |
import math
def generate_boxes(bounds=(-1, -1, 1, 1), method='size', size=math.inf):
"""
Generate a stream of random bounding boxes
Has two methods for generating random boxes:
- *size* - generates a random central point (x0, y0)
within the bounding box, and then draws widths and heig... | 4cb4ae7fd179b466054c21d7512a1861652476c0 | 18,035 |
def create_assets(asset_ids, asset_type, mk_parents):
"""Creates the specified assets if they do not exist.
This is a fork of the original function in 'ee.data' module with the
difference that
- If the asset already exists but the type is different that the one we
want, raise an error
- Start... | 7be92642b6863f19039ed92d6652027ccd43d4ba | 18,036 |
def decoration(markdown: str, separate: int = 0) -> str:
"""見出しが使われているマークダウンをDiscordで有効なものに変換します。
ただたんに`# ...`を`**#** ...`に変換して渡された数だけ後ろに改行を付け足すだけです。
Parameters
----------
markdown : str
変換するマークダウンです。
separate : int, default 1
見出しを`**`で囲んだ際に後ろに何個改行を含めるかです。"""
new = ""
... | f76a21b093a00d04d1e95fc733a0956722737d51 | 18,037 |
import hashlib
def get_fingerprint(file_path: str) -> str:
"""
Calculate a fingerprint for a given file.
:param file_path: path to the file that should be fingerprinted
:return: the file fingerprint, or an empty string
"""
try:
block_size = 65536
hash_method = hashlib.md5()
... | b0ee4d592b890194241aaafb43ccba927d13662a | 18,038 |
def set_publish_cluster_args(args):
"""Set args to publish cluster
"""
public_cluster = {}
if args.public_cluster:
public_cluster = {"private": False}
if args.model_price:
public_cluster.update(price=args.model_price)
if args.cpp:
public_cluster.update(cr... | a1a5842093daf4d6de9bc9cdfae0cf7f9f5a0f5c | 18,039 |
def _get_iforest_anomaly_score_per_node(children_left, children_right, n_node_samples):
"""
Get anomaly score per node in isolation forest, which is node depth + _average_path_length(n_node_samples). Will
be used to replace "value" in each tree.
Args:
children_left: left children
childr... | d567d083d8e1914e4aee809092fd81e08e74f98d | 18,041 |
def get_invalid_value_message(value_name: str, value: str, line_no: int, uid: str, expected_vals: "list[str]") -> str:
"""
Returns the formatted message template for invalid value while parsing students data!
"""
msg = f"Invalid {value_name} <span class=\"font-weight-bold\">{value}</span>\
o... | cb7dc84b566bb117fe53ce5956919978558ccbbf | 18,042 |
def compute_score_for_coagulation(platelets_count: int) -> int:
"""
Computes score based on platelets count (unit is number per microliter).
"""
if platelets_count < 20_000:
return 4
if platelets_count < 50_000:
return 3
if platelets_count < 100_000:
return 2
if plate... | dc6e9935555fbb0e34868ce58a8ad8bc77be8b0c | 18,043 |
def check_horizontal_visibility(board: list):
"""
Check row-wise visibility (left-right and vice versa)
Return True if all horizontal hints are satisfiable,
i.e., for line 412453* , hint is 4, and 1245 are the four buildings
that could be observed from the hint looking to the right.
>>> che... | b84ff29fde689069ba5e92b10d54c8f0528aa321 | 18,044 |
import requests
def _get_soup(header, url):
"""This functions simply gets the header and url, creates a session and
generates the "soup" to pass to the other functions.
Args:
header (dict): The header parameters to be used in the session.
url (string): The url address to create the ses... | 22ad8876bdd19d405398272cfe0d4429f4b6ac9a | 18,045 |
import json
def get_text_block(dunning_type, language, doc):
"""
This allows the rendering of parsed fields in the jinja template
"""
if isinstance(doc, string_types):
doc = json.loads(doc)
text_block = frappe.db.get_value('Dunning Type Text Block',
{'parent': dunning_type, 'language': language},
['... | 31775b402a943e0c735d65a3c388503a6e03b37e | 18,047 |
def group_create_factory(context, request):
"""Return a GroupCreateService instance for the passed context and request."""
user_service = request.find_service(name="user")
return GroupCreateService(
session=request.db,
user_fetcher=user_service.fetch,
publish=partial(_publish, reques... | 3928a35a74d1f62e4a6f5e38087fce72e7ebbc95 | 18,050 |
def verify(params, vk, m, sig):
""" verify a signature on a clear message """
(G, o, g1, hs, g2, e) = params
(g2, X, Y) = vk
sig1 , sig2 = sig
return not sig1.isinf() and e(sig1, X + m * Y) == e(sig2, g2) | 7413d9172d383c3602cbc2b8348c4ace61c40302 | 18,051 |
def generate_data(n):
"""
生成训练数据
"""
X, y = make_classification(n_samples=n, n_features=4)
data = pd.DataFrame(X, columns=["x1", "x2", "x3", "x4"])
data["y"] = y
return data | 0bf9cac1cf94c6bf8c12cb605f3bfcd6cde10a0d | 18,053 |
def blsimpv(p, s, k, rf, t, div=0, cp=1):
"""
Computes implied Black vol from given price, forward, strike and time.
"""
f = lambda x: blsprice(s, k, rf, t, x, div, cp) - p
result = brentq(f, 1e-9, 1e+9)
return result | 30ad8274aa40f50460cc7f52095ead8ef5021c9a | 18,054 |
def container_describe(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /container-xxxx/describe API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Containers-for-Execution#API-method%3A-%2Fcontainer-xxxx%2Fdescribe
"""
return DXHTTPRequest('... | e56126b67880a316a84ab81cbcd208844282f0f5 | 18,055 |
from typing import Union
from typing import Dict
def nested(fields: Union[Dict[str, Dict], DataSpec], **config) -> dict:
"""
Constructs a nested Field Spec
Args:
fields: sub field specifications
config: in kwargs format
Returns:
the nested spec
"""
spec = {
"... | 3cba172e642b968aabbeb7ee1f2c21d217f443e2 | 18,056 |
from typing import List
def objects_from_array(
objects_arr: np.ndarray, default_keys=constants.DEFAULT_OBJECT_KEYS
) -> List[btypes.PyTrackObject]:
"""Construct PyTrackObjects from a numpy array."""
assert objects_arr.ndim == 2
n_features = objects_arr.shape[1]
assert n_features >= 3
n_obje... | eeabc05132fa04f826c65d204f2d97ded625189a | 18,058 |
def run_policy(env, policy, scaler, logger, episodes):
""" Run policy and collect data for a minimum of min_steps and min_episodes
Args:
env: ai gym environment
policy: policy object with sample() method
scaler: scaler object, used to scale/offset each observation dimension
... | 8d723d13d10b15fda3a2da3591b663ec3c1b81b8 | 18,059 |
def load_data():
"""Load database"""
db = TinyDB(DATABASE_PATH)
data = db.all()
return pd.DataFrame(data) | 5fba31fb66f1ccb86125902e8a39fe2c0247f741 | 18,060 |
def plotcmaponaxis(ax, surf, title, point_sets=None):
"""Plot a Surface as 2D heatmap on a given matplotlib Axis"""
surface = ax.pcolormesh(surf.X, surf.Y, surf.Z, cmap=cm.viridis)
if point_sets:
for x_y, z, style in point_sets:
ax.scatter(x_y[:, 0], x_y[:, 1], **style)
ax.set_xlabe... | 9d462c745cc3a5f2142c29d69ddba1b4f96f6cab | 18,061 |
def get_log_storage() -> TaskLogStorage:
"""Get current TaskLogStorage instance associated with the current application."""
return current_app.config.get("LOG_STORAGE") | 30e4e8d6c61196ee94d519cff020d54d47b2ddbf | 18,062 |
def test_optional_posonly_args1(a, b=10, /, c=100):
"""
>>> test_optional_posonly_args1(1, 2, 3)
6
>>> test_optional_posonly_args1(1, 2, c=3)
6
>>> test_optional_posonly_args1(1, b=2, c=3) # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: test_optional_posonly_args1() g... | 8986d0718e65988f109b31bf5f7ce8fdcd65c833 | 18,063 |
def _build_schema_resource(fields):
"""Generate a resource fragment for a schema.
Args:
fields (Sequence[google.cloud.bigquery.schema.SchemaField): schema to be dumped.
Returns:
Sequence[Dict]: Mappings describing the schema of the supplied fields.
"""
return [field.to_api_repr() f... | 34a32c9b1707062d202a1fd9f98cdd4dc0cb11ae | 18,064 |
def flatten_swtn(x):
""" Flatten list an array.
Parameters
----------
x: list of dict or ndarray
the input data
Returns
-------
y: ndarray 1D
the flatten input list of array.
shape: list of dict
the input list of array structure.
"""
# Check input
if... | 2f8e0b17c462dd97eaa3cd69104164cdcf533cdc | 18,065 |
def crossing(series, value, **options):
"""Find where a function crosses a value.
series: Series
value: number
options: passed to interp1d (default is linear interp)
returns: number
"""
interp = interp1d(series.values, series.index, **options)
return interp(value) | 5318975ad28280e6aff4c0dbd944daf0dd2a24d1 | 18,067 |
import math
def equilSoundSpeeds(gas, rtol=1.0e-6, maxiter=5000):
"""
Returns a tuple containing the equilibrium and frozen sound speeds for a
gas with an equilibrium composition. The gas is first set to an
equilibrium state at the temperature and pressure of the gas, since
otherwise the equilibr... | c2b10fe05cc2f19e50b5ed8934c463768ec16c8e | 18,068 |
import time
import click
def benchmark(partitioner_list: list, item_list: list, bucket_list: list, iterations: int = 1,
begin_range: int = 1, end_range: int = 10, specified_items_sizes: list = None, verbose: bool = False)\
-> pd.DataFrame:
"""
Args:
Returns:
Raises:
"""
... | 08e4d00fa57bada7297c509ead2a2e45f1fb5cc7 | 18,069 |
def adj_by_strand(genes):
"""
liste: list of hmm gene with homogenous strand
Check if the gene is in tandem with another and if so store the gene inside a set obj.TA_gene.linked
In parallel it clean up the list obj.TA_gene.genes
by removing the genes that forme a tandem. Then TA_gene.genes has only ... | 2836375fadf46b445098ddecf3aaf1884dad8efc | 18,070 |
def register_user():
""" register a user and take to profile page """
form = RegisterForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
email = form.email.data
first_name = form.first_name.data
last_name = form.last... | 2f1f875d3c35589d8efc1e069a8d050b931a5f51 | 18,071 |
def stack_init_image(init_image, num_images):
"""Create a list from a single image.
Args:
init_image: a single image to be copied and stacked
num_images: number of copies to be included
Returns:
A list of copies of the original image (numpy ndarrays)
"""
init_images = []
... | 2cf26723bdbf53921ff053308e408bd84ec03edb | 18,072 |
def f5(x, eps=0.0):
"""The function f(x)=tanh(4x)+noise"""
return np.tanh(4*x) + eps * np.random.normal(size=x.shape) | 02025ed30032b1e8de9ecbca4238170e5adff4b1 | 18,075 |
def get_next_event(game, players):
"""
return None if a player has to move before the next event
otherwise return the corresponding Event enum entry
"""
active_player = get_active_player(players, game.finish_time)
if active_player is None:
return None
planet_rotation_event = (
... | 955082da6a3c0ec8b0ee50e149e7251651584352 | 18,076 |
def max_width(string, cols, separator='\n'):
"""Returns a freshly formatted
:param string: string to be formatted
:type string: basestring or clint.textui.colorred.ColoredString
:param cols: max width the text to be formatted
:type cols: int
:param separator: separator to break rows
:type se... | 49521ec4521b639e71b3fc5212738cc6e4d93129 | 18,078 |
import base64
def aes_encrypt(text, sec_key):
"""
AES encrypt method.
:param text:
:param sec_key:
:return:
"""
pad = 16 - len(text) % 16
if isinstance(text, bytes):
text = text.decode('utf-8')
text += pad * chr(pad)
encryptor = AES.new(sec_key, 2, '0102030405060708')
... | 55340a7f1fcf37c58daaf3a72db70344159fbf30 | 18,079 |
def get_value_at_coords(matrix, x, y):
"""Returns the value of the matrix at given integer coordinates.
Arguments:
matrix {ndarray} -- Square matrix.
x {int} -- x-coordinate.
y {int} -- y-coordinate.
Returns:
int -- Value of the matrix.
"""
offset = matrix_offset(m... | 92e96f276025e21bc8643eb96ce03fd191285c93 | 18,080 |
def rms(vector):
"""
Parameters
----------
vector
Returns
-------
"""
return np.sqrt(np.mean(np.square(vector))) | 9d4888050e7f048a8d2ca5b92fa638d5c8d24eb7 | 18,081 |
def parse(text):
"""Parse a tag-expression as text and return the expression tree.
.. code-block:: python
tags = ["foo", "bar"]
tag_expression = parse("foo and bar or not baz")
assert tag_expression.evaluate(tags) == True
:param text: Tag expression as text to parse.
:param... | 202951a1023557e3405b8f5d4d06084e798ae12c | 18,082 |
import itertools
def average_distance(points, distance_func):
"""
Given a set of points and their pairwise distances, it calculates the average distances
between a pair of points, averaged over all C(num_points, 2) pairs.
"""
for p0, p1 in itertools.combinations(points, 2): # assert symmetry... | 236735da94e902dd7fbe062de8abb9a02208156f | 18,083 |
def get_bin_alignment(begin, end, freq):
"""Generate a few values needed for checking and filling a series if
need be."""
start_bin = get_expected_first_bin(begin,freq)
end_bin = (end/freq)*freq
expected_bins = expected_bin_count(start_bin, end_bin, freq)
return start_bin, end_bin, expecte... | 0ff46d4d8df2d7fd177377621c69bac95f23eb9f | 18,084 |
def TagAndFilterWrapper(target, dontRemoveTag=False):
"""\
Returns a component that wraps a target component, tagging all traffic
coming from its outbox; and filtering outany traffic coming into its inbox
with the same unique id.
"""
if dontRemoveTag:
Filter = FilterButKeepTag
else:
... | 83329d0c3f6bbf872ba65d31f7b2111c60a768e7 | 18,085 |
import requests
import json
def tweets(url):
"""tweets count"""
try:
twitter_url = 'http://urls.api.twitter.com/1/urls/count.json?url=' + url
r = requests.get(twitter_url, headers=headers)
json_data = json.loads(r.text)
return json_data['count']
except:
return 0 | 07e10d4b1ddad8cf74d79dc21fbc8dbfe1c38428 | 18,086 |
def CLJPc(S):
"""Compute a C/F splitting using the parallel CLJP-c algorithm.
CLJP-c, or CLJP in color, improves CLJP by perturbing the initial
random weights with weights determined by a vertex coloring.
Parameters
----------
S : csr_matrix
Strength of connection matrix indicating the... | 3ef11327120a71123e51b702c5452e8036f581d5 | 18,087 |
def displayTwoDimMapPOST():
"""Run displayTwoDimMap"""
executionStartTime = int(time.time())
# status and message
success = True
message = "ok"
plotUrl = ''
dataUrl = ''
# get model, var, start time, end time, lon1, lon2, lat1, lat2, months, scale
jsonData = request.json
model... | 7b0402b66538b7b5d987c1385d9ac12df82fac66 | 18,088 |
def encrypt(msg, hexPubkey):
"""Encrypts message with hex public key"""
return pyelliptic.ECC(curve='secp256k1').encrypt(
msg, hexToPubkey(hexPubkey)) | 30befcf48d0417f13a93ad6d4e9f8ccf0fdbeae5 | 18,089 |
def indexing(zDatagridLeft,zDatagridRight,zModelgridLeft,zModelgridRight):
"""
Searches for closest distances between actual and theorectical points.
zDatagridLeft = float - tiled matrix (same values column-wise) of z coordintates
of droplet on left side, size = [len(z... | d14b0037a4898fc12524aba0a29231a545dfed8a | 18,090 |
def torch2np(tensor):
"""
Convert from torch tensor to numpy convention.
If 4D -> [b, c, h, w] to [b, h, w, c]
If 3D -> [c, h, w] to [h, w, c]
:param tensor: Torch tensor
:return: Numpy array
"""
array, d = tensor.detach().cpu().numpy(), tensor.dim()
perm = [0, 2, 3, 1] if d == 4 el... | 23acaa7b4e58d7891e77c22f29b7cbdc7a9a80d0 | 18,091 |
from typing import Any
import array
import numpy
def message_to_csv(msg: Any, truncate_length: int = None,
no_arr: bool = False, no_str: bool = False) -> str:
"""
Convert a ROS message to string of comma-separated values.
:param msg: The ROS message to convert.
:param truncate_leng... | 10ab4c7482c2fbf6e4335daaf0359390ed215152 | 18,093 |
def create_message(username, message):
""" Creates a standard message from a given user with the message
Replaces newline with html break """
message = message.replace('\n', '<br/>')
return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username) | d12807789d5e30d1a4a39c0368ebe4cf8fbde99e | 18,094 |
def overlaps(sdf, other):
"""
Indicates if the intersection of the two geometries has the same shape
type as one of the input geometries and is not equivalent to either of
the input geometries.
========================= =========================================================
**Argument** ... | 14cad072b3b11efe4c4f14d7fc14e053a262f904 | 18,095 |
from django.contrib.auth.views import redirect_to_login
def render_page(request, page):
"""Рендер страницы"""
if page.registration_required and not request.user.is_authenticated:
return redirect_to_login(request.path)
# if page.template:
# template = loader.get_template(page.template)
... | 6e11ea24ee9dc9cf7e1cf8df3bfc192715202044 | 18,096 |
def _whctrs(anchor):
"""
Return width, height, x center, and y center for an anchor (window).
"""
w = anchor[2] - anchor[0] + 1
h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (w - 1)
y_ctr = anchor[1] + 0.5 * (h - 1)
# 16,16, 7.5, 7.5
return w, h, x_ctr, y_ctr | ae3f3d7c486b1698f31ecce301f0e2c2f8af5e84 | 18,097 |
def obtener_atletas_pais(atletas: list, pais_interes: str) -> list:
"""
Función que genera una lista con la información de los atletas del país dado,
sin importar el año en que participaron los atletas.
Parámetros:
atletas: list de diccionarios con la información de cada atleta.
pais_in... | 4b03364a76af4e7818f977731b259fdfee6817ee | 18,098 |
def kl_div_mixture_app(m1, v1, m2, v2,
return_approximations=False,
return_upper_bound=False):
"""Approximate KL divergence between Gaussian and mixture of Gaussians
See Durrieu et al, 2012: "Lower and upper bounds for approximation of the
Kullback-Leibler dive... | e90fbf8596a06513d68c1eca17a35857d75eea70 | 18,099 |
def wilson_primality_test(n: int) -> bool:
"""
https://en.wikipedia.org/wiki/Wilson%27s_theorem
>>> assert all(wilson_primality_test(i) for i in [2, 3, 5, 7, 11])
>>> assert not all(wilson_primality_test(i) for i in [4, 6, 8, 9, 10])
"""
return ((factorial_lru(n - 1) + 1) % n) == 0 | 809415a5bd5a4ee4c19cc41a4616e91e17574a09 | 18,100 |
def project_from_id(request):
"""
Given a request returns a project instance or throws
APIUnauthorized.
"""
try:
pm = ProjectMember.objects.get(
user=request.user,
project=request.GET['project_id'],
)
except ProjectMember.DoesNotExist:
raise APIUna... | d23daddfacf736b835bdd10594d99dd4d4e5a0fe | 18,101 |
def make_beampipe_from_end(pipe_aperture, pipe_length, loc=(0, 0, 0), rotation_angles=(0, 0, 0)):
"""Takes an aperture and creates a pipe.
The centre of the face of aperture1 will be at loc and rotations will happen
about that point.
Assumes the aperture is initially centred on (0,0,0)
Args:
... | a3b85995165ac2b11d9d6d0014b68356996e97b9 | 18,103 |
import urllib
def encode_string(value):
"""Replace and encode all special characters in the passed string.
Single quotation marks need to be doubled. Therefore, if the string contains a single
quotation mark, it is going to be replaced by a pair of such quotation marks.
"""
value = value.replace(... | a6e30e834eb9b4d1d5882b7b24eec0da28ed5f4c | 18,104 |
async def make_json_photo():
"""Photo from web camera in base64.
"""
img, _ = get_png_photo()
if img:
result = {"image": png_img_to_base64(img)}
else:
result = {"error": "Camera not available"}
return result | d498d8d47a995125f0480c069b1459156875f2b7 | 18,105 |
from typing import Any
from typing import Union
from typing import List
from typing import Dict
from typing import Type
def Option(
default: Any = MISSING,
*,
name: str = MISSING,
description: str = MISSING,
required: bool = MISSING,
choices: Union[List[Union[str, int, float]], Dict[str, Union... | a344edbcdbc4211adebd072f0daaf20a6abc657e | 18,107 |
def inverse(f, a, b, num_iters=64):
"""
For a function f that is monotonically increasing on the interval (a, b),
returns the function f^{-1}
"""
if a >= b:
raise ValueError(f"Invalid interval ({a}, {b})")
def g(y):
if y > f(b) or y < f(a):
raise ValueError(f"Invalid... | 5d0b3c990d20d486f70bff2a5569920134d71ea1 | 18,108 |
def gmof(x, sigma):
"""
Geman-McClure error function
"""
x_squared = x ** 2
sigma_squared = sigma ** 2
return (sigma_squared * x_squared) / (sigma_squared + x_squared) | 63448c03e826874df1c6c10f053e1b1e917b6a98 | 18,109 |
import tqdm
def download_data(vars):
"""
function to download data from the ACS website
:param:
geo_level (geoLevel object): which geophical granularity to obtain for the data
vars (string): a file name that holds 3-tuples of the variables,
(in the format returned by censusdat... | a333eb2565736a6509cc3760de35fae8bc020c5e | 18,110 |
def oddify(n):
"""Ensure number is odd by incrementing if even
"""
return n if n % 2 else n + 1 | dee98063cb904cf462792d15129bd90a4b50bd28 | 18,111 |
from typing import List
import re
def method_matching(pattern: str) -> List[str]:
"""Find all methods matching the given regular expression."""
_assert_loaded()
regex = re.compile(pattern)
return sorted(filter(lambda name: re.search(regex, name), __index.keys())) | b4a4b1effcd2359e88022b28254ed247724df184 | 18,112 |
def update_binwise_positions(cnarr, segments=None, variants=None):
"""Convert start/end positions from genomic to bin-wise coordinates.
Instead of chromosomal basepairs, the positions indicate enumerated bins.
Revise the start and end values for all GenomicArray instances at once,
where the `cnarr` bi... | f42780517cde35d2297620dcaf046ea0a111a7b9 | 18,113 |
async def respond_wrong_author(
ctx: InteractionContext, author_must_be: Member | SnakeBotUser, hidden: bool = True
) -> bool:
"""Respond to the given context"""
if not ctx.responded:
await ctx.send(
ephemeral=hidden,
embeds=embed_message(
"Error",
... | a39e3672dd639e0183beb30c6ebfec324dfc96de | 18,114 |
def ParseFloatingIPTable(output):
"""Returns a list of dicts with floating IPs."""
keys = ('id', 'ip', 'instance_id', 'fixed_ip', 'pool',)
floating_ip_list = ParseNovaTable(output, FIVE_COLUMNS_PATTERN, keys)
for floating_ip in floating_ip_list:
if floating_ip['instance_id'] == '-':
floating_ip['insta... | 691d9c0525cee5f4b6b9c56c4e21728c24e46f48 | 18,115 |
def test_logging_to_progress_bar_with_reserved_key(tmpdir):
""" Test that logging a metric with a reserved name to the progress bar raises a warning. """
class TestModel(BoringModel):
def training_step(self, *args, **kwargs):
output = super().training_step(*args, **kwargs)
self.... | 827719942bed424def0753af9c4b6757b5f6cdf0 | 18,117 |
def cdf_inverse(m, alpha, capacity, f, subint):
"""
This function computes the inverse value of a specific probability for
a given distribution.
Args:
m (mesh): The initial mesh.
alpha (float): The probability for which the inverse value is computed.
capacity (float): The capaci... | cb0609a1f5049a910aaec63b9d6ed311a1fdc263 | 18,118 |
def concatenation(clean_list):
"""
Concatenation example.
Takes the processed list for your emails and concatenates any elements that are currently separate that you may
wish to have as one element, such as dates.
E.g. ['19', 'Feb', '2018'] becomes ['19 Feb 2018]
Works best if the lists are simi... | 59b727f21e663f2836f6fe939f4979e9f7484f62 | 18,119 |
def add_pattern_bd(x, distance=2, pixel_value=1):
"""
Augments a matrix by setting a checkboard-like pattern of values some `distance` away from the bottom-right
edge to 1. Works for single images or a batch of images.
:param x: N X W X H matrix or W X H matrix. will apply to last 2
:type x: `np.nda... | 1f545a472d6d25f23922c133fb0ef0d11307cca1 | 18,120 |
def tokenize(string):
"""
Scans the entire message to find all Content-Types and boundaries.
"""
tokens = deque()
for m in _RE_TOKENIZER.finditer(string):
if m.group(_CTYPE):
name, token = parsing.parse_header(m.group(_CTYPE))
elif m.group(_BOUNDARY):
token = ... | 0121f9242a5af4611edc2fd28b8af65c5b09078d | 18,122 |
def query(obj,desc=None):
"""create a response to 'describe' cmd from k8s pod desc and optional custom properties desc """
# this is a simplified version compared to what the k8s servo has (single container only); if we change it to multiple containers, they will be the app's components (here the app is a singl... | bce425c503c3c779c6f397020061ccee3150b562 | 18,123 |
def binary_cross_entropy(preds, targets, name=None):
"""Computes binary cross entropy given `preds`.
For brevity, let `x = `, `z = targets`. The logistic loss is
loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i]))
Args:
preds: A `Tensor` of type `float32` or `float64`.
... | f16441fe921b550986604c2c7513d9737fc230b3 | 18,124 |
def weld_standard_deviation(array, weld_type):
"""Returns the *sample* standard deviation of the array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
... | 763b96ef9efa36f7911e50b313bbc29489a5d5bd | 18,126 |
def dev_to_abs_pos(dev_pos):
"""
When device position is 30000000, absolute position from home is 25mm
factor = 30000000/25
"""
global CONVFACTOR
abs_pos = dev_pos*(1/CONVFACTOR)
return abs_pos | 74800f07cdb92b7fdf2ec84dfc606195fceef86b | 18,127 |
import torch
def model_predict(model, test_loader, device):
"""
Predict data in dataloader using model
"""
# Set model to eval mode
model.eval()
# Predict without computing gradients
with torch.no_grad():
y_preds = []
y_true = []
for inputs, labels in test_loader:
... | 0b43a28046c1de85711f7db1b3e64dfd95f11905 | 18,128 |
def calc_precision_recall(frame_results):
"""Calculates precision and recall from the set of frames by summing the true positives,
false positives, and false negatives for each frame.
Args:
frame_results (dict): dictionary formatted like:
{
'frame1': {'true_pos': int, '... | 7389050a73a1e368222941090991883f6c6a89b7 | 18,129 |
def euler_to_quat(e, order='zyx'):
"""
Converts from an euler representation to a quaternion representation
:param e: euler tensor
:param order: order of euler rotations
:return: quaternion tensor
"""
axis = {
'x': np.asarray([1, 0, 0], dtype=np.float32),
'y': np.asarray([0, ... | ff5a848433d3cb9b878222b21fc79f06e42ea03f | 18,131 |
def setnumber(update,context):
"""
Bot '/setnumber' command: starter of the conversation to set the emergency number
"""
update.message.reply_text('Please insert the number of a person you trust. It can be your life saver!')
return EMERGENCY | 5faa4d9a9719d0b1f113f5912de728d24aee2814 | 18,132 |
def mean_ale(covmats, tol=10e-7, maxiter=50, sample_weight=None):
"""Return the mean covariance matrix according using the AJD-based
log-Euclidean Mean (ALE). See [1].
:param covmats: Covariance matrices set, (n_trials, n_channels, n_channels)
:param tol: the tolerance to stop the gradient descent
... | 0df7add370bda62e596abead471f3d393691f62c | 18,133 |
def get_affiliate_code_from_qstring(request):
"""
Gets the affiliate code from the querystring if one exists
Args:
request (django.http.request.HttpRequest): A request
Returns:
Optional[str]: The affiliate code (or None)
"""
if request.method != "GET":
return None
a... | 173b8f7ed3d202e0427d45609fcb8e9332cde15b | 18,134 |
def get_gifti_labels(gifti):
"""Returns labels from gifti object (*.label.gii)
Args:
gifti (gifti image):
Nibabel Gifti image
Returns:
labels (list):
labels from gifti object
"""
# labels = img.labeltable.get_labels_as_dict().values()
label_dict = gifti... | 3a4915ed50132a022e29cfed4e90905d05209484 | 18,135 |
def get_temporal_info(data):
"""Generates the temporal information related
power consumption
:param data: a list of temporal information
:type data: list(DatetimeIndex)
:return: Temporal contextual information of the energy data
:rtype: np.array
"""
out_info =[]
for d in ... | 308640fec7545409bfad0ec55cd1cc8c941434d2 | 18,136 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.