content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
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],
[3.14, 3.93],
[4.71... | 5,317,800 |
def _calculate_Neff(infile, outfile, cutoff):
"""Parsing arguments for processing.
"""
msa = parse_msa_file(infile)
hdm = hamming_distance_matrix(msa)
clu = cluster_sequences(hdm, cutoff)
Neff = effective_family_size(clu, msa.shape[1])
click.echo('Effective family size at %s%% identity: %.3f... | 5,317,801 |
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 app... | 5,317,802 |
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] | 5,317,803 |
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:/tmp/t.c'
cobj = crypto.cbase64(obj... | 5,317,804 |
def change_suffix(fname: str, new_suffix: str, old_suffix: Optional[str] = None) -> str:
"""Change suffix of filename.
Changes suffix of a filename. If no old suffix is provided, the part that is replaced is guessed.
Args:
fname: Filename to process.
new_suffix: Replace old suffix with thi... | 5,317,805 |
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 ... | 5,317,806 |
def new_markers():
"""
Read name of packages from scripts arguments and create set of them.
"""
new_markers = set()
for x in sys.argv[1:]:
if check_package(x):
new_markers.add(x)
else:
error(f"ERROR: Package {x} not installed in system. Can't mark it.")
re... | 5,317,807 |
def concat(nidm_file_list, out_file):
"""
This function will concatenate NIDM files. Warning, no merging will be done so you may end up with
multiple prov:agents with the same subject id if you're concatenating NIDM files from multiple vists of the
same study. If you want to merge NIDM files on subjec... | 5,317,808 |
def dumpRoot(root):
"""
:param root:
"""
for dir0, dirs, ff in os.walk(root):
for fname in ff:
if fname[-4:] == ".toc":
pp(fname, 0)
fname = dir0 + "\\" + fname
dump(fname, targetDirectory) | 5,317,809 |
def test_stage_upstream_params(mock_ssh, mock_upload):
"""
Test the correct arguments make it to the upload method.
"""
jobs = {
"jobone": {
"destdir": "/path/to/jobone12484",
"resource": "test-machine",
"localworkdir": "/path/to/local/dir"
}
... | 5,317,810 |
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... | 5,317,811 |
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 SYSTEM SET {key}... | 5,317,812 |
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... | 5,317,813 |
def create():
"""
does setup of Tellor contract on Alogrand
solidity equivalent: constructor()
args:
0) governance address
1) query id
2) query data
"""
return Seq(
[
App.globalPut(tipper, Txn.sender()),
# TODO assert application args length is corre... | 5,317,814 |
async def test_setup_discovery(hass, device, main_zone):
"""Test set up integration via discovery."""
discovery_info = {
"name": "Yamaha Receiver",
"model_name": "Yamaha",
"control_url": "http://receiver",
"description_url": "http://receiver/description",
}
await async_lo... | 5,317,815 |
def task(args):
"""Find the adequate limits for a task."""
solutionList = args.path[:]
if args.usecorrect or len(args.path) == 0:
try:
taskSettings = json.load(open(os.path.join(args.taskpath, 'taskSettings.json'), 'r'))
correctSolutions = taskSettings['correctSolutions']
... | 5,317,816 |
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)) | 5,317,817 |
def test_text_id():
"""ID is a numerical text"""
my_er = ExclusionRequest('25663')
assert my_er.id == 25663 | 5,317,818 |
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` instead.
Args:
... | 5,317,819 |
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... | 5,317,820 |
def table_coverage(class_name, name, root, Xsamp, burnin=500, MC=None, plot=False, movie=False, thinning=1,
loadDict=False, CI='quant'):
"""
:param class_name:
:param name:
:param root:
:param burnin:
:param MC:
:param plot:
:return:
"""
plt.close('all')
... | 5,317,821 |
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... | 5,317,822 |
def test_cpu_execution_type(
mocker, con, ipc: Optional[bool], gpu_device: Optional[int]
):
"""Test the combination of ipc and gpu_device parameters for connection."""
connection_info = {
'host': con.host,
'port': con.port,
'user': con.user,
'password': con.password,
... | 5,317,823 |
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
corouine.
args: positional arguments for this function.
kwargs: key argum... | 5,317,824 |
def construct_engine(engine, **opts):
""".. versionadded:: 0.5.4
Constructs and returns SQLAlchemy engine.
Currently, there are 2 ways to pass create_engine options to :mod:`migrate.versioning.api` functions:
:param engine: connection string or a existing engine
:param engine_dict: python diction... | 5,317,825 |
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... | 5,317,826 |
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, ... | 5,317,827 |
def test_sharpness_on_test_set(supply_test_set):
"""Test sharpness on the test set for some dummy values."""
_, test_std, _ = supply_test_set
assert np.abs(sharpness(test_std) - 0.648074069840786) < 1e-6 | 5,317,828 |
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... | 5,317,829 |
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"]
... | 5,317,830 |
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 ... | 5,317,831 |
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 ... | 5,317,832 |
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 | 5,317,833 |
def create_indexd_tables_no_migrate(
index_driver_no_migrate, alias_driver_no_migrate, auth_driver):
"""Make sure the tables are created but don't operate on them directly.
There is no migration required for the SQLAlchemyAuthDriver.
Also set up the password to be accessed by the client tests.
... | 5,317,834 |
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_factory = dict_f... | 5,317,835 |
def p2():
"""Day 6, Part 2
sum questions where everyone in group answered yes
"""
groups = load_data()
group_sums = []
for group in groups:
master_list = set([c for c in ''.join(group)])
group_sum = 0
for c in master_list:
group_sum += 1 if all(c in g for g ... | 5,317,836 |
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... | 5,317,837 |
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 FROM TABLE')
'\... | 5,317,838 |
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) | 5,317,839 |
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 ... | 5,317,840 |
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... | 5,317,841 |
def assess_number_signatures(
signatures: List[SnvSpectrum],
n: int,
decomposition: str,
decomposition_args: Optional[Mapping] = None,
iterations: int = 1,
) -> None:
"""Asses the number of signatures."""
raise NotImplementedError('Function placeholder.') | 5,317,842 |
def check_subtype(argtype, arg):
"""
check if the subtype is supported.
:param argtype: (type or List instance) a type or list object
:param arg: (Argument object) an Argument
"""
if isinstance(argtype, List):
if not handled_type(argtype.type, "s"):
print(message("unknown %s... | 5,317,843 |
async def test_ambilight_with_nightlight_disabled(hass: HomeAssistant):
"""Test that main light on ambilights with the nightlight disabled shows the correct brightness."""
mocked_bulb = _mocked_bulb()
properties = {**PROPERTIES}
capabilities = {**CAPABILITIES}
capabilities["model"] = "ceiling10"
... | 5,317,844 |
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()
for letter in x_tokens:
if not _check_su... | 5,317,845 |
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] | 5,317,846 |
def test_ids_from_path():
"""should get correct ids"""
check.equal(resources.ids_from_path(
"study/1/series/2/instances/3"), {'study_id': '1', 'series_id': '2', 'instance_id': '3', })
check.equal(resources.ids_from_path(
"study/1/series/2/instances/3/frames/4"),
{'study_id': ... | 5,317,847 |
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)
:param timestamp: timestamp to ... | 5,317,848 |
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... | 5,317,849 |
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 | 5,317,850 |
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) | 5,317,851 |
def start_in_keepedalive_processes(obj, nb_process):
"""
Start nb_process and keep them alive. Send job to them multiple times, then close thems.
"""
processes = []
readers_pipes = []
writers_pipes = []
for i in range(nb_process):
# Start process with Pipes for communicate
lo... | 5,317,852 |
def set_global_writer(writer: Writer) -> None:
"""
:return:
:rtype:"""
global GLOBAL_WRITER
# if GLOBAL_WRITER:
# GLOBAL_WRITER_STACK TODO: push to stack if existing?
GLOBAL_WRITER = writer | 5,317,853 |
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_(_... | 5,317,854 |
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) | 5,317,855 |
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,
seq,qual... | 5,317,856 |
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... | 5,317,857 |
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 | 5,317,858 |
def test_filter_by_date_interval():
"""Test filter by date interval"""
df = filter_by_date_and_resolution(df_data, "2019-12-27/2019-12-29", Resolution.HOURLY)
assert not df.empty
df = filter_by_date_and_resolution(df_data, "2020/2022", Resolution.HOURLY)
assert df.empty | 5,317,859 |
def generate_key():
"""
生成节点公私钥
:return:
私钥
公钥
"""
extra_entropy = ''
extra_key_bytes = text_if_str(to_bytes, extra_entropy)
key_bytes = keccak(os.urandom(32) + extra_key_bytes)
privatekey = keys.PrivateKey(key_bytes)
pubKey = keys.private_key_to_public_key(privatekey... | 5,317,860 |
def test_algorithm_process():
"""Algorithm_test.test_algorithm_process()
confirms that algorithm.process returns an obspy.core.stream object
"""
algorithm = Algorithm()
timeseries = Stream()
outputstream = algorithm.process(timeseries)
assert_equal(isinstance(outputstream, Stream), True) | 5,317,861 |
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’ happens when the system predicts a pair <term,defn> and there is some overlap (at least one toke... | 5,317,862 |
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... | 5,317,863 |
def average(aggregation, discard_zeros=False):
"""Perform the average aggregation"""
# This method take the data from the inmediate lower granularity and computes the
# average, then it insert the new average
try:
# Calculate the inmediate lower granularity:
LOGGER.debug('Requested gran... | 5,317,864 |
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, ... | 5,317,865 |
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... | 5,317,866 |
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... | 5,317,867 |
def record_CT(dataset_path):
"""load CT image folds into json format
"""
patients_dict = dict()
for p in os.listdir(dataset_path):
print(p)
patient_path = osp.join(dataset_path, p)
studies_list = dict()
for study in os.listdir(patient_path):
study_path = osp.j... | 5,317,868 |
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 and fail to buil... | 5,317,869 |
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 a handler which runs a given callback when the specified item is activated.
Args:
parent (... | 5,317,870 |
def main(argv=None, abort=False, debug=None):
"""Drive the validator.
This function acts as the command line interface backend.
There is some duplication to support testability.
"""
init_logger(level=logging.DEBUG if debug else None)
forest = argv if argv else sys.argv[1:]
if not forest:
... | 5,317,871 |
def filter_files(files, search_settings):
"""
Filter a list of files based on the search settings
"""
ret_val = []
patterns = search_settings['patterns']
for f in files:
try:
file_path = f.path
except AttributeError:
file_path = f
for path in searc... | 5,317,872 |
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)) | 5,317,873 |
def append_county_time_series(**kwargs):
"""
Load JHU's CSV and append today's US county data.
"""
# (1) Load historical time-series
historical_df = load_jhu_us_time_series()
# (2) Bring in current JHU feature layer and clean
today_df = load_jhu_us_current()
# (3) Fill in missing stuff... | 5,317,874 |
def download_hourly_csv(out_file, begin_date, end_date, station, product='water_level', datum='STND', time_zone='GMT'):
"""Download hourly water level or meteorology csv file from NOAA CO-OPS website.
Uses API described at https://tidesandcurrents.noaa.gov/api
Note that there is a limit of 365 days.
I... | 5,317,875 |
def test_get_meta_data_by_product_id_no_data_found(_udm_mock):
"""Tests that an empty Metadata object is returned if no Metadata was found for a given product id"""
lh = univention.bildungslogin.handlers.LicenseHandler(MagicMock())
with patch.object(lh, "_meta_data_mod") as meta_data_mod_mock:
meta_... | 5,317,876 |
def cleanup_rds_clusters(neo4j_session: neo4j.Session, common_job_parameters: Dict) -> None:
"""
Remove RDS cluster graph nodes
"""
run_cleanup_job('aws_import_rds_clusters_cleanup.json', neo4j_session, common_job_parameters) | 5,317,877 |
def printf_line(*args):
"""printf_line(int indent, char format, v(...) ?) -> bool"""
return _idaapi.printf_line(*args) | 5,317,878 |
def mainfunction(text):
"""
Main function. Calls all other functions, depending on whether the macro input is in python or c++.
It adds the header information. Also, it adds a cell that draws all canvases. The working text is
then converted to a version 3 jupyter notebook, subsequently updated to a vers... | 5,317,879 |
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
absolute value o... | 5,317,880 |
def test_difference(minion_opts, local_salt):
"""
Test the `difference` Jinja filter.
"""
rendered = render_jinja_tmpl(
"{{ [1, 2, 3] | difference([2, 3, 4]) | join(', ') }}",
dict(opts=minion_opts, saltenv="test", salt=local_salt),
)
assert rendered == "1" | 5,317,881 |
def load_example_asos() -> DataFrame:
"""
Fixture to load example data
"""
example_data_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "staticdata")
)
data_path = os.path.join(example_data_path, "AMW_example_data.csv")
return meteogram.download... | 5,317,882 |
def test_fetch_and_serialize_unused_coupons_empty(user):
"""
Test that fetch_and_serialize_unused_coupons returns an empty list for users
that have no unredeemed coupon assignments
"""
ProductCouponAssignmentFactory.create(email=user.email, redeemed=True)
unused_coupons = fetch_and_serialize_unu... | 5,317,883 |
def daemonize(mountpoint, options):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
pid = os.fork()
if pid > 0:
# wait for mount to be ready
... | 5,317,884 |
def optionMenu(*args, **kwargs):
"""
This command creates a popup menu control.
Returns: `string` Full path name to the control.
"""
pass | 5,317,885 |
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 ... | 5,317,886 |
def SLC_phase_shift(SLC_1, SLC_par1, SLC_2, SLC_par2, ph_shift, logpath=None, outdir=None, shellscript=None):
"""
| Add a constant phase from an SLC image
| Copyright 2015, Gamma Remote Sensing, v1.1 1-Dec-2015 clw
Parameters
----------
SLC_1:
(input) SLC data file (fcomplex or scomplex... | 5,317,887 |
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] *... | 5,317,888 |
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)
... | 5,317,889 |
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... | 5,317,890 |
def validate_community_config(api, community, aspaths, med, origin):
"""
Validate BGP Attributes Config
"""
ixnetwork = api._ixnetwork
bgpv4 = (
ixnetwork.Topology.find()
.DeviceGroup.find()
.NetworkGroup.find()
.Ipv4PrefixPools.find()
.BgpIPRouteProperty.fin... | 5,317,891 |
def file_str(f):
"""
:param f: 输入完整路径的文件夹或文件名
:return: 返回简化的名称
a/b ==> <b>
a/b.txt ==> b.txt
"""
name = os.path.basename(f)
if os.path.isdir(f):
s = '<' + name + '>'
else:
s = name
return s | 5,317,892 |
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... | 5,317,893 |
def xdoctest(session: Session) -> None:
"""Run examples with xdoctest."""
if session.posargs:
args = [package, *session.posargs]
else:
args = [f"--modname={package}", "--command=all"]
if "FORCE_COLOR" in os.environ:
args.append("--colored=1")
session.install(".")
... | 5,317,894 |
def del_vars_stack():
"""Delete the last substack from the function stack"""
vars_stacks[-1].pop() | 5,317,895 |
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 | 5,317,896 |
async def dreadful(message):
"""
"""
global average_typing_speed
if message.author != bot.user:
msg = message.content
if msg == "Did you ever want to live in the nineteenth century?" \
or msg == "Do you think you could find out all the answers to all the questions?" \
... | 5,317,897 |
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... | 5,317,898 |
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 | 5,317,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.