content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def adapt_field(field):
""" Convert sql field name to application field
"""
if field in app_fields:
adapted_field = app_fields[field]
if adapted_field != '':
return adapted_field
return field | b4b76945e37a9ecca798d1a481a7048366e88080 | 48,544 |
def im_to_double(im):
"""
"""
min_val = np.min(im.ravel())
max_val = np.max(im.ravel())
return (im.astype('float') - min_val) / (max_val - min_val) | 306fc3a7ab582182d3c7f149fdd8592fd850f632 | 48,545 |
def dos_from_bands(bands, smearing, npoints):
"""
Compute DOS from bands
:param bands: The `BandsData` to be used as input.
:param smearing: Smearing width in eV
:param npoints: Number of points
"""
bands_data = bands.get_bands(also_occupations=False, also_labels=False)
_, weights = ban... | fdb04989332011196eb7e12790f5dc27c65b6053 | 48,546 |
import numpy
def cubeellipse(theta, lam=0.6, gamma=1.0, s=4.0, r=1.0, h=1.2):
"""Create an RGB colormap from an input angle theta. Takes lam (a list of
intensity values, from 0 to 1), gamma (a nonlinear weighting power),
s (starting angle), r (number of revolutions around the circle), and
h (a hue fac... | 54b5c36c544e344c7235cc0969e8f974097faaa2 | 48,547 |
from typing import IO
from typing import Any
def load(f: IO[str]) -> Any:
"""YAML load data from stream
Args:
f (IO[str]): IO Stream with data
Returns:
Any: YAML Data
"""
yml = ruamel.yaml.YAML(typ="safe")
return yml.load(f) | a28f64dbb71efc48e559cf4df80cdf436b3ba8a8 | 48,548 |
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
a_substrings = set(substring_tokenize(a, n))
b_substrings = set(substring_tokenize(b, n))
return a_substrings & b_substrings | a0f089280616985606f1fa65333274b3e9a55094 | 48,549 |
def iteritems(dictionary):
"""Replacement to account for iteritems/items switch in Py3."""
if hasattr(dictionary, "iteritems"):
return dictionary.iteritems()
return dictionary.items() | 591bba21a1026d2e9d380555623c8ca78d3ed466 | 48,550 |
def validate_testapps(apis, api_configs):
"""Ensures the chosen apis are valid, based on the config."""
if "all" in apis:
return [key for key in api_configs]
for api in apis:
if api not in api_configs:
raise RuntimeError("Testapp given as flag not found in config: %s" % api)
return apis | 4726ae4e28bb57e2fa812cd0fa3721d38ba1103a | 48,551 |
def _encrypt_bhv(trace):
"""
加密轨迹
:param trace:
:return:
"""
with open('ysf_slider.js', 'rb') as f:
js = f.read().decode()
ctx = execjs.compile(js)
return ctx.call('getCompress', trace) | 6be3b7012b835ad6fd561c9fb377a87bbbb14b09 | 48,552 |
import copy
def prune_basis(basis, use_copy=True):
"""
Removes primitives that have a zero coefficient, and
removes duplicate shells
This only finds EXACT duplicates, and is meant to be used
after uncontracting
If use_copy is True, the input basis set is not modified.
"""
if use_cop... | 8847539ce717868e9383db52e39008bbae2882f0 | 48,553 |
def insert(node, data):
"""
Insert data in BST rooted at node if necessary, and return new root.
Assume node is the root of a Binary Search Tree.
@param BinaryTree node: root of a binary search tree.
@param object data: data to insert into BST, if necessary.
>>> b = BinaryTree(8)
>>> b = ... | 7f4afbdbf766f2e8aca20f23fc53ee7a909d876d | 48,554 |
def read_version(other_file_name, filename):
"""Read the the current version or build of the app"""
version = ""
version = read_file(other_file_name, filename)
if version:
version = version.rstrip()
if not version:
version = "__UNKNOWN__"
return version | 5c462299e66b9c3272122488416a7c15f7df463a | 48,555 |
def api_tag_list():
"""Listing for all tags.
"""
tags = db.session.query(database.TagRecord).all()
return _tags_response(tags) | ec7ae513546001bf64b2b3c486dfc42daacd5c8a | 48,556 |
def load_file_as_str(file_path: str) -> str:
"""
Loads the file at a specificed path, returns an error otherwise
:param file_path (str): The path to the file you want to load
:return _file a str of the contents of the file
"""
_file = ""
try:
with open(file_path, "r") as fp:... | 45eaa87ed0570f618d1eef2c5e05a06dea97b2dc | 48,557 |
def _dol_to_lod(dol):
"""Convert a dict-of-lists into a list-of-dicts.
Reverse transformation of :func:`_lod_to_dol()`.
"""
keys = list(dol.keys())
lod = []
for i in range(len(dol[keys[0]])):
lod.append({k: v[i] for k, v in dol.items()})
return lod | 9e8a98d2502797ae27cae88ab2a0ec7fda4aff34 | 48,559 |
def infomap(adata: AnnData, basis: str = "umap", color: str = "infomap", *args, **kwargs):
"""\
Scatter plot for infomap community detection in selected basis.
Parameters
----------
adata: :class:`~anndata.AnnData`
an Annodata object.
%(scatters.parameters.no_adata|basis)s
... | eec92a19e93c080137aba2648d96c30ed9ba72df | 48,560 |
def get_base_complex_data(model, complex_id):
"""If a complex is modified in a metabolic reaction it will not
have a formation reaction associated with it. This function returns
the complex data of the "base" complex, which will have the subunit
stoichiometry of that complex"""
# First try unmodifi... | c91841798c11b6e867130c7d6128756492e738e3 | 48,562 |
def update_content(content_id):
"""
**Update Information of a Specific Content Record**
This function allows user to update a specific content information through their content_id.
:param content_id: id of the content
:type content_id: int
:return: content information updat... | 8a83cd349e3b1030eaeac967cc0804ee51d8ffb6 | 48,564 |
def compute_winner_index(interactions, game=None):
"""Returns the index of the winner of the Match"""
scores = compute_final_score(interactions, game)
if scores is not None:
if scores[0] == scores[1]:
return False # No winner
return max([0, 1], key=lambda i: scores[i])
retu... | 7cd5e0cb357ee3bc0505e6d5467ed651d097c08e | 48,565 |
def get_shard_index(shard_name):
"""Returns tuple of shard index, num_shards based on a shard name."""
if shard_name in ['0', '-']:
return 0, 1
shard_begin, shard_end = shard_name.split('-')
num_bytes_used = max(len(shard_begin), len(shard_end)) / 2
if shard_begin:
shard_begin = int(shard_begin, 16)
... | 69a6bc62b64287599536ed5d529392de6e362e7e | 48,566 |
def decode_segmap(label_mask, dataset='pascal'):
"""Decode segmentation class labels into a color image
Args:
label_mask (np.ndarray): an (M,N) array of integer values denoting
the class label at each spatial location.
Returns:
np.ndarray: the resulting decoded color image.
"""... | cdead8c808783bd93cbb80f2317e8e24b71e7172 | 48,567 |
def PullToBrepFace1(thisCurve, face, tolerance, multiple=False):
"""
Pulls this curve to a brep face and returns the result of that operation.
Args:
face (BrepFace): A brep face.
tolerance (double): A tolerance value.
Returns:
Curve[]: An array containing the resulting curves a... | aa8823baa84e8b0503d956f9c43fc7481dbd2745 | 48,568 |
def medfilereader(filename, varsToExtract = 'all',
sessionToExtract = 1,
verbose = False,
remove_var_header = False):
"""
Reads in Med Associates file stored as single column and returns variables as lists.
Args:
filename - file to be read i... | 86c9f773fe4e95574eb7f109831a243beb0c7b5b | 48,571 |
def get_label(node_name):
""" Function that returns the label of a specific docker node (eg. label can be loc=edge).
Args: node_name: name of the docker node
Returns: dictionary of the label: dict["label"] = "value"
"""
return_dict = {}
cmd = "sudo docker node inspect -f '{{ range $k, $v... | 0656a6777f4af94cc8e62c660821f2fcd9c4649e | 48,573 |
def product_vector4_4x4(vector,matrix):
"""mulipli le vector 4 par une matrice care de 4"""
x = matrix[0][0]*vector[0] + matrix[0][1]*vector[1] + matrix[0][2]*vector[2] + matrix[0][3]*vector[3]
y = matrix[1][0]*vector[0] + matrix[1][1]*vector[1] + matrix[1][2]*vector[2] + matrix[1][3]*vector[3]
z = matrix[2][0]*vec... | 13a90165fd2a08af0d380f3b2bc541554f377b11 | 48,574 |
def ghostnet(**kwargs):
"""
Constructs a GhostNet model
"""
cfgs = [ # input e.g. 512 x 512
# k, t, c, SE, s
# stage1
[[3, 16, 16, 0, 1]], # 256 x 256
# stage2
[[3, 48, 24, 0, 2]],
[[3, 72, 24, 0, 1]], # 128 x 128
# stage3
[[5, 7... | ba619b9006e343e71ad917ccc5668ff891435a49 | 48,575 |
def soft_normal(v, alpha):
"""ソフト正規化関数"""
v_norm = np.linalg.norm(v)
softmax = v_norm + 1 / alpha * np.log(1 + np.exp(-2 * alpha * v_norm))
return v / softmax | bb81b4d6be688629e354ffb9a17780e55e86591f | 48,577 |
def wrap_decoder(trg_vocab_size,
max_length,
n_layer,
n_head,
d_key,
d_value,
d_model,
d_inner_hid,
prepostprocess_dropout,
attention_dropout,
relu_dr... | 25d828de5a7c4e590fe8e09152fa226f4d72606b | 48,578 |
def eval_feature_detail(Info_Value_list,out_path=False):
"""
format InfoValue list to Dataframe
:param Info_Value_list: Instance list of Class InfoValue
:param out_path:specify the Dataframe to csv file path ,default False
:return:DataFrame about feature detail
"""
rst = Info_Value_list
... | aa911f01c8b41964e0883f23a76784ffae57aa7e | 48,579 |
def get_answer_phrase(question, sentence):
"""
Given a question and the sentence with an answer, extract the answer.
:param question: Question asked of us.
:param sentence: Sentence with question in it.
:return: string phrase of answer
"""
# Tokenize question for W-word
q_toks = nltk.wo... | 856b1667361bf1b8faf5d6ea3ffe6a071ef32ef8 | 48,581 |
def get_search_queries(phrase):
"""Return querysets to lookup different types of objects.
Args:
phrase (str): searched phrase
"""
return {
'skills': _search_skills(phrase),
'users': _search_users(phrase),
'tasks': _search_orders(phrase)} | 3d279b435932df28e19170d3277ec5e1a281e21d | 48,582 |
def sortclosestpoints(pt0, pts):
"""return pt index in pts sorted by increasing distance from pt0
Note: cartesian distance
"""
x1, y1 = pt0
x2, y2 = np.array(pts).T
diffx = x1 - x2
diffy = y1 - y2
dist = np.hypot(diffx, diffy)
sortedindices = np.argsort(dist)
sortedistances ... | 2fb81bd1c8e975f12dd34b7aa3d8124c53b6c9a8 | 48,583 |
def prune_properties(document, paths):
"""Prune given properties from a document.
This assumes properties will always have an object (dict) as a parent.
The function modifies the document in-place, but also returns the document
for convenience. (The return value may be ignored.)
"""
for path in... | 299734c7c09513f6e6b840ec126d85975b39cfc0 | 48,584 |
def HT_DCPERIOD(df):
"""
函数名:HT_DCPERIOD
名称: 希尔伯特变换-主导周期
简介:将价格作为信息信号,计算价格处在的周期的位置,作为择时的依据。
[文库文档](https://wenku.baidu.com/view/0e35f6eead51f01dc281f18e.md)
NOTE: The ``HT_DCPERIOD`` function has an unstable period.
python API
real=HT_DCPERIOD(close)
:return:
"""
close = d... | f1ca7a7a4b05512a4ecac43b1c9adbf5dcdddd95 | 48,585 |
def exp(str_in, expansion):
"""exp():
"""
return perm(str_in, expansion) | 191a20d550f494f7d17aaaadf9251c25912ddb5d | 48,587 |
import itertools
def compat_tee(iterable):
"""Return two independent iterators from a single iterable.
Based on http://www.python.org/doc/2.3.5/lib/itertools-example.html
"""
# Note: Using a dictionary and a list as the default arguments here is
# deliberate and safe in this instance.
def gen... | 025e809961bd098aaede070c2fa8090c59d31b5a | 48,588 |
def uint8(image:'np.ndarray')->'np.ndarray':
"""Convert to uint8
Args:
image('np.ndarray'):
Returns:
Raises:
"""
# Change range 0-1 to 0-255 and change type to uint8
return (image*255).astype(np.uint8) | e38a61d93c2e70f33a5d6768d1b870f96e5ebb67 | 48,589 |
def _p(pp, name):
"""
make prefix-appended name
"""
return '%s_%s'%(pp, name) | 0a38c89384830b8fc11cb19187c684112408c784 | 48,590 |
def map_to_parent(t_class, parents_info_level):
"""
parents_info_level: {<classid>: [parent]}, only contains classid that has a super-relationship
"""
if t_class in parents_info_level:
assert len(parents_info_level[t_class]) < 2, f"{t_class} has two or more parents {parents_info_level[t_class]}... | a92cf3671aff03724ac89ef024089df06ae28d4a | 48,591 |
from typing import Optional
from typing import cast
import ftplib
import re
from datetime import datetime
import logging
def _get_mtime(c: FTPClient, path: str) -> Optional[int]:
"""Returns timestamp of last modification"""
try:
mdtm = cast(ftplib.FTP, c).sendcmd("MDTM " + path)
# mdtm-respons... | e3319e7775f236398fee9b06d1d2ddf0da300d46 | 48,592 |
def argParse():
"""Parses commandline args."""
desc='Scrape the doxygen generated xml for docstrings to insert into python bindings'
parser = ArgumentParser(description=desc)
parser.add_argument("function", help="Operation to perform on docstrings", choices=["scrape","sub","copy"])
parser.add_... | 6536c83561727ca0e9b1c39ec670ea0d3d9c4ae2 | 48,593 |
import uuid
def get_temp_entity_table_name() -> str:
"""Returns a random table name for uploading the entity dataframe"""
return "feast_entity_df_" + uuid.uuid4().hex | 62d8b0ca2d58fb813db88caa753f93e412c62ad0 | 48,594 |
def _sort_mixed(values) -> np.ndarray:
"""order ints before strings in 1d arrays, safe in py3"""
str_pos = np.array([isinstance(x, str) for x in values], dtype=bool)
nums = np.sort(values[~str_pos])
strs = np.sort(values[str_pos])
return np.concatenate([nums, np.asarray(strs, dtype=object)]) | a7aa58f6f33737285c563492d99f3d62dc8a6ade | 48,595 |
def lpmm2lpph(lpmm, n, pixelPitch):
"""Convert resolution specified in Line-Pair per Milli Meters (LPMM) to
Line-Pair per Picture Height (LPPH)
Parameters
----------
lpmm : float
resolution in terms of Line-Pair per Milli-Meters (LPMM)
n : integer
Number of pixels in the picture... | e4cfaa0376830cb3a33c05ad1d2eba78ff6312e0 | 48,596 |
def isPalindrome1(s, indent):
"""Return True if s is a palindrome and False otherwise."""
print indent, "isPalindrome called with", s
if len(s) <= 1:
print indent, "About to return True from base case"
return True
else:
ans = s[0] == s[-1] and isPalindrome1(s[1:-1], indent + inde... | 38fe4a949a4795ec5e957a3d05949c8a46ab0559 | 48,597 |
from typing import Tuple
def _parse_gcs_url(gsurl: str) -> Tuple[str, str]:
"""
Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a
tuple containing the corresponding bucket and blob.
"""
parsed_url = urlparse(gsurl)
if not parsed_url.netloc:
raise AirflowException('Plea... | 12f2a8dbff5bab0f7586d17ac777a07e6efadc1f | 48,598 |
def transformation_task(df):
"""Tranform original dataset.
:param_df: Input Dataframe.
:return: Transformed DataFrame.
"""
##Prepare dataframes
spark.sql('use xxx_usercrypto_db')
##create staging table
# spark.sql('drop table if exists stg_users')
# df.write.saveAsTable('stg_users')... | 6ffa8d7ae22b73ea39bc59483a2f7855c04d6ca6 | 48,600 |
def is_weight_node(node):
"""
Check if the node is weight type.
Args:
node (Node): The node object.
Returns:
bool, if the node is weight type.
"""
if node.type == NodeTypeEnum.PARAMETER.value:
full_name = node.full_name.lower()
weight_flag = False
if ful... | 283f90340bfa0feb81073a4113dfd645929ac4a2 | 48,601 |
def dict_to_qbody(d, prefix=''):
"""
Generates a string representing a query body from an AST dict.
:param d: AST dict
:param prefix: needed in case it will recurse
"""
if type(d) is not dict:
return ''
s = ''
iprefix = prefix + '\t'
args = ''
for k, v in d.items():
... | c297835a7f72be9f749e55c33441edadf22b6ee0 | 48,602 |
def has_setter(obj, attr):
"""True if an attribute has an associated setter.
Parameters
----------
obj : object
Any class instance.
attr : str
Name of the attribute to check.
"""
_check_is_attr_name(attr)
return True if has_property(obj, attr) and \
g... | 6414f935a8843164a343df5b17930d614afb330e | 48,603 |
import pydensecrf.densecrf as dcrf
from pydensecrf.utils import (
unary_from_labels, unary_from_softmax,
create_pairwise_bilateral, create_pairwise_gaussian)
def FC_CRF(pred, im, NLABELS, RESIZE_FACTOR= 5,
DELTA_COL= 5, DELTA_SIZE= 5, n_steps=10,
CERTAINTY= 0.7, mode= "multilabel"):
... | 5acf086e5bc4477a8d994291622cd887f1642d4b | 48,604 |
import math
def convert_to_samples(c, deg, boundary_condition='Mirror', in_place=False):
"""
Convert interpolation coefficients into samples
In the input array, the signals are considered along the first dimension
(1D computations).
"""
n = c.shape[0]
if n == 1:
return c
kerl... | c3f0d47d00495058075f4889f45b155fdd06ef07 | 48,605 |
from .signaltools import get_window
def firwin2(numtaps, freq, gain, nfreqs=None, window='hamming', nyq=1.0,
antisymmetric=False):
"""
FIR filter design using the window method.
From the given frequencies `freq` and corresponding gains `gain`,
this function constructs an FIR filter with l... | 7d5a34ec8d1272989f1785d06425d698893de8d0 | 48,606 |
def run_notebook_or_python(clname, path, params):
"""원격 노트북 인스턴스에서 노트북 또는 파이썬 파일 실행.
Returns:
tuple: (stdout, exit_code)
"""
info("run_notebook_or_python: {} - {}".format(clname, path))
check_cluster(clname)
clinfo = load_cluster_info(clname)
dask = 'type' in clinfo and clinfo['ty... | ac872e8bf8e26b4dcdf10894de00b2be97e02463 | 48,607 |
def remove_raw_object(cls):
"""
Decorator.
If a Record class is decorated, raw_object will be removed once all mark properties are cached.
"""
cls.remove_raw_object = True
return cls | 9aab8feb4201237864de5eae891a98ed3894d862 | 48,608 |
def change_user_password():
"""
User-friendly function to be used on first boot for changing user passwords
"""
usernames = get_nonroot_nonsystem_users()
if len(usernames) == 0:
logger.warning("Can't detect any users! Changing root password instead")
usernames = ["root"]
for name... | 5e734e66508ae4a96a5f463c202d61436f5e9430 | 48,610 |
def columnOfMatrix(matrix, i):
"""
Метод для получения i-го столбца матрицы
"""
return [row[i] for row in matrix] | 605c95e7cf90dca575bdcf8d4bc434b850131c21 | 48,611 |
import datasets
import time
def run_wall_clock_test(optimizer,
problem,
num_steps,
dataset=datasets.EMPTY_DATASET,
seed=None,
logdir=None,
batch_size=None):
"""Runs optim... | 3fceec7ebd2dcd4c3e7052035e7f177024378e3a | 48,612 |
def p_list_formatter(primer_list):
"""
Reformat the primer list (remove unnecessary characters from biopython2 output).
Args:
primer_list (list): list from list_from_gen output
Returns:
primer_dimers (list): list with unnecessary chars removed.
"""
reformat_p_list = []
primer... | 0b1585221a13c3560d511127af782875fcd71732 | 48,613 |
def fullpath(dataset):
"""
return absolute path to dataset
dataset is an array as returned by CURDATA()
"""
dat = dataset[:] # make a copy because I don't want to modify the original array
if len(dat) == 5: # for topspin 2-
dat[3] = join(normpath(dat[3]), 'data', dat[4], 'nmr')
f... | 5aa8ba5f2d2abca6a33e42af1d8017f72791dda0 | 48,614 |
def edit_meeting(request, club_name, meeting_id):
"""Edit details of meeting"""
current_club = Club.objects.get(club_name=club_name)
meeting = Meeting.objects.get(id=meeting_id)
form = MeetingForm(instance=meeting)
if request.method == 'POST':
form = MeetingForm(request.POST, instance=meetin... | dec2e6704e498ba093e5ca225d821bfee09b2a73 | 48,615 |
def parse_mulplt(path):
"""
Parses MULPLT.DEF file and returns list of lists like: [station, channel type (e.g. SH), channel (E, N or Z)].
"""
data = []
with open(path, "r") as f:
lines = f.readlines()
tag = "#DEFAULT CHANNEL"
for line in lines:
if line[:len(tag)... | c18bad56944c4c8617c0b8c98d5c01cde822de56 | 48,616 |
def status():
"""Status check for server"""
return "Running...\n" | 89b001639d8983cfb2d8705bfcdfdcc6fc8750a4 | 48,617 |
def parse(report_file: str, summary_file: str) -> dict:
"""
Check input file is an accepted file, then select the appropriate parsing method.
Args:
report_file (str): An Ariba report file of clusters which passed filtering.
summary_file (str): A summary file of the report
Returns:
... | 457620a773132eaca13c5b1437781037a7f610f9 | 48,618 |
import pickle
def load_sim(filename):
"""Load a saved simulation"""
with open(filename, "rb") as f:
sim = pickle.load(f)
return sim | 712ce4bc662ec04acc4364515cbc502d01712e8c | 48,619 |
def _repr_rule(iptc_rule, ipv6=False):
""" Return a string representation of an iptc_rule """
s = ''
if ipv6==False and iptc_rule.src != '0.0.0.0/0.0.0.0':
s += 'src {} '.format(iptc_rule.src)
elif ipv6==True and iptc_rule.src != '::/0':
s += 'src {} '.format(iptc_rule.src)
if ipv6==... | e01c3b27ec6ee831a7d88fc87e69e707639ef0b6 | 48,620 |
def CV_IS_SEQ_CLOSED(*args):
"""CV_IS_SEQ_CLOSED(CvSeq seq) -> int"""
return _cv.CV_IS_SEQ_CLOSED(*args) | 2551448332db2e0375cbb4afaaf59f9a398c6216 | 48,621 |
def add_padding_0_bits(bits_string: str, required_length: int) -> tuple:
"""
Adds 0 to bits string.
Returns tuple - (bits string with padding, number of added 0s)
"""
extra_0_bits_count = 0
while len(bits_string) < required_length:
bits_string += '0'
extra_0_bits_count += 1
r... | fd3eee071821d087b710c33a0beef72431836505 | 48,623 |
def get_sheet(filename):
"""
Open workbook and return first worksheet as object
Args:
filename: local file name
Returns:
Worksheet object
"""
wb = load_workbook(filename)
return wb.worksheets[0] | 34015122747021a6a6b815bef62f689818fb523d | 48,624 |
def object_clearance():
"""
Check for two Objects Clearance distance:
Quick measurements between parallel faces and similarly placed objects
Original code from: Bill 03/2015
Adapted to WF by : Rentlau_64 03/2015
"""
global verbose
msg = verbose
m_actDoc = get_ActiveDocument(info=m... | 16c52c178a3485ed10da5a221d8a501e74d06700 | 48,625 |
import json
def readlasfile(lasfile):
"""
Run a PDAL pipeline. Input is a JSON declaration to
deliver to PDAL. Output is a labelled numpy array.
Data are filtered to compute height above ground using nearest ground point neighbours (TIN method arriving soon) and sort by morton order. Any unused dimen... | 12aa456f0dd062b41a4b4cd719aa3a896020bd47 | 48,626 |
def avgpool_4x4(inputs, downsample=False):
"""
avgpool_4x4
"""
return avgpool_base(inputs, (4, 4), downsample) | 973d8b4066f1e8eea7dcf20baae6df24e4029044 | 48,628 |
def str_data(group, field, default=''):
"""
Retrieve value of field as a string, with default if field is missing.
"""
if field in group:
data = group[field][0]
if data.ndim > 0:
value = [_s(v) for v in data]
else:
value = _s(data)
return value
... | c6f4a886eb64fa2b44a151e3032de8a5381b46b1 | 48,629 |
def filter_attributes(func):
"""Filters and removes attributes from User Dictionary objects depending on test requirements."""
@wraps(func)
def filter_attributes_wrapper(*args, **kwargs):
# Get generated users.
users = func(*args, **kwargs)
# If only single user (dict), treat as a ... | 98c81d09e56e240c106cc4ee6cd5a3b158796396 | 48,630 |
def mask_source_centers(array, fwhm, y, x):
""" Creates a mask of ones with the size of the input frame and zeros at
the center of the sources (planets) with coordinates x, y.
Parameters
----------
array : array_like
Input frame.
fwhm : float
Size in pixels of the FWHM.
y, x... | 9b2627ab24a19d6b1921092d3bdd94ff8b0ef70b | 48,631 |
def IsInstance(type_):
"""Returns a function which can be used to check whether or not a value is of the given type."""
def Do(item):
return isinstance(item, type_)
return Do | 06f916e8658761a03619834692d78a44d145b514 | 48,632 |
from typing import Set
def random_proof_tree(rules_dict: RulesDict, root: int) -> Node:
"""Return random tree found by breadth first search."""
seen: Set[int] = set()
root_node = Node(root)
queue = deque([root_node])
while queue:
v = queue.popleft()
rule = choice(list(rules_dict[v.... | 8193a767b88607c018afc8f3099dddfb149f2fed | 48,633 |
def PCreate (name, uvData, err):
"""
Create the parameters and underlying structures of a set of images.
* name = Name to be given to object
* uvData = Python uv data from which the image mosaic will be derived
Most control parameters are in InfoList member
* err = Pyt... | 5bbe747a32f69c865a50082d3639d8da73cda265 | 48,634 |
def split_addresslines( lines ):
"""
Split up to 4 lines into appropiate fields (org, dept, street 1/2)
"""
data = {
'organisation': '',
'department': '',
'street_1': '',
'street_2': '',
}
if len(lines) == 0:
pass
elif len(lines) == 1:
data['s... | 481755042c10b54c9724c30c71ba6c9d29bdff91 | 48,638 |
import glob
from pathlib import Path
import importlib
def supported_format():
""" give supported formats """
if not bool(__supported_format__):
modules = glob.glob(join(dirname(__file__), "*.py"))
module_name = [Path(local_file) for local_file \
in modules if not '__init__... | e9f2ae9d7c68399386a444c81b063ec472d77ea1 | 48,639 |
def _make_edge_trace(graph_nx: nx.Graph, pos: dict) -> Scatter:
"""(HELPER) This function is a helper function to visualize_graph_with_attributes.
Return a trace containing lines which represent edges between nodes
given the position of nodes in pos.
"""
x_edges = []
y_edges = []
for edge... | f3e6502779f9b1efcf46ed3f169bf6708ee566c8 | 48,640 |
def import_tnmr(path):
"""
Import tnmr data and return dnpdata object
Args:
path (str) : Path to .jdf file
Returns:
tnmr_data (object) : dnpdata object containing tnmr data
"""
attrs = import_tnmr_pars(path)
values, coords, dims = import_tnmr_data(path)
tnmr_data = dn... | c10723983e5c4bc33adeee6b12f9265e6f04fb64 | 48,641 |
def focal_loss(
y_true,
y_pred,
alpha=[1-0.25, 0.25],
gamma=2.0,
from_logits=False
):
"""
Computes the multi-class focal loss, with class balancing parameter.
Parameters
----------
y_true : tensor
Targets of shape [num_targets,].
y_pre... | 1cf0907eb2d3c8d3c9be71e62e1140ec264f6d41 | 48,642 |
import aeneas.cdtw.cdtw
import aeneas.cmfcc.cmfcc
import aeneas.cew.cew
def can_run_c_extension(name=None):
"""
Determine whether the given Python C extension loads correctly.
If ``name`` is ``None``, tests all Python C extensions,
and return ``True`` if and only if all load correctly.
:param st... | b93b160e448d0d71b42fade1dbeefb63b7a53225 | 48,643 |
def _merge_surrogates(text):
"""Returns a copy of the text with all surrogate pairs merged"""
return _decode_surrogatepass(
text.encode("utf-16-le", _surrogatepass),
"utf-16-le") | 4d887b1352c23900c8ca5829c347c248ac10c3c8 | 48,644 |
def show_nums_to_user():
"""
093
Ask the user to enter five numbers. Sort them into order and present them to the user.
Ask them to select one of the numbers. Remove it from the original array and save it in a
new array.
:return: new array with one (popped) item.
"""
arr, trigger = [], 5... | 3b5a365dd729623ede7079d5d131ecc9f40897e7 | 48,646 |
from re import X
def player(board):
"""
Returns player who has the next turn on a board.
"""
if terminal(board):
return
elif board == initial_state():
return X
else:
no_of_X = 0
no_of_O = 0
for row in board:
no_of_X += row.count("X")
... | 542698f474894fcdfa60a440e653a52dae6dbab5 | 48,647 |
def seq_type(seq):
"""
Determines whether a sequence consists of 'N's only
(i.e., represents a gap)
"""
return 'gap' if set(seq.upper()) == {'N'} else 'bases' | 5555e5cd0ccdbf8f5e7b475c5c983ab54a17fb07 | 48,648 |
from typing import Tuple
def get_rows_and_columns(num_plots: int) -> Tuple[int, int]:
"""Get optimal number of rows and columns to display figures.
Parameters
----------
num_plots : int
Number of subplots
Returns
-------
rows : int
Optimal number of rows.
cols : int
... | c1c6f40423975459f08e71c764ffa2c1b81ce90d | 48,649 |
from typing import Union
import ast
def get_fixture_decorator(node: AnyFunctionDef) -> Union[ast.Call, ast.Attribute, None]:
"""
Returns a @pytest.fixture decorator applied to given function definition, if any.
Return value is either:
* ast.Call, if decorator is written as @pytest.fixture()
* ast... | 717e63c4f585e0a28fc08ad07b7892bf61d44b01 | 48,650 |
def do__AcmeV2_AcmeOrder__acme_server_sync(
ctx,
dbAcmeOrder=None,
authenticatedUser=None,
):
"""
:param ctx: (required) A :class:`lib.utils.ApiContext` instance
:param dbAcmeOrder: (required) A :class:`model.objects.AcmeOrder` object to refresh against the server
:param authenticatedUser: (... | 060af883b56ea44826a0d2de3c3a0874449a87f5 | 48,651 |
def static_equilibrium(topology, tmax=100, eta=1e-6, verbose=False, callback=None):
"""
Generate a form diagram in static equilibrium.
Parameters
----------
topology : :class:`compas_cem.diagrams.TopologyDiagram`
A topology diagram.
tmax : ``int``, optional
Maximum number of ite... | 3ae9f86fa47a83f965e1733211b5d2a32765a235 | 48,652 |
from random import shuffle
def chooselabelsubset(lst, n, method):
"""Chooses a subset of the given list, using the given method:
start: from the beginning
end: from the end
random: randomly
"""
# pick the the trainpos and trainneg sets
def randindexes(lst):
"""Ret... | bd922b22654b4bcaf6ed1bb8161b3c582f7f3427 | 48,653 |
import logging
def create_logger() -> logging.Logger:
""" Creates a logging object to be used for reports. """
# Gets a logger object with the name 'gol_logger' and sets the log level to INFO.
#
# Sets an absolute path log_path to the log file _Resources/gol.log, then runs
# logging.FileHandler t... | 48a161b1c4c5856568a87dedf37b06e6a6a5a6bb | 48,654 |
def s_quantifier(num, quantifier):
"""S quantifier."""
return quantifier_selector(num, quantifier, f'{quantifier}s') | 4453fdfb68a6affe6a1f05089b193264d3ae93ba | 48,655 |
def get_monitor_info_a(h_monitor):
"""
BOOL GetMonitorInfoA(
HMONITOR hMonitor,
LPMONITORINFO lpmi
);
"""
return __get_monitor_info(WINDLL.user32.GetMonitorInfoA, h_monitor) | aadfb1f9fe679c6d3ad9facc47c804245f7ea37e | 48,656 |
def textdeskew(image):
"""
Function that calculates a the rotation angle for documents that are
already properly scanned. Using the angle, it tries to deskew. Useful in
cases where there is no difference between foreground and background, and
the document is properly scanned.
"""
gray = cv2.cvtColor(image, cv... | 95d59ec6aca39627bdefa10f174f8b6e97c2c47c | 48,657 |
def group_arguments(seq, group=254):
"""
group the list into lists of 254 items each.
This is due to argument restrictions in python.
http://docs.djangoproject.com/en/dev/topics/http/urls/#patterns
"""
return (seq[pos:pos + group] for pos in range(0, len(seq), group)) | 066ffdd6984fe74f62a1838856124c98a726b623 | 48,658 |
from typing import List
from typing import Union
from typing import Dict
def get_reduction_mask(inputs: List[Union[Chord, Key]], kwargs: Dict = None) -> List[bool]:
"""
Return a boolean mask that will remove repeated inputs when applied to the given inputs list
as inputs[mask].
Parameters
-------... | c20a1c190f49e73126a1dd23cbdee850cb162958 | 48,659 |
import traceback
def generate_requirement_image(
learn_guide_project,
): # pylint: disable=too-many-statements
"""Generate a single requirement image"""
def make_line(
requirement_name, position=(0, 0), icon=None, hidden=False, triangle_icon=None
): # pylint: disable=too-many-branches
... | 92bc23d0baebf55be60b4e34b21535f1b8c9e905 | 48,660 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.