content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rollback_event(db):
"""
Test fixture that uses a ``MagicMock`` as an event listener for database session rollbacks.
Useful for counting rollback events using ``rollback_event.call_count``.
"""
counter = mock.MagicMock()
sa.event.listen(db.session, "after_rollback", counter)
return count... | 852f74e7dbf126dee73545cf7196efe21b1a1a7b | 62,136 |
def adler32(space, string, start=rminiz_oxide.ADLER32_DEFAULT_START):
"""
adler32(string[, start]) -- Compute an Adler-32 checksum of string.
An optional starting value can be specified. The returned checksum is
an integer.
"""
ustart = r_uint(start)
checksum = rminiz_oxide.adler32(string,... | 5840ba5dd6c39b6a973e1c8d5e02831f462d9dce | 62,137 |
from openpype.lib import get_workfile_template_key
import io
def compute_session_changes(
session, task=None, asset=None, app=None, template_key=None
):
"""Compute the changes for a Session object on asset, task or app switch
This does *NOT* update the Session object, but returns the changes
required... | 34f6a812a9c3f745dadf7697bac5c2c6d26ce215 | 62,138 |
import json
def execute_statement(connect_info: Client, statement: str) -> JsonDict:
"""Calls the execute statement endpoint of df-df_connect.
Args:
statement: the SQL statement to be executed
connect_info: A Client object for establishing session and loading jdbc parameters
Returns:
... | aaa916c53666c1f18231e29fa55a174658b37366 | 62,141 |
def pytest_exception_interact(node, call, report):
"""
Set a different exit code on uncaught exceptions.
"""
global unhandled_exit
exctype, value, traceback = call.excinfo._excinfo
if exctype == AssertionError:
return report
unhandled_exit = node.config.getoption('--unhandled-exc-ex... | 0206a848c9324fe40fe1875e18a28f1b0e8f9def | 62,142 |
def relabel(image):
"""Given a labeled image, relabel each of the objects consecutively
image - a labeled 2-d integer array
returns - (labeled image, object count)
"""
#
# Build a label table that converts an old label # into
# labels using the new numbering scheme
#
unique_lab... | 5944b1b5da71ac7169c40c80ffe615cc821a1f02 | 62,143 |
def parseContent(content):
"""解析上报的设备信息,返回 kv 数据对"""
data={}
# print 'Content:',content
cap = '[VERSION]'
if content.find(cap) == 0:
ver = content.split(cap)[-1]
data['ver'] = ver
cap = 'IMEI:'
if content.find(cap) == 0:
items = map(lambda _:_.strip(),content.split(... | 44cd0c1099809682d07ad1eda2d3d77f27bf7f9e | 62,144 |
def get_counter(data, base):
"""
See setCounters() / getCounters() methods in IJ source, ij/gui/PointRoi.java.
"""
b0 = data[base]
b1 = data[base + 1]
b2 = data[base + 2]
b3 = data[base + 3]
counter = b3
position = (b1 << 8) + b2
return counter, position | fa960648edce84a465be3b588b265e14d817067d | 62,145 |
import httpx
import typing
def endorsement_response(
request: httpx.Request,
asset_type_id: str,
asset_id: str,
hashed_claim: str,
endorser_id: str,
request_id: str,
node_id: str,
) -> typing.Dict[str, typing.Union[str, typing.List[str]]]:
"""Simualate response for creating an entity."... | 399d49cf01811364612cebdba7e5deeef9ba7c58 | 62,146 |
def he_normal(weight_shape):
"""
Initialize network weights `W` using the He normal initialization strategy.
Notes
-----
The He normal initialization strategy initializes the weights in `W` using
draws from TruncatedNormal(0, b) where the variance `b` is
.. math::
b = \\frac{2}{\\... | 43938f26112ec5e74b2a46d9eb08167cfd9a7b52 | 62,147 |
def update_get_space_ids(ems_rooms):
"""
Get R25 space_ids for EMS Rooms.
:param ems_rooms: A collection of ems_client.models.Room
:return: A dictionary of Room.id: space_id
"""
space_ids = {}
for room in ems_rooms:
if room.active and room.external_reference is not None:
... | f2a88e4ca93ef3a5076c56b3b008df4dff72acaf | 62,148 |
def match_identifier_in_cache(identifier, db_instance):
"""Return list of matches for the given identifier in the file database.
Args:
identifier: identifier to use as a reference if the corresponding data is already cached
db_instance: Connected Database file with `DBConnect()`.
Returns:
... | 8bde79befd613fc4719536baa28294f79aa43f8e | 62,149 |
from typing import Optional
from typing import Dict
from typing import Union
from typing import Any
def apply(df: pd.DataFrame, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> Dict[str, Any]:
"""
Discovers a footprint object from a dataframe
(the footprints of the dataframe are returned... | 6f0fbf7b72d08dbc0f0f6bb44ee6f61d586112af | 62,151 |
def psy_const_of_psychrometer(psychrometer, atmos_pres):
"""
Calculate the psychrometric constant for different types of
psychrometer at a given atmospheric pressure.
Based on FAO equation 16 in Allen et al (1998).
:param psychrometer: Integer between 1 and 3 which denotes type of
psychromet... | e19e8c6d675d8a743a2be0444a90497a99150019 | 62,152 |
def create_four_axes_figure(figsize=(10,8)):
"""生成一个含有4个坐标轴的figure,并返回坐标轴列表
:param figsize: (宽, 高)
:return: (ax1, ax2, ax3, ax4)
"""
rect1 = [0.05, 0.50, 0.9, 0.45]
rect2 = [0.05, 0.35, 0.9, 0.15]
rect3 = [0.05, 0.20, 0.9, 0.15]
rect4 = [0.05, 0.05, 0.9, 0.15]
fg=figure(f... | 4aad07347f84d879c470bbbba70659b606dbc356 | 62,153 |
def test_declarative_forms():
# language=rst
"""
Declarative forms
-----------------
You can create forms declaratively, similar to Django forms. There are some important differences between iommi forms and Django forms in this mode, maybe the most important being that in iommi you can pass a calla... | ec2fbc5d13f53dd6508ca05641f83b5e9ae88a49 | 62,155 |
import glob
def read_corpus():
"""
读原始数据
"""
src = []
tgt = []
data_path = glob.glob("./corpus/文言文翻译/*")
for p in data_path:
dir = p.split("/")[:-1]
dir = "/".join(dir)
# print(dir)
name = p.split("/")[-1]
if "翻译" in name:
# 找到了一个翻译文件
... | cc225268c90be6fbfca59f36b81d2520a65c6f95 | 62,156 |
def gen_sym_axial_vector(sym_ops, x, y, z):
"""
Transform axial vector by symmetry operations
Usage:
uvw = gen_symcen_pos(sym_ops,cen_ops,x,y,z)
sym_ops = [n*'x,y,z'] array of string symmetry operations
cen_ops = [m*'x,y,z'] array of string centring operations
x,y,z = fractional coo... | 1c20a97662030646318a3d828a8372becc4b1e5a | 62,158 |
def ipr_record():
"""
ipr template.
"""
record_dtype = np.dtype([('target_record_class', np.ubyte),
('target_instrument_group', np.ubyte),
('target_record_subclass', np.ubyte),
('target_record_offset', np.uint32)])
... | c39449e36bef0a7fc7da493433ea5a4d32be43c1 | 62,159 |
def classify(df, model_dir, num_of_processes):
""" Makes prediction
Args:
df (pandas.DataFrame)
model_dir (str): path to dir where models are locaded
num_of_processes (int): the number of processes
Returns:
df (pandas.DataFrame) : with prediction
"""
df = calculate_pr... | 002a2bfafdf655bab21c03ceecdd440729f77a3b | 62,160 |
def stitch(input_directory, input_filename, output_directory, imagej_instance):
"""
Use the BigStitcher plugin to stitch together the series at input_filepath.
See Fuse.ijm for the ImageJ macro code.
Args:
input_directory (Union[str, pathlib.Path]):
Directory in which input microscopy fi... | 5e6e1775d65af8dd295bd59ceda4da7dc0556126 | 62,161 |
def _get_mounts():
"""
List mounted filesystems.
"""
mounts = {}
with salt.utils.files.fopen("/proc/mounts") as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split(
" "
)
... | 8a62536ae58c56ab106cecf5b36707594605d024 | 62,162 |
def get_role_class(expected_rolename):
"""
<Purpose>
Return the role class corresponding to
'expected_rolename'. The role name returned
by expected_meta_rolename() should be the name
passed as an argument to this function. If
'expected_rolename' is 'Root', the class
RootFile is returned.
... | 3ea6947af974c8dce56c18178d5ff76b35b6de04 | 62,163 |
def sub64(a,b):
"""Return a 64-bit integer difference of `a` and `b`."""
return(np.subtract(a, b, dtype=np.uint64)) | 1aad62ee3710faee68fdbd4444c7577be30cf0df | 62,164 |
def get_basename(basename, out_log):
""" Checks if provided basename value is correct """
bsn = str(basename)
if basename == '':
fu.log('No basename provided, default value %s assigned' % get_default_value('basename'), out_log)
bsn = get_default_value('basename')
return bsn | c2a2635f792895294fb17d8197658aa3754d8c98 | 62,165 |
def M(*args, **kwargs) -> dict:
"""Join objects to dict"""
result = {}
for arg in args:
if isinstance(arg, dict):
result.update(arg)
if hasattr(arg, "__dict__"):
result.update(dict(arg))
return result | kwargs | 87cd7bfecc746f70e56b39239d66a63a93fe9a1c | 62,166 |
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Set up the Unifi Protect components."""
return True | ecea5b98f7c3d464454f42cccaad7400a4bced36 | 62,167 |
import math
def fd_jenkinson(in_file, rmax=80., out_file=None):
"""
Compute the :abbr:`FD (framewise displacement)` [Jenkinson2002]_
on a 4D dataset, after ``3dvolreg`` has been executed
(generally a file named ``*.affmat12.1D``).
:param str in_file: path to epi file
:param float rmax: the de... | f45a39c9549a30769cd37d823824a12951a928df | 62,169 |
def cymdtoymd(str):
"""cymdtoymd(str) -> string
Convert a legal CCSDS time string with the date expressed as a month and day
to a simple time string with the date expressed as a month and day."""
try:
(year, mon, day, hour, min, sec) = cymdtoaymd(str)
ymd = aymdtoymd(year, mon, day, hour, min, sec)
exce... | 2443beb1f7b25b406c5fc29a7f93aced6079b52a | 62,170 |
from typing import Any
def _substitute_none_val(data: Any):
"""Trakt represents null-value as {}. Change it to None."""
if data == {}:
return None
if isinstance(data, list):
data = [_substitute_none_val(v) for v in data]
if isinstance(data, dict):
data = {k: _substitute_none_v... | 3995f49272117fce66afbf1087e8e4a2240b2392 | 62,171 |
from typing import Union
from re import T
from typing import List
def ensure_list(value: Union[T, List[T], None]) -> List[T]:
"""Wrap value in list if it is not one."""
if value is None:
return []
return value if isinstance(value, list) else [value] | a083b131412737043a03c528042e5746d50e1a00 | 62,172 |
def tofov(i, shape=None, var_params=None):
"""Check whether i is tensor or initialization function or tf.Variable; return tf.Variable;
Parameters
-------
i : tensor or function or tf.Variable
Tensor or function to initialize tensor
shape : list or tuple or None
Shape of tensor t... | 404346f85f338a40a34e920208ec2428de7dacca | 62,173 |
import torch
def decomposed_kl(z, mu, logvar):
"""Decompose KL term in VAE loss.
Decomposes the KL divergence loss term of the variational autoencoder into three terms:
1. index code mutual information
2. total correlation
3. dimension-wise KL
None of these terms can be computed exactly when... | a6bd216329a919b48c977c65f977f37c20d49318 | 62,174 |
def _preprocess_data(df, use_preprocessdata=False, save_path=None):
"""Preprocess task speccific pipeline.
Args:
df (DataFrame): target pandas DataFrame object.
use_preprocessdata (bool): Wheter or not to use local preprocess file loading
save_path (str): local preprocess file path
R... | bd6adb1e381e1bd10da83b2531148faa6ca9c6d2 | 62,175 |
def exemplar_selection(x, m):
"""
Parameters
----------
x: the features, n * dimension
m: the number of selected exemplars
Returns
----------
pos_s: the position of selected exemplars
"""
pos_s = []
comb = 0
mu = np.mean(x, axis=0, keepdims=F... | 30e36b9019e8bd29fbc7a936ea58d72026ae09bb | 62,176 |
def run_accuracy_check(nvars_list, problem_params, order_stencil):
"""
Routine to check the error of the Laplacian vs. its FD discretization
Args:
nvars_list: list of nvars to do the testing with
problem_params: dictionary containing the problem-dependent parameters
Returns:
a ... | 0b4183889ca945dee8171f317903798dc55eafdb | 62,177 |
def spof(img1, img2):
""" symmetric phase-only filter"""
F1 = np.fft.rfft2(img1, axes=(0,1))
F2 = np.fft.rfft2(img2, axes=(0,1))
R = F1*np.conj(F2)
R = R/(np.sqrt(np.abs(R))+1e-5)
r = np.fft.irfft2(R, axes=(0,1))
shift_r = np.fft.fftshift(r, axes=(0,1))
return shift_r | 96cdf91b7ff6a3b7974add3c49216a27aebd899b | 62,178 |
def get_neighbors(device, neigh_type='cdp'):
"""Gets neighbors from a device
Args:
device (Device): This is the device object of an NX-API enabled device
using the Device class within device.py
neigh_type (str): lldp or cdp
Returns:
list: ordered list of dicts (dict per... | 9bdf980a5510778134c317ec13becc39517b4bb7 | 62,179 |
def mean_image_subtraction(image, means=(_R_MEAN, _G_MEAN, _B_MEAN)):
"""Subtracts the given means from each image channel.
For example:
means = [123.68, 116.779, 103.939]
image = _mean_image_subtraction(image, means)
Note that the rank of `image` must be known.
Args:
image: a tensor of size [hei... | 56ad92792ff36a7ac5af266171933d2b440281a4 | 62,180 |
import tqdm
def mod(dividends, divisor):
""" return dividends (array) mod divisor (double)
"""
output = np.zeros(len(dividends))
for i in tqdm(range(len(dividends))):
output[i] = dividends[i]
done=False
while (not done):
if output[i] >= divisor:
o... | 832d913bbb25a9cb7170b26a4f0aaa3a6ab357ed | 62,182 |
import requests
from bs4 import BeautifulSoup
def get_department_names():
"""Gets a list of unibo's departments parsing a webpage"""
dep_resp = requests.get(constant.DEPURL)
dep_soup = BeautifulSoup(dep_resp.content, from_encoding=get_encoding(dep_resp), features="html5lib")
depts = dep_soup.find("div... | 3105a8ce94832b26e121f2b910fd2142214bb7e6 | 62,183 |
def ScanAllTorsionsInMol(Mol, TorsionsMolInfo, MolNum = None):
"""Peform scans on all torsions in a molecule."""
if TorsionsMolInfo["NumOfMatches"] == 0:
return Mol, True
Mol = AddHydrogens(Mol)
MolName = RDKitUtil.GetMolName(Mol, MolNum)
FirstTorsionMode = OptionsInfo["FirstTors... | 35ef56af5448f9fd2be1e0d11b9ab16b1c285c21 | 62,185 |
def calcSimilarity(s1List, s2List, tiles, treshold):
"""Calculates Similarity and returns list [similarity:float, suspectedPlagiarism:bool]"""
#compute similarity
similarity = sim(s1List, s2List, tiles)
#check if it is suspected plagiarism
suspPlag = similarity >= treshold
return [similarity, ... | e523639685dcd37614b9740169497cb67b1109b6 | 62,186 |
def rivers_with_station(stations):
"""For a list of MonitoringStation objects, return a set of rivers which have a monitoring station"""
rivers = []
for station in stations:
rivers.append(station.river)
return set(rivers) | a9af1a64acf0b5dbc89cecad83c3f654e77e74a8 | 62,187 |
def calculate_tax(income):
"""Implement the code required to make this function work.
Write a function `calculate_tax` that receives a number (`income`) and
calculates how much of Federal taxes is due,
according to the following table:
| Income | Tax Percentage |
| ------------- | ----------... | fce9ad9ac9d88b1821a1772b6cc5bb9259ba7ae5 | 62,188 |
def Asin(x, target=utils.CCE):
"""
Computes the trignometric inverse sine of `x` element-wise.
asin(x) = | arcsin(sqrt(1-x^2)) - HALF_PI, x belongs to [-1, -sqrt(2)/2)
| the 15th order taylor expansion, x belongs to [-sqrt(2)/2, sqrt(2)/2)
| HALF_PI - arcsin(sqrt(1-x^2)), x belo... | 923573eb9c83101516a3007b7c7c6446c2582304 | 62,189 |
import click
def afterhours(args=None):
"""Console script for podcasts."""
click.echo("Replace this message by putting your code into "
"podcasts.cli.main")
return recommendations(url="http://feeds.harvardbusiness.org/harvardbusiness/after-hours") | cce35cfcd7824358f54894729df1647d5d55dde6 | 62,190 |
import sqlite3
from typing import Dict
def get_cid2nid(db: sqlite3.Connection) -> Dict[int, int]:
"""Mapping card ID to note ID.
Args:
db: Database (:class:`sqlite3.Connection`)
Returns:
Dictionary
"""
cards = get_table(db, "cards")
_cid2nid = dict(zip(cards["id"], cards["ni... | 27252043a59a0e640c8ab247f805e7c04627ebbd | 62,191 |
import collections
import gzip
from pathlib import Path
def validate_fastq(fq, fq2=None):
"""Validate FASTQ files."""
input_fastq = fq
if fq2:
input_fastq = fq + fq2
# Reduce the probability of uploading the FASTQ files with the same
# content multiple times (as multiple lanes or mates)... | e17161d9f0ab36cc80ba6066b48ff3272deeeb0a | 62,192 |
import numpy
def mult_rasters_op(array_a, array_b, nodata_a, nodata_b, target_nodata):
"""Mult a*b and account for nodata."""
result = numpy.empty(array_a.shape)
result[:] = target_nodata
valid_mask = (
~numpy.isclose(array_a, nodata_a) & ~numpy.isclose(array_b, nodata_b))
result[valid_mas... | e354c057214a419142071c1f66b750ad900935fa | 62,193 |
import collections
def frequency(input_list):
"""
Finds the occurances of elements in a list.
Works with numbers not consisting of numbers as well.
:param input_list: list or tuple
>>> frequency([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
Counter({4: 4, 3: 3, 2: 2, 1: 1})
"""
return collections.... | 417dcd493da11f72609e4c4aa3c4edfb35e921aa | 62,194 |
def get_linked_domains(domain, include_deleted=False):
"""
:param domain:
:return: List of ``DomainLink`` objects for each domain linked to this one.
"""
manager = DomainLink.all_objects if include_deleted else DomainLink.objects
return list(manager.filter(master_domain=domain).all()) | 42b2ab4ffce3e73473e74f29e91dcb43c16895db | 62,195 |
def to_normal_strokes(big_stroke):
"""Convert from stroke-5 format (from sketch-rnn paper) back to stroke-3."""
l = 0
for i in range(len(big_stroke)):
if big_stroke[i, 4] > 0:
l = i
break
if l == 0:
l = len(big_stroke)-1
result = np.zeros((l+1, 3))
result[:, 0:2] = big_stroke[0:l+1, 0:2]... | dfb15825d24d76f6a1a784eaabe9543da7dcefa8 | 62,196 |
def deposit(owner_id, amount, reference=None):
"""Deposit given amount into the wallet."""
assert amount.amount > 0, "The amount must be positive."
wallet_obj = get_wallet(owner_id, amount.currency)
qs = models.Wallet.objects.get(id=wallet_obj.id).transactions
trx_obj = qs.create(amount=amount, ref... | cdbb7fdebc2d695a1000344e7a814d3379f045c8 | 62,197 |
def array_to_dict(result_array, regions):
"""Convert an array with regions to dict
with region as key
Arguments
---------
result_array : array
Results in region_array
regions : list
List with all regions (order is the same)
Returns
--------
result_dict : dict
... | 263e69179983eec525bba9f79f1ed02539e1d647 | 62,198 |
def setup():
"""Raspberry Pi GPIO setup."""
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
power_button = 3
if data['args']['gpio-mode'] == 'BOARD':
GPIO.setmode(GPIO.BOARD)
power_button = 5
GPIO.setup(power_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
for pin in gpio_setup:
... | ab312721721e7168692cddc61dca8477cdd4a89c | 62,199 |
def api_ping():
"""
api ping
"""
return jsonify({"message": "pong"}) | 49478b5375b1adabdad0485bed2c5970949e3732 | 62,200 |
from typing import Callable
from typing import Hashable
from typing import Any
def max_by(d: D, *, keyfunc: Callable[..., Hashable], **kwds: Any) -> NumDict:
"""
Find maximum values in d grouped by keyfunc.
Maps each l in the range of keyfunc to the max of all d[k] such that
keyfunc(k) is equal ... | a225136da9d9b8d97bc16a234293675fbf3fc851 | 62,202 |
import socket
import time
def socket_backoff_connect(family, socktype, proto, addr, timeout, attempts):
"""connect will backoff if the response is not ready for a pseudo random number greater than zero and less than
51e-6, 153e-6, 358e-6, 768e-6, 1587e-6, 3225e-6, 6502e-6, 13056e-6, 26163e-6, 52377e-6
... | 0428072c50a6252bd2ecfe0c4097f84e3c7183ea | 62,203 |
def reverse(start, end):
"""
takes in 2 nodes a start and end
swaps all nodes
iterating over start to end
"""
# set a prev to the end
prev = end
# set a next_starting_node to the start.next
next_starting_node = start.next
# set a current_node
current_node = start.next
... | a68b32868a6b94bfc856624a2fbebb8d9c8d639a | 62,206 |
import sqlite3
import atexit
def init_background_tasks(app):
"""
不同 job 之间的间隔应大于 1 分钟, 否则会导致某些 job 不被执行.
job 的执行函数第一个参数为当前的 app
"""
with app.app_context():
c = get_db()
c.execute('BEGIN EXCLUSIVE')
mutex = c.execute("select * from misc where key = 'mutex'").fetchone()
... | 35d423c2c6e63ff4b0031e874cf69fdd1da4a873 | 62,207 |
def n_pixels(seeing_fwhm):
"""Calculate number of pixels in aperture extraction region.
Uses the SNR-maximizing extraction radius
(1.346 FWHM)--see LSST SNR doc eq. 19
seeing_fwhm: float
seeing in arcsec
"""
npix_extract = np.pi * (0.673 * seeing_fwhm / PIXEL_SCALE)**2.
... | 4544c7e70b12f6fa5e438532f093d706e4c7df90 | 62,209 |
def get_frequency_counts(classification):
"""
Get the raw and fractional class frequency counts for an `xarray.Dataset`.
Intended to be used with outputs from the `*_cluster_dataset()` functions.
Parameters
----------
classification: xarray.Dataset
An `xarray.Dataset` with a `classi... | 5c09d1af4cb9d22dcefaa299dadef775fe96af0e | 62,210 |
def embed_backward(dx, cache):
"""Inputs: dx (N,T,D), cache. Outputs: dW_embed (V,D).
Only need to compute dW_embed as output"""
inputs, W = cache
dW = np.zeros_like(W)
np.add.at(dW, inputs, dx)
return dW | 81510ce2cbe35a9e2fdf713e4c47d10a84986330 | 62,211 |
def generator_function(context: DurableOrchestrationContext):
"""Orchestrator function for testing retry'ing semantics
Parameters
----------
context: DurableOrchestrationContext
Durable orchestration context, exposes the Durable API
Returns
-------
List[str]:
Output of acti... | 42150e7949da9d78796b64ada29c5077b899f39d | 62,212 |
def add_traits(base, names, trait_type=None):
""" Add traits to a traited class.
All traits are set to Undefined by default
"""
if trait_type is None:
trait_type = traits.Any
undefined_traits = {}
for key in names:
base.add_trait(key, trait_type)
undefined_traits[key] = ... | 3b17b08b4b63595acb25104d0221555e8758bc75 | 62,214 |
def translate_blocks(blocks):
"""Translate code blocks into the machine code.
Args:
blocks (dict): dictionary of blocks indexed by offsets
Returns:
str: assembly code
"""
def fill_instruction(instruction, block):
template = TRANSLATION_TABLE[instruction["instruction"].name]... | e6293b394d191bba5e33f0ceb01011ae9dac1d19 | 62,217 |
def _get_vel_list():
"""Get the tuple from which a zombie's velosity will be determined
Example:
>>> Options.speed = 4
>>> Tile.length = 32
>>> _get_vel_list()
(2, 4, 2, 1)
>>> Options.speed = 9
>>> _get_vel_list()
(4, 8, 4, 2)
"""
base_speed = Options.speed / 4
ts = base... | c04e2d745580d219bdb5900c0bef017c624b6c45 | 62,218 |
def create_cifar10_data(gray):
"""加载cifar10数据集"""
cifar_path = "cifar10"
images, labels = load_CIFAR10(cifar_path)
# 转灰度
image_num = images.shape[0]
if gray == True:
images_gray = rgb2gray(images)
# numpy array使用连续内存块,所以应一开始就定义好大小,然后根据索引对其赋值
features = np.zeros((len(image... | 4c639bf24f0a6898dbf6b4cc411620a218207f1f | 62,220 |
import math
def get_circle_centre(points, radius):
"""returns the cg of a circle (and angle of sector) given two points and a radius"""
l = distance(points[0], points[1])
s = line_slope(points)
phi = math.pi - 2 * math.acos(l / (2 * radius))
midpoint = (0.5*(points[0][0]+points[1][0]), 0.5*(points... | f01c907cec2d3192400733e55dd72f3b02da8fb7 | 62,221 |
def get_bird_data():
"""
Fetches the full Oregon eBird dataset and filters data based on
relevant columns and months
Args: None
Returns:
bird1 (pd dataframe): Cleaned eBird data from repo
"""
print("Retrieving Bird Data...")
bird1 = pd.read_csv("phoenix/data/ebird_app_data.csv... | aed894d0b31c83d0d5bcc9166dde333e2d3b3f3c | 62,222 |
def string_from_uuid(uuid_obj):
"""Returns standard hexadecimal string for uuid; same as str(uuid_obj).
arguments:
uuid_obj (uuid.UUID object): the uuid which is required in hexadecimal string format
returns:
string (40 characters: 36 lowercase hexadecimals and 4 hyphens)
"""
return... | 903f3b257854900f2b534658dbfa4e504812c67b | 62,223 |
def psnr2d(img1, img2, max_val=None, name='psnr2d'):
"""Computes the peak signal-to-noise ratio (PSNR) between two 2D images.
This function operates on batches of multi-channel inputs and returns a PSNR
value for each image in the batch.
Arguments:
img1: A `Tensor`. First batch of images. Must have rank >... | 6677bc0d766cab0d75255d2fec06b6c46b8aae0a | 62,225 |
import typing
def get_row_history(row: 'md_table.Table') \
-> 'typing.Dict[md_column.Column, typing.Dict[str, typing.Any]]':
"""
Gets the history for the specified row.
This returns a dict, indexed by Column, with values being another dict with `old` and `new` keys
that represent the old and ... | 42fb6a5c76fc3936a6bc0a3d5b40b76057a24c22 | 62,226 |
def decoding(sprobs, samples, params, mask=None):
"""Generate decoded sequence from seqs"""
if mask is None:
mask = [1.] * len(sprobs)
flat_sprobs = []
for _sprobs, _m in zip(sprobs, mask):
if _m < 1.:
continue
for start_prob in _sprobs:
flat_sprobs.appe... | e660a85af689759daacb9b553751fe7eb168dda7 | 62,227 |
import unicodedata
def is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, fo... | 756e86b4a56a44409494c4f6cf81cb61f278d636 | 62,228 |
def _test_all():
"""Run lint and tests.
:return: exit code
"""
return _lint() + _test() | 2b82157b0de0ddc7ae471756879dceaf51b28055 | 62,229 |
def hassio_update(config, supervisor):
"""Create scheduler task for update of supervisor hassio."""
async def _hassio_update():
"""Check and run update of supervisor hassio."""
if config.last_hassio == supervisor.version:
return
_LOGGER.info("Found new HassIO version %s.", c... | 644c72423185e7a3f91dec49c92e02a0b06a9905 | 62,230 |
def strlist_vsort(alist):
"""Same as `strlist` except sorted according to version-representation"""
alist = strlist(alist)
alist = sorted(alist, key=lambda x: LooseVersion(x))
return alist | e7e14b0a7d157252c724fa09b26d71fb3eaf7aad | 62,231 |
from datetime import datetime
def sync_all_message():
"""
获取数据
"""
now = datetime.datetime.now()
now_height = datetime_to_height(now)
height = 31884
log = MigrateLog.objects(version="s1").first()
if log:
height = int(log.message_content.get("height") or height) - 1
# messag... | c923dd1ecb97e8153a3265e9dca7566f225d346e | 62,232 |
def data_context_notification_context_notif_subscriptionuuid_notification_channel_namevalue_name_get(uuid, value_name): # noqa: E501
"""data_context_notification_context_notif_subscriptionuuid_notification_channel_namevalue_name_get
returns tapi.common.NameAndValue # noqa: E501
:param uuid: Id of notif-s... | 6b3603f5c7ecff1b8bd857ffc73906f47fd1254c | 62,234 |
def calc_resp(password_hash, server_challenge):
"""calc_resp generates the LM response given a 16-byte password hash and the
challenge from the type-2 message.
@param password_hash
16-byte password hash
@param server_challenge
8-byte challenge from type-2 message
... | fc23b12a38bc6b216c3e60400bae2e6fb187a65f | 62,235 |
def get_dist_info(df, dists):
"""
:param df: any object having shape attribute (e.g. pandas Dataframe, numpy array).
:param dists: the output of from "scipy.spatial.distance.pdist" function.
:return: pandas Dataframe with ['pair','dist'] columns representing the row indices and distances between th... | 2b2bbb329852e6ce5aa34867ac9650a89db22b06 | 62,236 |
import logging
def run_inference_queue_kdd(N, T, num_segments, sim_opts_gen, log_q_high, log_q_low, num_procs=None):
"""Run inference for the given sim_opts_gen by sweeping over 'q' and
running the simulation for different seeds."""
if num_procs is None:
num_procs = mp.cpu_count() - 1
in_que... | a24fbdcf5ed853b054f0fc7a34e7aeb5638fd6e3 | 62,237 |
def ImageLoad_torch(data, ensemble_n, resize_layers, is_silent):
"""
input:
data -- np array (H, W, 3)
p -- rescale factor. e.g. p=0.4: (720, 1280) --> (288, 512)
"""
normalize = transforms.Normalize(mean = [0.485, 0.456, 0.406],
std = [0.229, 0.224, ... | c2eaaff658ab1775b3a4f2d64373e4f0e69e1400 | 62,238 |
def _select_action_policy(policy_seq, action_seq):
"""
:param policy_seq: policy for every [batch,tick,action]
:param action_seq: actions taken on every [batch,tick]
:return: returns policy for selected actions of shape [batch, tick]
"""
batch_i = np.arange(policy_seq.shape[0])[:, None]
time... | d20c90960071f27bffd13b369e71345c91e64b29 | 62,239 |
def create_setWeight(col: str, weight: str, lemex: str):
"""
:return str: format of 'setweight(col, weight, lemex)' \n
Check postgresql text search setweight function to see the syntax
"""
return """setweight(%s, '%s', '%s')""" % (col, weight, lemex) | 965b25a5ccb8f3c68ecc3742a512dd7c28dac0a4 | 62,240 |
import rasterio
def extractByMaskReturnList(flRasterName, gdMask):
"""
Takes a Raster Image and a Geopandas dataframe and returns
[outImage,outMeta,outTransform]
"""
with rasterio.open(flRasterName) as src:
outImage, outTransform = rasterio.mask.mask(
src, gdMask.geometry, cro... | 4bc89eb3a4be1297ce0b3b383fea5ccba2f7900c | 62,241 |
def create_transforms(input_config):
"""Create transforms from configuration
Parameters
----------
input_config : dict
Dictionary containing the configuration options for input pre-processing.
Returns
-------
train_transforms : list
List of transforms to be applied to the i... | 42fe6268c1834d0453e0707f8c564635612a1f82 | 62,242 |
def lgamma(expr):
"""
---------------------------------------------------------------------------
Natural Logarithm of the expression Gamma.
Parameters
----------
expr: object
Expression.
Returns
-------
str_sql
SQL expression.
"""
expr = format_magic(expr)
return str_sql("LN(({} - 1)!)".forma... | ffcaf35e1f08bc8e618ac93ad52d913b2b9356e2 | 62,244 |
def share_snapshot_instance_create(context, snapshot_id, values):
"""Create a share snapshot instance for an existing snapshot."""
return IMPL.share_snapshot_instance_create(
context, snapshot_id, values) | 702bfacc37d2c0a74a19c49f49b07829801df316 | 62,245 |
def reduce_precision_tf(x, npp):
"""
Reduce the precision of image, the tensorflow version.
"""
npp_int = npp - 1
x_int = tf.rint(tf.multiply(x, npp_int))
x_float = tf.div(x_int, npp_int)
return x_float | 5e43afb35ad9bdf93f2951e62b16df39294b8309 | 62,246 |
def compute_cell_size(npz_file, method='median', by_image=True):
"""Computes the typical cell size from a stack of labeled data
Args:
npz_file: Paired X and y data
method: one of (mean, median) used to compute the cell size
by_image: if true, cell size is reported for each image in npz_... | 6124ff2fabb8bed7d3a840da5cc5eb4826e966e1 | 62,247 |
from scipy.ndimage.morphology import binary_dilation
def overlay_davis(image,mask,colors=[255,0,0],cscale=2,alpha=0.4):
""" Overlay segmentation on top of RGB image. from davis official"""
# import skimage
colors = np.reshape(colors, (-1, 3))
colors = np.atleast_2d(colors) * cscale
im_overlay = ... | c7c94e61597b4d150f0a7997442ba62542912e5a | 62,248 |
def calc_delta(Y, Ygrid, X, m, fy=None, xr=None):
"""Plischke et al. (2013) delta index estimator (eqn 26) for d_hat."""
N = len(Y)
if fy is None:
fy = gaussian_kde(Y, bw_method="silverman")(Ygrid)
if xr is None:
xr = rankdata(X, method="ordinal")
abs_fy = np.abs(fy)
d_hat = 0
... | 94d0c26d853ae0c3172f99521feceec118c01f12 | 62,249 |
def create_model(vocab_size, embedding_dim=50):
"""Create a model.
Args:
vocab_size(int): vocabulary size.
embedding_dim(int): embedding dimension.
Returns:
model: model object.
"""
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim,... | cabccf77c59aebc0727230bda33afc6831bb2b4b | 62,250 |
from tensorflow_addons.layers import StochasticDepth
def replace_add_with_stochastic_depth(model, survivals=(1, 0.8)):
"""
- [Deep Networks with Stochastic Depth](https://arxiv.org/pdf/1603.09382.pdf)
- [tfa.layers.StochasticDepth](https://www.tensorflow.org/addons/api_docs/python/tfa/layers/StochasticDep... | 0dff0124c1d8ff336dbaee57bef59aa89e36cb89 | 62,251 |
from pathlib import Path
from typing import Tuple
from typing import Dict
import json
def parse_fsh_generated(path: Path) -> Tuple[Dict, Dict, Dict, Dict, Dict, Dict]:
"""
Parse json files generated from FSH through SUSHI.
Goal: Extract structure definitions, instances, value set and dependencies from ge... | 76d280dd82a748ff9749b689a6e1b41023a04f5f | 62,252 |
def get_event_bpt_hea(*args):
"""
get_event_bpt_hea(ev) -> ea_t
"""
return _ida_idd.get_event_bpt_hea(*args) | 366713a10d6c12cab153b8fdbb8a86ed60d64250 | 62,253 |
import torch
def quat_from_xyz(xyz):
"""
Construct 3D rotation from the imaginary component
"""
w = (1.0 - xyz.norm()).unsqueeze(-1)
assert bool((w >= 0).all()), "xyz has its norm greater than 1"
return torch.cat([xyz, w], dim=-1) | df62a104cb2a983095576cc71241869d94c0efd9 | 62,254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.