content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def sweep_gateDelay(qubit, sweepPts):
"""
Sweep the gate delay associated with a qubit channel using a simple Id, Id,
X90, X90 seqeuence.
Parameters
---------
qubit : Channels.LogicalChannel
Qubit channel for which to create sequences
sweepPts : int/float iterable
Iterable t... | 20,300 |
def execute(args):
"""Run the server."""
os.environ['LOCAL_DEVELOPMENT'] = 'True'
common.kill_leftover_emulators()
if not args.skip_install_deps:
common.install_dependencies()
# Do this everytime as a past deployment might have changed these.
appengine.symlink_dirs()
# Deploy all yaml files from te... | 20,301 |
def add(n):
"""Add 1."""
return n + 1 | 20,302 |
def get_system_status(memory_total=False,
memory_total_actual=False,
memory_total_usage=False,
memory_total_free=False,
all_pids=False,
swap_memory=False,
pid=False):
"""
Parameters
... | 20,303 |
def _area(x1, y1, x2, y2, x3, y3):
"""Heron's formula."""
a = np.sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2))
b = np.sqrt(pow(x3 - x2, 2) + pow(y3 - y2, 2))
c = np.sqrt(pow(x1 - x3, 2) + pow(y3 - y1, 2))
s = (a + b + c) / 2
return np.sqrt(s * (s - a) * (s - b) * (s - c)) | 20,304 |
def set_link_color(color='black', p_id=None, na_id=None):
"""
Set link's color in project(s) or join.
:param color: 'black' / 'red',
:param p_id: <Project.p_id>, optional
:param na_id: '<NetworkApplication.na_id>, optional
:type color: str
:type p_id: int
:type na_id: int
"""
se... | 20,305 |
def test_ljmc_imported():
"""Sample test, will always pass so long as import statement worked"""
assert "ljmc" in sys.modules | 20,306 |
def plot_coarray(array, ax=None, show_location_errors=False):
"""Visualizes the difference coarray of the input array.
Args:
array (~doatools.model.arrays.ArrayDesign): A sensor array.
ax (~matplotlib.axes.Axes): Matplotlib axes used for the plot. If not
specified, a new figure will... | 20,307 |
def get_publicKey(usrID): # TODO: from barbican
"""
Get the user's public key
Returns:
Public key from meta-container (Keys) in meta-tenant
"""
auth = v3.Password(auth_url=AUTH_URL,username=SWIFT_USER,password=SWIFT_PASS,project_name='demo',project_domain_id="Default",user_domain_na... | 20,308 |
def pad_sequence(sequences, batch_first=False, padding_value=0.0):
"""Pad a list of variable-length Variables.
This method stacks a list of variable-length :obj:`nnabla.Variable` s with the padding_value.
:math:`T_i` is the length of the :math:`i`-th Variable in the sequences.
:math:`B` is the batch s... | 20,309 |
def _fetch_global_config(config_url, github_release_url, gh_token):
"""
Fetch the index_runner_spec configuration file from the Github release
using either the direct URL to the file or by querying the repo's release
info using the GITHUB API.
"""
if config_url:
print('Fetching config fr... | 20,310 |
def parse_color(c, desc):
"""Check that a given value is a color."""
return c | 20,311 |
def get_package_dir():
"""
Gets directory where package is installed
:return:
"""
return os.path.dirname(ndextcgaloader.__file__) | 20,312 |
def __virtual__():
"""Only load gnocchiv1 if requirements are available."""
if REQUIREMENTS_MET:
return 'gnocchiv1'
else:
return False, ("The gnocchiv1 execution module cannot be loaded: "
"os_client_config or keystoneauth are unavailable.") | 20,313 |
def test_unconcretized_install(install_mockery, mock_fetch, mock_packages):
"""Test attempts to perform install phases with unconcretized spec."""
spec = Spec('trivial-install-test-package')
with pytest.raises(ValueError, match='must have a concrete spec'):
spec.package.do_install()
with pytes... | 20,314 |
def setup():
"""Start headless Chrome in docker container."""
options = webdriver.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=options)
driver.implicitly_wait(5)
return driv... | 20,315 |
def lambdaResponse(statusCode,
body,
headers={},
isBase64Encoded=False):
"""
A utility to wrap the lambda function call returns with the right status code,
body, and switches.
"""
# Make sure the body is a json object
if not isinstance(bo... | 20,316 |
def singleton(class_):
"""
Specify that a class is a singleton
:param class_:
:return:
"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance | 20,317 |
def is_datetime(
value: Scalar, formats: Optional[Union[str, List[str]]] = None,
typecast: Optional[bool] = True
) -> bool:
"""Test if a given string value can be converted into a datetime object for
a given data format. The function accepts a single date format or a list of
formates. If no format i... | 20,318 |
def sortkey(d):
"""Split d on "_", reverse and return as a tuple."""
parts=d.split("_")
parts.reverse()
return tuple(parts) | 20,319 |
def main():
"""Program entry point."""
args = parse_args()
if args.verbose is None:
logging.basicConfig(level=logging.WARNING)
elif args.verbose == 1:
logging.basicConfig(level=logging.INFO)
elif args.verbose >= 2:
logging.basicConfig(level=logging.DEBUG)
host_tag = get... | 20,320 |
def resolve_stream_name(streams, stream_name):
"""Returns the real stream name of a synonym."""
if stream_name in STREAM_SYNONYMS and stream_name in streams:
for name, stream in streams.items():
if stream is streams[stream_name] and name not in STREAM_SYNONYMS:
return name
... | 20,321 |
def get_split_cifar100_tasks(num_tasks, batch_size,run,paradigm,dataset):
"""
Returns data loaders for all tasks of split CIFAR-100
:param num_tasks:
:param batch_size:
:return:
datasets = {}
# convention: tasks starts from 1 not 0 !
# task_id = 1 (i.e., first task) => start_class = 0, end_class = 4
cifar_... | 20,322 |
def is_point_in_triangle(pt, v1, v2, v3):
"""Returns True if the 2D point pt is within the triangle defined by v1-3.
https://www.gamedev.net/forums/topic/295943-is-this-a-better-point-in-triangle-test-2d/
"""
b1 = sign(pt, v1, v2) < 0.0
b2 = sign(pt, v2, v3) < 0.0
b3 = sign(pt, v3, v1) < 0.0
... | 20,323 |
def precomputed_aug_experiment(
clf,
auged_featurized_x_train,
auged_featurized_y_train,
auged_featurized_x_train_to_source_idxs,
auged_featurized_x_test,
auged_featurized_y_test,
auged_featurized_x_test_to_source_idxs,
aug_iter,
train_idxs_scores,... | 20,324 |
def get_yahoo_data(symbol, start_date, end_date):
"""Returns pricing data for a YAHOO stock symbol.
Parameters
----------
symbol : str
Symbol of the stock in the Yahoo. You can refer to this link:
https://www.nasdaq.com/market-activity/stocks/screener?exchange=nasdaq.
start_date : s... | 20,325 |
def first_n(m: dict, n: int):
"""Return first n items of dict"""
return {k: m[k] for k in list(m.keys())[:n]} | 20,326 |
def listdictnp_combine(
lst: List,
method: str = "concatenate",
axis: int = 0,
keep_nested: bool = False,
allow_error: bool = False,
) -> Dict[str, Union[np.ndarray, List]]:
"""Concatenate or stack a list of dictionaries contains numpys along with error handling
Parameters
----------
... | 20,327 |
def main():
"""Main routine"""
setup (
name = "cmssh",
version = "%s.%s" % (cmssh.__version__, cmssh.__revision__),
description = "An interactive, programmable environment and shell for CMS",
package_dir = {'cmssh':'src/cmssh'},
data_files = [('config',['src/config/cmssh_... | 20,328 |
def pytest_configure(config):
"""Configure Pytest with Astropy.
Parameters
----------
config : pytest configuration
"""
if ASTROPY_HEADER:
config.option.astropy_header = True
# Customize the following lines to add/remove entries from the list of
# packages for which v... | 20,329 |
def find_pure_symbol(symbols, clauses):
"""Find a symbol and its value if it appears only as a positive literal
(or only as a negative) in clauses.
>>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A])
(A, True)
"""
for s in symbols:
found_pos, found_neg = False, False
for c in claus... | 20,330 |
def update_field(states, js, beta, loops):
"""
Update loops random selected states in the Ising model. Performance boost using jit-numba with parallelization of
the operations done by one loop.
:param states: np.2darray = Field containing the ising model states
:param js: np.3darray = 3d Array with ... | 20,331 |
def cross_entropy_emphasized_loss(labels,
predictions,
corrupted_inds,
axis=0,
alpha=0.3,
beta=0.7,
regularizer=None... | 20,332 |
def print_array_info(ar):
"""
Print array shape and other basic information.
"""
ar = nm.asanyarray(ar)
print(ar.shape, 'c_contiguous:', ar.flags.c_contiguous, \
'f_contiguous:', ar.flags.f_contiguous)
print('min:', ar.min(), 'mean:', ar.mean(), 'max:', ar.max()) | 20,333 |
def get_process_list(node: Node):
"""Analyse the process description and return the Actinia process chain and the name of the processing result
:param node: The process node
:return: (output_objects, actinia_process_list)
"""
input_objects, process_list = check_node_parents(node=node)
output_o... | 20,334 |
def _validate_image_formation(the_sicd):
"""
Validate the image formation.
Parameters
----------
the_sicd : sarpy.io.complex.sicd_elements.SICD.SICDType
Returns
-------
bool
"""
if the_sicd.ImageFormation is None:
the_sicd.log_validity_error(
'ImageFormatio... | 20,335 |
def handle_closet(player, level, reward_list):
"""
Handle a closet
:param player: The player object for the player
:param level: The level that the player is on
:return reward: The reward given to the player
"""
# Print the dialogue for the closet
print "You found a closet. It appears t... | 20,336 |
def module_path_to_test_path(module):
"""Convert a module locator to a proper test filename.
"""
return "test_%s.py" % module_path_to_name(module) | 20,337 |
def inspect_bom(filename):
"""Inspect file for bom."""
encoding = None
try:
with open(filename, "rb") as f:
encoding = has_bom(f.read(4))
except Exception: # pragma: no cover
# print(traceback.format_exc())
pass
return encoding | 20,338 |
def parse_requirement(text):
"""
Parse a requirement such as 'foo>=1.0'.
Returns a (name, specifier) named tuple.
"""
from packaging.specifiers import SpecifierSet
match = REQUIREMENT_RE.match(text)
if not match:
raise ValueError("Invalid requirement: %s" % text)
name = match.g... | 20,339 |
def H_split(k, N, eps):
"""Entropy of the split in binary search including overlap, specified by
eps"""
return (k / N) * (np.log(k) + H_epsilon(k, eps)) + ((N - k) / N) * (np.log(N - k) + H_epsilon(N - k, eps)) | 20,340 |
def date_features(inputs, features_slice, columns_index) -> tf.Tensor:
"""Return an input and output date tensors from the features tensor."""
date = features(inputs, features_slice, columns_index)
date = tf.cast(date, tf.int32)
date = tf.strings.as_string(date)
return tf.strings.reduce_join(date, ... | 20,341 |
def save_calib(filename, calib_params):
""" Saves calibration parameters as '.pkl' file.
Parameters
----------
filename : str
Path to save file, must be '.pkl' extension
calib_params : dict
Calibration parameters to save
Returns
-------
saved : bool
Saved successfully.
"""
if type(calib_par... | 20,342 |
def createWrap(cbName, line):
"""在Python封装段代码中进行处理"""
# 生成.h文件中的on部分
#if 'OnRspError' in cbName:
#on_line = 'virtual void on' + cbName[2:] + '(dict error, int id, bool last)\n'
#override_line = '("on' + cbName[2:] + '")(error, id, last);\n'
#elif 'OnRsp' in cbName:
#on_line ... | 20,343 |
def context_to_dict(context):
"""convert a django context to a dict"""
the_dict = {}
for elt in context:
the_dict.update(dict(elt))
return the_dict | 20,344 |
def returnItemsWithMinSupport(itemSet, transactionList, minSupport, freqSet):
"""calculates the support for items in the itemSet and returns a subset
of the itemSet each of whose elements satisfies the minimum support"""
_itemSet = set()
localSet = defaultdict(int)
for item in it... | 20,345 |
def create_P(P_δ, P_ζ, P_ι):
"""
Combine `P_δ`, `P_ζ` and `P_ι` into a single matrix.
Parameters
----------
P_δ : ndarray(float, ndim=1)
Probability distribution over the values of δ.
P_ζ : ndarray(float, ndim=2)
Markov transition matrix for ζ.
P_ι : ndarray(float, ndim=1)... | 20,346 |
def sel_nearest(
dset,
lons,
lats,
tolerance=2.0,
unique=False,
exact=False,
dset_lons=None,
dset_lats=None,
):
"""Select sites from nearest distance.
Args:
dset (Dataset): Stations SpecDataset to select from.
lons (array): Longitude of sites to interpolate spect... | 20,347 |
def evaluate(dataset, predictions, gts, output_folder):
"""evaluate dataset using different methods based on dataset type.
Args:
dataset: Dataset object
predictions(dict): each item in the list represents the
prediction results for one image.
gt(dict): Ground truth for each b... | 20,348 |
def html_xml_save(
s=None, possible_sc_link=None, table="htmlxml", course_presentation=None
):
"""Save the HTML and XML for a VLE page page."""
if not possible_sc_link:
# should really raise error here
print("need a link")
if not s:
if "learn2.open.ac.uk" in possible_sc_link:
... | 20,349 |
def app(request):
"""An instance of the Flask app that points at a test database.
If the TEST_DATABASE environment variable is set to "postgres", launch a temporary PostgreSQL
server that gets torn down at the end of the test run.
"""
database = os.environ.get('TEST_DATABASE', 'sqlite')
if data... | 20,350 |
def htmr(t,axis="z"):
"""
Calculate the homogeneous transformation matrix of a rotation
respect to x,y or z axis.
"""
from sympy import sin,cos,tan
if axis in ("z","Z",3):
M = Matrix([[cos(t),-sin(t),0,0],
[sin(t),cos(t),0,0],
[0,0,1,0],
... | 20,351 |
def vt(n, gm, gsd, dmin=None, dmax=10.):
"""Evaluate the total volume of the particles between two diameters.
The CDF of the lognormal distribution is calculated using equation 8.12
from Seinfeld and Pandis.
Mathematically, it is represented as:
.. math::
V_t=\\frac{π}{6}∫_{-∞}^{∞}D_p^3n... | 20,352 |
def core_value_encode(origin):
"""
转换utf-8编码为社会主义核心价值观编码
:param origin:
:return:
"""
hex_str = str2hex(origin)
twelve = hex2twelve(hex_str)
core_value_iter = twelve_2_core_value(twelve)
return ''.join(core_value_iter) | 20,353 |
def generate_params_file(output_path, args) -> None:
""" Generates parameter files. """
with open(output_path.joinpath(f'params-{time.strftime("%Y_%m_%d_%H%M%S", time.localtime(time.time()))}.txt'), 'w', encoding='UTF-8') as params_file:
output_vars = [
f'input={args.fasta_file_path.resolve(... | 20,354 |
def user_query_ahjs_is_ahj_official_of(self, request, queryset):
"""
Admin action for the User model. Redirects the admin to
a change list of AHJs the selected users are AHJ officials of.
"""
model_name = 'ahj'
field_key_pairs = [field_key_pair('AHJPK', 'AHJPK')]
queryset = AHJUserMaintains.... | 20,355 |
def open_gui(root_path: str):
"""The main function. This opens the DataLight GUI.
:param root_path: The path to the root of the RoboTA project
metadata descriptions.
"""
app = QtWidgets.QApplication(sys.argv)
datalight_ui = DatalightUIWindow(root_path)
datalight_ui.ui_setup()
datalight_u... | 20,356 |
def get_cache_node_count(
cluster_id: str, configuration: Configuration = None, secrets: Secrets = None
) -> int:
"""Returns the number of cache nodes associated to the cluster
:param cluster_id: str: the name of the cache cluster
:param configuration: Configuration
:param secrets: Secrets
:ex... | 20,357 |
def top_sentences(query, sentences, idfs, n):
"""
Given a `query` (a set of words), `sentences` (a dictionary mapping
sentences to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the `n` top sentences that match
the query, ranked according to idf... | 20,358 |
def print_defence_history(n:int, history:HistoryRecords, result:bool):
"""
print history.
"""
format_str = "[{0}] .... {1} ({2}, {3})"
print("\n===== challenge history ======")
for i in range(len(history.challenge)):
print(format_str.format(i + 1, history.challenge[i], history.response[... | 20,359 |
def load_distribution(label):
"""Load sample distributions as described by Seinfeld+Pandis Table 8.3.
There are currently 7 options including: Urban, Marine, Rural, Remote
continental, Free troposphere, Polar, and Desert.
Parameters
----------
label : {'Urban' | 'Marine' | 'Rural' | 'Remote C... | 20,360 |
def split_4d_itk(img_itk: sitk.Image) -> List[sitk.Image]:
"""
Helper function to split 4d itk images into multiple 3 images
Args:
img_itk: 4D input image
Returns:
List[sitk.Image]: 3d output images
"""
img_npy = sitk.GetArrayFromImage(img_itk)
spacing = img_itk.GetSpacing(... | 20,361 |
def parse_results(html, keyword):
"""[summary]
Arguments:
html {str} -- google search engine html response
keyword {str} -- search term
Returns:
pandas.DataFrame -- Dataframe with the following columns ['keyword', 'rank', 'title', 'link', 'domain']
"""
soup = BeautifulSoup(... | 20,362 |
def maybe_iter_configs_with_path(x, with_params=False):
"""
Like x.maybe_iter_configs_with_path(), but returns [(x, [{}])] or [(x, {}, [{}])] if x is just a config object and not a Tuner object.
"""
if is_tuner(x):
return x.iter_configs_with_path(with_params=with_params)
else:
if wi... | 20,363 |
def median(vals: typing.List[float]) -> float:
"""Calculate median value of `vals`
Arguments:
vals {typing.List[float]} -- list of values
Returns:
float -- median value
"""
index = int(len(vals) / 2) - 1
return sorted(vals)[index] | 20,364 |
def melody_mapper(notes):
"""
Makes a map of a melody to be played
each item in the list 'notes' should be formatted using these chars:
duration - length in seconds the sound will be played
note - the note to play
sleep - time in seconds to pause
(note, duration)
... | 20,365 |
def sample_bounding_box_scale_balanced_black(landmarks):
"""
Samples a bounding box for cropping so that the distribution of scales in the training data is uniform.
"""
bb_min = 0.9
bb_old = image.get_bounding_box(landmarks)
bb_old_shape = np.array((bb_old[2] - bb_old[0], bb_old[3] - bb_old[1])... | 20,366 |
def get_files(data_path):
"""
获取目录下以及子目录下的图片
:param data_path:
:return:
"""
files = []
exts = ['jpg', 'png', 'jpeg', 'JPG','bmp']
for ext in exts:
# glob.glob 得到所有文件名
# 一层 2层子目录都取出来
files.extend(glob.glob(os.path.join(data_path, '*.{}'.format(ext))))
files... | 20,367 |
def get_trainable_layers(layers):
"""Returns a list of layers that have weights."""
layers = []
# Loop through all layers
for l in layers:
# If layer is a wrapper, find inner trainable layer
l = find_trainable_layer(l)
# Include layer if it has weights
if l.get_weights():... | 20,368 |
def outcome_from_application_return_code(return_code: int) -> outcome.Outcome:
"""Create either an :class:`outcome.Value` in the case of a 0 `return_code` or an
:class:`outcome.Error` with a :class:`ReturnCodeError` otherwise.
Args:
return_code: The return code to be processed.
Returns:
... | 20,369 |
def group_by_scale(labels):
""" Utility that groups attribute labels by time scale """
groups = defaultdict(list)
# Extract scales from labels (assumes that the scale is given by the last numeral in a label)
for s in labels:
m = re.findall("\d+", s)
if m:
groups[m[-1]].append... | 20,370 |
def FontMapper_GetEncodingDescription(*args, **kwargs):
"""FontMapper_GetEncodingDescription(int encoding) -> String"""
return _gdi_.FontMapper_GetEncodingDescription(*args, **kwargs) | 20,371 |
def create_merged_ngram_dictionaries(indices, n):
"""Generate a single dictionary for the full batch.
Args:
indices: List of lists of indices.
n: Degree of n-grams.
Returns:
Dictionary of hashed(n-gram tuples) to counts in the batch of indices.
"""
ngram_dicts = []
for ind in indices:
n... | 20,372 |
def set_cipher(shared_key, nonce, key_name, hint):
"""Set shared key to the encryptor and decryptor
Encryptor and Decryptor are created for each inter-node connection
"""
global encryptors, decryptors
cipher = Cipher(algorithms.AES(bytes(shared_key)), modes.CTR(nonce), backend=default_backend())
... | 20,373 |
def compute_hash_base64(*fields):
"""bytes -> base64 string"""
value = compute_hash(*fields)
return base64.b64encode(value).decode() | 20,374 |
def triplet_margin_loss(
anchor,
positive,
negative,
margin=0.1,
p=2,
use_cosine=False,
swap=False,
eps=1e-6,
scope='',
reduction=tf.losses.Reduction.SUM
):
"""
Computes the triplet margin loss
Args:
anchor: The tensor containing the anchor embeddings
... | 20,375 |
def f_raw(x, a, b):
"""
The raw function call, performs no checks on valid parameters..
:return:
"""
return a * x + b | 20,376 |
def compute_barycentric_weights_1d(samples, interval_length=None,
return_sequence=False,
normalize_weights=False):
"""
Return barycentric weights for a sequence of samples. e.g. of sequence
x0,x1,x2 where order represents the order in whi... | 20,377 |
def _generate_conversions():
"""
Generate conversions for unit systems.
"""
# conversions to inches
to_inch = {'microinches': 1.0 / 1000.0,
'mils': 1.0 / 1000.0,
'inches': 1.00,
'feet': 12.0,
'yards': 36.0,
'miles': 63360,
... | 20,378 |
def sleep(seconds, check=True):
"""
Sleep the specified seconds checking for abort button periodically
:param seconds: float
:param check: bool, check for abort
"""
if check:
end_time = time.time() + seconds
while time.time() < end_time:
time.sleep(.1)
ch... | 20,379 |
def _ifail(repo, mynode, orig, fcd, fco, fca, toolconf):
"""
Rather than attempting to merge files that were modified on both
branches, it marks them as unresolved. The resolve command must be
used to resolve these conflicts."""
return 1 | 20,380 |
def parser(
text: str,
*,
field: str,
pattern: Pattern[str],
type_converter: Optional[Callable] = None,
clean_up: Optional[Callable] = None,
limit_size: Optional[int] = None,
null_value: Optional[Union[str, int, bool, None]] = None,
) -> str:
"""
Returns text based on regex patte... | 20,381 |
def func4():
"""
Let’s convert the item from RGB to grayscale, using the service we created:
""" | 20,382 |
def checkpoint_metrics_path(checkpoint_path, eval_name, file_name=None):
"""Gets a path to the JSON of eval metrics for checkpoint in eval_name."""
checkpoint_dir = os.path.dirname(checkpoint_path)
checkpoint_name = os.path.basename(checkpoint_path)
if eval_name:
# This bit of magic is defined by the estima... | 20,383 |
def colorize(text='', opts=(), **kwargs):
"""
Return your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Return the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', ... | 20,384 |
def get_prediction(img_path, threshold):
"""
get_prediction
parameters:
- img_path - path of the input image
- threshold - threshold value for prediction score
method:
- Image is obtained from the image path
- the image is converted to image tensor using PyTor... | 20,385 |
def display_img(result):
""" Display images fetched from any subreddit in your terminal.
Args:
result([list]): A list of urls which you want to display.
"""
lst = []
while True:
url = random.choice(result)
if url not in lst:
subprocess.call("w3m -o ext_image_vie... | 20,386 |
def make_fixed_size(protein, shape_schema, msa_cluster_size, extra_msa_size,
num_res, num_templates=0):
"""Guess at the MSA and sequence dimensions to make fixed size."""
pad_size_map = {
NUM_RES: num_res,
NUM_MSA_SEQ: msa_cluster_size,
NUM_EXTRA_SEQ: extra_msa_size,... | 20,387 |
def plot_skymap_tract(skyMap, tract=0, title=None, ax=None):
"""
Plot a tract from a skyMap.
Parameters
----------
skyMap: lsst.skyMap.SkyMap
The SkyMap object containing the tract and patch information.
tract: int [0]
The tract id of the desired tract to plot.
title: st... | 20,388 |
def label(vertex):
""" Graph vertex label in dot format """
label = f"{vertex.name} {vertex.state or ''}\n{vertex.traceback or ''}"
label = json.dumps(label).replace("\\n", r"\l")
return f"[label={label}]" | 20,389 |
def compute_hashes_from_fileobj(fileobj, chunk_size=1024 * 1024):
"""Compute the linear and tree hash from a fileobj.
This function will compute the linear/tree hash of a fileobj
in a single pass through the fileobj.
:param fileobj: A file like object.
:param chunk_size: The size of the c... | 20,390 |
def imshow(axim, img, amp_range=None, extent=None,\
interpolation='nearest', aspect='auto', origin='upper',\
orientation='horizontal', cmap='jet') :
"""
extent - list of four image physical limits for labeling,
cmap: 'gray_r'
#axim.cla()
"""
imsh = axim.imshow(img, interpol... | 20,391 |
def test_get_aws_client(mock_get_aws_client) -> None:
"""
Test that a baseclient is returned
"""
assert get_aws_client() | 20,392 |
def test_duration_min_inclusive001_1114_duration_min_inclusive001_1114_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=minInclusive and value=P1Y1MT1H
and document value=P1Y1MT1H
"""
assert_bindings(
schema="msData/datatypes/Facets/duration/duration_minInclusi... | 20,393 |
def get_total():
"""
Return the rounded total as properly rounded string.
Credits:
https://github.com/dbrgn/coverage-badge
"""
cov = coverage.Coverage()
cov.load()
total = cov.report(file=Devnull())
class Precision(coverage.results.Numbers):
"""
A class for usin... | 20,394 |
def _infer_subscript_list(context, index):
"""
Handles slices in subscript nodes.
"""
if index == ':':
# Like array[:]
return ValueSet([iterable.Slice(context, None, None, None)])
elif index.type == 'subscript' and not index.children[0] == '.':
# subscript basically implies ... | 20,395 |
def count_by_guess(dictionary, correctly=False):
"""
Count the number of correctly/incorrectly guessed images for a dataset
:param dictionary:
:param correctly:
:return:
"""
guessed = 0
for response in dictionary:
guessed = guessed + count_by_guess_user(response, correctly)
... | 20,396 |
def get_game_by_index(statscursor, table, index):
""" Holds get_game_by_index db related data """
query = "SELECT * FROM " + table + " WHERE num=:num"
statscursor.execute(query, {'num': index})
return statscursor.fetchone() | 20,397 |
def create_queue():
"""Creates the SQS queue and returns the queue url and metadata"""
conn = boto3.client('sqs', region_name=CONFIG['region'])
queue_metadata = conn.create_queue(QueueName=QUEUE_NAME, Attributes={'VisibilityTimeout':'3600'})
if 'queue_tags' in CONFIG:
conn.tag_queue(QueueUrl=qu... | 20,398 |
def db_describe(table, **args):
"""Return the list of columns for a database table
(interface to `db.describe -c`). Example:
>>> run_command('g.copy', vector='firestations,myfirestations')
0
>>> db_describe('myfirestations') # doctest: +ELLIPSIS
{'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... | 20,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.