content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import socket
def stop_daos_agent_services(test_file, args):
"""Stop any daos_agent.service running on the hosts running servers.
Args:
test_file (str): the test python file
args (argparse.Namespace): command line arguments for this program
Returns:
int: status code: 0 = success,... | bffba0dfe3e838e22453d059cfa5fadc767c935b | 64,000 |
import os
def get_gremlin_endpoint():
"""Returns the gremlin endpoint from the environment."""
gremlin_endpoint = os.getenv('GREMLIN_ENDPOINT', '')
if gremlin_endpoint == '':
raise EnvVarNotSetError('GREMLIN_ENDPOINT')
return gremlin_endpoint | cbdf87de713e577d48b05d6c2830d9300206472f | 64,001 |
import argparse
import os
import glob
def main(argv=None):
"""
This is the main function that is called when you run 'finialize.py'.
Here, you will load the configuration settings specified in the toml configuration
file, initiate the class dataInterface, and set up some directories and other
important things... | c2f99e019fd4657676729eed0274b3f329b7545f | 64,002 |
def category(chr):
"""Retrieves the unicode category for a unicode character.
>>> categories.category('A')
'L'
>>> categories.category('τ')
'L'
>>> categories.category('-')
'Pd'
:param chr: A unicode character
:type chr: str
:return: The unicode category for a unicode character... | 912a4da9714268bbc3e2c04f80c7d630b01b4be7 | 64,003 |
def pearson(counts1, counts2, row_standardize=True, outfile=None):
"""Calculates a column standardized Pearson correlation matrix"""
if row_standardize:
counts1 = (counts1.T - np.mean(counts1, axis=1)).T
counts1 = (counts1.T / np.std(counts1, axis=1)).T
counts2 = (counts2.T - np.mean(cou... | d2330eddb75d5545ffc00da3f0340069bb9a2846 | 64,004 |
def direction_vector(a, b):
"""
Returns False in case of independence, or a direction vector if no
independence is proven
>>> [direction_vector(*slice_pair) for slice_pair in slice_pairs]
[False, False, False, False, False, False, ('*', '=')]
# Dependent, test direction vectors
>>> directi... | 36ef4ba3705a8cc94996793009e026cbbf01e539 | 64,005 |
def get_document_url(cls):
"""
Create qualified URL on which a document is accessible.
Basically copied from:
https://github.com/GrappleGQL/wagtail-grapple/blob/
569b05d73282bee41b6c0509d413638b1aa9b040/grapple/types/images.py#L19
"""
url = ''
if hasattr(cls, 'url'):
url = cls.... | 512553fb35e181275b84ebbe193811bae8027c26 | 64,006 |
import logging
def get_geo_cords(ip, config):
"""
Retrieve latitude and longitude of server which
has specific IP.
If an error occurs the result will look like: (None, None)
:param ip: str
:param config: dict
:return: (latitude: str, longitude: str): tuple
"""
token = config.get('I... | f755955e8afee99a80257996bb147a1379ce5273 | 64,007 |
def read(filename, ignore_data=False):
""" This is the simplest (and recommended) way for our code to read a
Siemens DICOM file.
It returns a tuple of (parameters, data). The parameters are a dict.
The data is in a Python list.
"""
# Since a DICOM file is params + data together, it's not so... | a8be6bb8c67552beae698220e665d0b515759d6b | 64,008 |
from . import PrefixUnit
import io
def generate_prefixonly_unit_summary(namespace):
"""
Generates table entries for units in a namespace that are just prefixes
without the base unit. Note that this is intended to be used *after*
`generate_unit_summary` and therefore does not include the table header.... | a6b0244f6e5026bc94076a2a31e21bfceb003bff | 64,009 |
def SingleStr2Num(ch):
"""
单个字符转成数字
Example:
F --> 15
"""
result = 0
if str(ch) == "0":
result = 0
elif str(ch) == "1":
result = 1
elif str(ch) == "2":
result = 2
elif str(ch) == "3":
result = 3
elif str(ch) == "4":
result = 4
elif... | 70d0e3bccc476410d235d8b37127dd122e59cac9 | 64,010 |
def parse_config_arg(arg):
""" Parse a KEY=VALUE command-line argument """
m = CONFIG_ARG_RE.match(arg)
if m is None:
return None, None
else:
return m.group(1), m.group(2) | 25c59e6ab797109467a4e7f3b12d422c10b7846f | 64,011 |
def handle_module_not_found_error(error_message: str) -> str:
"""Handling ModuleNoutFoundError is quite simple as most of well known packages
already have questions on ModuleNotFoundError solved at stackoverflow"""
message = error_message.replace("ModuleNotFoundError", EMPTY_STRING)
return url_for_erro... | ff9a69c0815dc78c83bb55e9ea09458de83c99b0 | 64,012 |
from typing import Tuple
def parents(population: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Evenly splits population
Args:
population (np.ndarray): the population to crossover. Shape is n_individuals x n_chromosomes.
Returns:
Tuple[np.ndarray, np.ndarray]: population split into... | 1eab8b74ae82160dd8fc3a1e261fb2d76f3b464a | 64,013 |
from typing import Callable
from typing import List
from typing import Dict
def remove_null_values(
f: Callable[..., List[Dict[str, object]]]
) -> Callable[..., List[Dict[str, object]]]:
"""Decorator to ensure that the list of rows has all nulls values removed."""
return lambda *args, **kwargs: [nonnull_r... | 83b78addb32621298324e29ce6db897d7e35ea89 | 64,014 |
def get_progress_rate(k, c_species, v_reactants):
"""Returns the progress rate for a reaction of the form: va*A+vb*B --> vc*C.
INPUTS
=======
k: float
Reaction rate coefficient
c_species: 1D list of floats
Concentration of all species
v_reactants: 1D list of floats
Stoi... | 6baaaa07fe0814dbc50516b29ba55087c4ec23fd | 64,015 |
def preserve_ratio(surface, node, width=None, height=None):
"""Manage the ratio preservation."""
if node.tag == 'marker':
width = width or size(surface, node.get('markerWidth', '3'), 'x')
height = height or size(surface, node.get('markerHeight', '3'), 'y')
_, _, viewbox = node_format(sur... | 8da2c5cd5f48e343207a8e826c811cb34039c2bd | 64,016 |
def progress_bar(perc, width = 30):
"""
Gets a progress bar for printing.
:param perc: The percent completed.
:param width: The entire width of the bar.
:return: The progress bar string.
"""
assert(width > 10)
width -= 3
prog = int(perc * width)
bar = "[" + "=" * prog + (">" if p... | 5e796310d8f58d0a4f3e07e357bcca417e0fb3a2 | 64,017 |
def username(email):
"""Keeps the username of an email address."""
return email and email.split('@', 1)[0] | ef1c52120ba59e62061691f5bbb4a0387f691fc5 | 64,018 |
def add_position_network_count_entries_for_one_friend(voter_id, friend_voter_we_vote_id,
google_civic_election_id=0, voter_we_vote_id=""):
"""
This is called when a voter adds a friend.
:param voter_id:
:param friend_voter_we_vote_id:
:param goog... | eea9a1133c5aafb68ba042d490383d8b9d623adf | 64,019 |
def gather_feat(feat, ind):
"""
feat=[b,h*w,c]
ind=[b,k]
expand to [b,k,3] and get from [b,h*w,c]
"""
dim = feat.size(2)
ind = ind.unsqueeze(2).expand(ind.size(0),ind.size(1),dim)
feat = feat.gather(1, ind)
return feat | 8404d20fa96b16e2209a2ab83223b9fbf2f73dd2 | 64,020 |
def scale_shape_identity(name=None, breaks=None, labels=None, limits=None, na_value=None, guide='none'):
"""
Use this scale when your data has already been scaled.
I.e. it already represents aesthetic values that ggplot2 can handle directly.
This will not produce a legend unless you also supply the brea... | ca9c2e981ff3b1d7ee3170356c08bca82c4918c3 | 64,021 |
from pathlib import Path
import shlex
import subprocess
def open_gui(hdl_viewer: str, sim_file: Path) -> bool:
"""Simulates the provided target"""
print(f"### Opening gui")
cmd = f"{hdl_viewer} {sim_file}"
print(f" -> {cmd}")
process = Popen(
shlex.split(cmd),
stdout=subprocess.DE... | ac0f438ef9d7ade562113645dde76a8ef2aac463 | 64,022 |
def optctp(_pct_param, Q, PDE, N, mtype, n_cells):
"""
Optimization function
Parameters
----------
_pct_param : TYPE
DESCRIPTION.
Q : iterable
Experimental photocounting statistics of a laser source.
PDE : float
PDE of the detector.
N : int
Size of poisso... | de18f2051cfeb2e9d9cdf8dffbba165971a711e3 | 64,023 |
import time
def get_blocks_within_volume(vol_ref, Vimgs, blksz_3d, stride_3d, n_larger, n_lower=0, seed=0,
shuffleP=False, metric_operator='sum', nregions=1, return_bvm=False):
"""
vol_ref - metric volume from which 'n_larger' high signal intensity and 'n_lower' random blo... | b5718953bf8e8d90092478fe770e3e963d9c2d47 | 64,024 |
import torch
def give_dataloaders(dataset, opt):
"""
Args:
dataset: string, name of dataset for which the dataloaders should be returned.
opt: argparse.Namespace, contains all training-specific parameters.
Returns:
dataloaders: dict of dataloaders for training, testing and eval... | 6459eefd4044e95c693e65d38d4568eb360bcbdc | 64,025 |
def matrix():
"""Compute the set of covers representing the problem."""
b = board()
covers = []
for name, shape in pentominos.items():
for rotation in rotations(shape):
for position in positions(rotation, 8, 8, b):
covers.append([name] + sorted(position))
return ... | 039496ab40b8123fe7754cce2169870e17424efc | 64,026 |
def get_driver():
"""
Instatiate a selenium Chrome webdriver, return it.
In: n/a
Out: selenium headless webdriver
"""
options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=options)
return driver | da824bee637e5cfb7f591f2975d7c82dbdbbf213 | 64,027 |
import json
def get_key(filepath, key, default=None):
"""
Opens the file and fetches the value at said key
:param str filepath: The path to the file
:param str key: The key to fetch
:param default: The value to return if no key is found
:return: The value at the key (or the default value)
... | 9f720f33373ceec9a9a1a4b46c0e9257d3a55787 | 64,028 |
def format_time(input_datetime):
""" Formats the datetime according to the FIX spec.
Args:
input: a datetime
Returns:
A string that can be sent in a FIX message.
"""
return input_datetime.strftime("%Y%m%d-%H:%M:%S") | 8ea7476d60e2f7fcd73ddedd43b886e4df5afdf6 | 64,029 |
from typing import List
from typing import Union
def normalize_offsets(offsets: List[Offset], min_offset_size: int = 0) -> List[Offset]:
"""
Normalize the provided list of offsets by merging or removing some of them
Takes care of priority included in the tag label (as `_1`)
:param offsets: original of... | 95ea5ea36033aa250e6a14747885071b4fee9d33 | 64,030 |
import dill
def general_pack(*args) -> bytes:
"""Converts all args into a bytes string. """
return dill.dumps(args) | 40ff3c6263294d9874a5129baff404d74824e56c | 64,031 |
def mDA(X, noise, eta):
"""
inputs:
X : d x n input (TRANSPOSE DE LA DATA-MATRICE HABITUELLE)
noise: corruption level
eta: regularization
outputs:
hx: d x n hidden representation
W: d x (d+1) mapping
"""
d, n = np.shape(X)
# adding bias
Xb ... | ab6742090a85464d4ffd31942865d505162181b6 | 64,032 |
def login_post():
"""
Process login requests once
:return: if the login is successful redirect to the main page
"""
email = request.form.get('email')
password = request.form.get('password')
format_error_attribute = check_user_format(email, password)
if format_error_attribute is not... | 88758ff11ac6c84a5c44631f5eadbe0a502d0e94 | 64,033 |
import requests
def update_vm(name, processors=None, memory=None):
"""Updates the VM settings"""
vm = get_vm_by_name(name)
# Get current values to avoid empty parameters
if processors is None or memory is None:
if processors is None:
print("[DEBUG] Inheriting processor spec")
... | 59fb9e87b91d301dcf58799b9b505d9a1eb89b87 | 64,034 |
def get_voxel_coords(vol_points, raydb, pitch):
"""
Get discrete voxel coordinates from continuous point sources (in microns).
"""
supersample_factor = raydb.supersample_factor
x_coords = np.linspace(0,raydb.nx,num=raydb.nx+1)
y_coords = np.linspace(0,raydb.ny,num=raydb.ny+1)
z_coords = np.... | f3fa02ddb4f0fbfbe4dfc6dec50ab850662fc300 | 64,035 |
def get_model(mdict, Tvals, i, logg, metal, vsini, alpha=None, mode='same'):
"""
Get the model with the requested parameters
Parameters:
===========
- mdict: 5x-nested dictionary, such as generated by MakeModelDicts
The model dictionary
- Tvals: List of floats
... | 7b12d29efa7005547744eb9ec60074a7eb49de15 | 64,036 |
import PIL
def seg_pil(img, classr, do_alpha=False):
""" convert numpy array into PIL Image object """
classr = np.array(classr)
classr = skimage.util.img_as_ubyte(classr)
if do_alpha is True:
alpha = (classr[:, :, 3] / 255)[:, :, None]
classr = classr[:, :, :3]
return PIL.Image.f... | 63838015a8ac872b6298a9b31f47551f41f62480 | 64,037 |
def getExtension(dirname):
"""get extension of a path"""
extension = dirname[:3]
return extension | 7f8b1c0d1509ca03be43c6fcd86876e8365f46a2 | 64,038 |
def autre_joueur(pikominos_joueur:list, pikominos_autre_joueurs:list, need_pikominos:int):
""" Fonction qui permet de prendre le pikominos d'un autre joueur
Fonction qui ajoute le pikominos au joueur
:param pikominos_joueur: liste des pikominos du joueur
:param pikominos_autre_joueurs: liste des pikominos des autre... | d99ce592db7f25fdc4fcbf1e52eb7ac7f408b05b | 64,039 |
def cnn_model(features, labels, mode):
"""
A 2 layer ConvNet to predict from sequence of words to a class.
Largely stolen from:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/text_classification_cnn.py
Returns a tf.estimator.EstimatorSpec.
"""
# Convert indexes of words int... | 47c446b9bc3cf18a46b438ff40c81c1a4c28a752 | 64,040 |
def AddWeigthTree(tree):
"""Add weigth to nodes of a tree (for branch with limit)"""
if 'splitVar' in tree:
if 'left' in tree:
wl = AddWeigthTree(tree['left'])
if 'right' in tree:
wr = AddWeigthTree(tree['right'])
tree['Weigth'] = wl + wr + 1
else:
tre... | 0729025ccbf17faf4055af5b4343e1d6b98c79a7 | 64,041 |
def estimate_length_phases_12(K=3, m=9, Delta=0.1, T=1000):
""" Estimate the length of phase 1 and 2 from the parameters of the problem.
Examples:
>>> estimate_length_phases_12(m=2, K=2, Delta=0.1, T=100)
198214307
>>> estimate_length_phases_12(m=2, K=2, Delta=0.01, T=100)
19821430723
>>> ... | 05fcb5cc56f13529bd5ed37ae3b4a81d701e08cf | 64,042 |
def random_gamma_with_runtime(
shape, concentration, rate=None, log_rate=None, seed=None, log_space=False):
"""Returns both a sample and the id of the implementation-selected runtime."""
# This method exists chiefly for testing purposes.
dtype = dtype_util.common_dtype([concentration, rate, log_rate], tf.floa... | b48158af9cb2c6e4781f6c6008492e1764ea44af | 64,043 |
def _parse_settings_vlan(opts, iface):
"""
Filters given options and outputs valid settings for a vlan
"""
vlan = {}
if "reorder_hdr" in opts:
if opts["reorder_hdr"] in _CONFIG_TRUE + _CONFIG_FALSE:
vlan.update({"reorder_hdr": opts["reorder_hdr"]})
else:
vali... | b9f7672e82a6c8680035f8cc17cc62e7d94fcece | 64,044 |
def VGGFace(include_top=True, model='vgg16', weights='vggface',
input_tensor=None, input_shape=None,
pooling=None,
classes=None):
"""Instantiates the VGGFace architectures.
Optionally loads weights pre-trained
on VGGFace datasets. Note that when using TensorFlow,
for ... | 59b8db024a0ad5f31e061b85571077c9385354c0 | 64,045 |
def prepare_storage_get_folder(classifier_name: str = None) -> str:
"""
Prepares a folder for the specified classifier and returns its path
:param classifier_name: The name of the classifier
:return: The path to the created classifier folder
"""
create_directory_if_not_exists(CLASSIFIERS_PATH)
... | 7b71f9b6b32acf039b3617244500e92f73a0b0ed | 64,046 |
def commonprefix(l):
"""Return the common prefix of a list of strings."""
if not l:
return ''
prefix = l[0]
for s in l[1:]:
for i, c in enumerate(prefix):
if c != s[i]:
prefix = s[:i]
break
return prefix | 235636c207c89a7128295fb5aa5b0cba732f50a1 | 64,047 |
from re import T
def ipv6_interface__gt__(self: T, other: T) -> bool:
"""Compare greater than on mixed IP interface object types."""
if isinstance(other, IPv4Interface):
return True
if isinstance(other, IPv6Interface):
return ipv6_interface__gt__.__gt__(self, other) # type: ignore
rai... | fdd39d8c9955ee0747fc07b4b82a925c87440777 | 64,048 |
from typing import List
async def languages(
config: str = "", encoding: str = AIOPYTESSERACT_DEFAULT_ENCODING
) -> List:
"""Tesseract available languages."""
proc = await execute_cmd(f"--list-langs {config}")
data = await proc.stdout.read()
languages = []
for line in data.decode(encoding).spl... | 5c911319a2d4716ac0aaae05de253dd83a0a50bd | 64,049 |
def create_train_state(
config, rng, learning_rate_fn,
example_batch):
"""Create and initialize the model.
Args:
config: Configuration for model.
rng: JAX PRNG Key.
learning_rate_fn: learning rate function
example_batch: for model intialization
Returns:
The initialized TrainState wit... | f6d939013f84a2672500978507af1c6e53b62850 | 64,050 |
def mock_profile(func):
"""
Mock decorator that is used when the PROFILER is not set
"""
def wrapper(*arg, **kwargs):
"""
Mock wrapper function
"""
return func(*arg, **kwargs)
return wrapper | 05b25c97f50a6dab4fe0c8d0eb39ee173bafdc01 | 64,051 |
import yaml
from pathlib import Path
import attrs
def _get_config(args: Namespace) -> Config:
"""Gets config from YAML."""
try:
with open(args.config) as file:
yaml_cfg = yaml.safe_load(file)
except FileNotFoundError:
raise SystemExit(
f"ERROR: config file at '{Path... | 09c512cc5edd83d4c7e603fd5df78cea9ec49bfc | 64,052 |
def get_piece_value(piece, i, j, piece_color):
"""Return absolute value of the pieces."""
eval_map = {
'p' : PAWN_EVAL,
'n' : KNIGHT_EVAL,
'b' : BISHOP_EVAL,
'r' : ROOK_EVAL,
'q' : QUEEN_EVAL,
'k' : KING_EVAL
}
eval_offset = {
'p' : 10,
'... | 861ab24bdb645f5b23dc5ca3c3915a1feebf89db | 64,053 |
import struct
def read_brt(filename, accept_localtime=False):
"""
Read BRT file holding the MWR brightness temperatures of starring obs
(fixed azimuth and elevation)
Parameters
----------
filename : str
path to .brt file holding the starring MWR brightness temp obs.
accept_localti... | 8e55b1bf4222d9a8996a7706dfd793b58522c455 | 64,054 |
import os
def get_connection() -> pymongo.mongo_client.MongoClient:
"""Get a connection to the DB
Other Parameters:
CONNECTION (pymongo.MongoClient): GLOBAL storing connection
BIFROST_DB_KEY: (ENV) This is a environmental variable taken from the system
Returns:
pymongo.mongo_clie... | c8c08dccf61d870bef20f01fb69fa7658cd25fce | 64,055 |
def shuffle_dataset(x, t):
"""データセットのシャッフルを行う
Parameters
----------
x : 訓練データ
t : 教師データ
Returns
-------
x, t : シャッフルを行った訓練データと教師データ
"""
permutation = np.random.permutation(x.shape[0]) #x.shape[0]=10 なら、0~9までの数をランダムに並べる。
x = x[permutation,:] if x.ndim == 2 else x[permutation... | ef4b36af06cf909d2953b699d28a4060805d879a | 64,056 |
from datetime import datetime
def trade():
"""Client to broker endpoint."""
# Pass the trade request to broker
req = request.json
agent_name = req.pop('name', 'nobody')
resp = broker.handle(req)
if resp['retcode'] == 0 and req['action'] in (2, 3):
# Record the new order
if req['action'] == 2:
... | b752c91545566ce98eaf6aa5638407322d60c358 | 64,057 |
from typing import List
def get_zones(cf: CloudFlare, zone_name: str) -> List[dict]:
""" grab the zone identifier"""
logger = get_logger("get_zones")
try:
return cf.zones.get(params={"name": zone_name})
except CloudFlareAPIError as err:
logger.error(
"bad authentication", m... | 5c54aec1941f3fba0e755be460e63bc4d85cc9a0 | 64,058 |
import fnmatch
def audit(data_list, tags, labels, debug=False, **kwargs):
"""
Run the sysctl audits contained in the YAML files processed by __virtual__
"""
__data__ = {}
for profile, data in data_list:
_merge_yaml(__data__, data, profile)
__data__ = apply_labels(__data__, labels)
... | 8e6a49d2228f36abdfbbe1f141eae03e381cea64 | 64,059 |
import os
def model_fn(model_dir):
"""Load the gluon model. Called once when hosting service starts.
:param: model_dir The directory where model files are stored.
:return: a model (in this case a Gluon network)
"""
net = gluon.SymbolBlock.imports(
symbol_file=os.path.join(model_dir, "mode... | 68e483b52936fab483d266f601e62f2afa38fdb4 | 64,060 |
def getgainfo(driver):
"""
funzione che ritorna la struttura ga.q, cioè la
coda dei comandi di google analytics come un dizionario
con più livelli o None se la struttura non è
definita
"""
return driver.execute_script(GETGAINFO) | 0e0d84e7b7bdd096579ab6baeb7cc0b60b093955 | 64,061 |
def get_qtypes(dataset_name, part):
"""Return list of question-types for a particular TriviaQA-CP dataset"""
if dataset_name not in {"location", "person"}:
raise ValueError("Unknown dataset %s" % dataset_name)
if part not in {"train", "dev", "test"}:
raise ValueError("Unknown part %s" % part)
is_biase... | 0aa1a186ebf4fcfe5820ecbb697d8cb166114310 | 64,062 |
def process_cost_effect(eff):
""" Check if the given effect is a cost effect. If it is, return the additive cost; if it is not, return None. """
if isinstance(eff, FunctionalEffect) and isinstance(eff.lhs, CompoundTerm) and eff.lhs.symbol.name == "total-cost":
if not isinstance(eff.condition, Tautology)... | 6f6c9842a0e920e954d3ffe7ace348a5b0049709 | 64,063 |
import yaml
from typing import OrderedDict
def yaml_ordered_load(
stream, loader_type=yaml.SafeLoader, object_pairs_hook=OrderedDict
):
"""Load YAML using an OrderedDict
This function is needed for reproducibility with Python 3.5,
which doesn't guarantee dict key ordering.
"""
class OrderedL... | 7ac46209d5c23f7ee46a2cd9803b979fc12aa989 | 64,064 |
def clear_dashboard(dashId):
"""
Clears all the set positions and sizes of the tables on the dashboard
"""
default_tables = {
"Counts": {
"sizex": 10,
"sizey": 13,
"row": 1,
... | 10c177d45e5462f252f61d0cf262dc762febb59d | 64,065 |
import re
def get_numbers_from_file(path, skip_lines=2):
"""
Function to read a file line-wise and extract numbers.
Parameters
----------
path: str
Path to the file including the filename.
skip_lines: int
Number of lines to skipp at the beginning of the file.
Returns
... | 64026a6c5cf9aa16076a3c8872663ab7996c1add | 64,066 |
def _get_bdf_model(bdf_filename, cards_to_skip=None, log=None, debug=False):
"""helper method"""
if isinstance(bdf_filename, BDF):
model = bdf_filename
else:
model = BDF(log=log, debug=debug)
model.disable_cards(cards_to_skip)
model.read_bdf(bdf_filename)
return model | 0701f9315f1f66e7908596a81026f5eeeb51b7c5 | 64,067 |
from datetime import datetime
def plotter(fdict):
""" Go """
pgconn = get_dbconn('asos')
ctx = get_autoplot_context(fdict, get_description())
station = ctx['zstation']
year = ctx['year']
month = ctx['month']
ptype = ctx['ptype']
# Extract the range of forecasts for each day for approx... | 55b1a69f1127e11ab67dd874389a5aeee5b22219 | 64,068 |
def by_mass(self):
"""Return a MassFlowIndexer that references this object's molar data."""
try:
mass = self._data_cache['mass']
except:
phases = self.phases
chemicals = self.chemicals
mol = self.data
mass = np.zeros_like(mol, dtype=object)
for i, phase in enu... | c668c1e556fc967e62c3d767cbd0094dd58ffe29 | 64,069 |
def fault_resolve_fault(cookie, in_id):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("FaultResolveFault")
method.cookie = cookie
method.in_id = str(in_id)
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
return xml_request | 1cd46f527a5eb9c3299a37edf3fd6501fd487269 | 64,070 |
def get_model(backbone, tasks, datasets, args, device):
"""
Returns FSL model and sorts out model_args
"""
print("Getting model: {}".format(args.model))
if args.model not in MODELS:
raise Exception("Model {} does not exist".format(args.model))
if 'seed' in args.model_args and a... | d3e8966df02892b2d3777fc107ee540e032357d0 | 64,071 |
def cpsd(a, b, nfft, fs, window='hann', step=None):
"""
Compute the cross power spectral density (CPSD) of the signals `a` and `b`.
Parameters
----------
a : |np.ndarray|
The first signal.
b : |np.ndarray|
The second signal.
nfft : int
The number of points in the fft.
... | 795185c65f74b57a44d4eefab87966150996fcd5 | 64,072 |
from datetime import datetime
import time
def daytemp(
city: str, appid: str = WEATHER_API_KEY, url: str = WEATHER_API_URL
) -> bool:
"""Check if the current temperature conforms to a daytime/nightime setting.
The expected ranges can be looked up in the settings file, and this function
only returns T... | 93372157c7e5f79c5b16cb3350f2f8a7c115dadd | 64,073 |
import requests
async def get_beacon_see_also(gnd: str):
"""
Get references in other data sources for a given GND number
"""
headers = {'Content-Type': 'application/json'}
url = 'https://beacon.findbuch.de/seealso/pnd-aks?format=seealso&id=' + gnd
findbuch_response = requests.get(url, headers... | 121f69b93bb255ca4f35403e2763f76a24702f61 | 64,074 |
import json
def generate_correct_manifest_line(
record_id, record_timestamp, topic_name, wrap_id=False
):
"""Returns the data that would be in a successful manifest for the given id.
Keyword arguments:
record_id -- the id of the record
record_timestamp -- the timestamp of the record
topic_nam... | bb7ca607f4b004ec2a1e86013a622e1b8a35fc71 | 64,075 |
import re
def _get_match_list(regex, key_alias, command_line, delimiter):
"""
:param regex: search for this pattern in command_line
:param key_alias: The key whose value is to be found out
:param command_line: command_line from where the value is to be fetched
:param delimiter: assignment operato... | 8d53cc4b53aaeaf44322a1ad75bd2e5ea3266959 | 64,076 |
import sys
import importlib
import json
def construct_app_args(args, conf, operations, func, default_profiles,
inst_conf, display_order=None):
"""
:param args: Command arguments, argparse instance
:param conf: Service configuration
:param operations: Operations module
:para... | b8b041ac77d0324b73c628fcc5b9385e3c9b215d | 64,077 |
def ParseUpdateOptionsBase(args, locations):
"""Helper function to build ClusterUpdateOptions object from args.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
locations: list of strings. Zones in which cluster has nodes.
Returns:
ClusterUp... | 48675a3fa9198e02ea6a4d7f54c92070a816b072 | 64,078 |
def derivative(da, grid, scale_factor, axis, position_fr="left", position_to="center"):
"""
Take the derivative of *da* as a finite difference
"""
# from W to T : 'fill', 0
# from T to W : 'fill', first value at T point
if (position_fr, position_to) == ("center", "left"):
# T to W point
... | f81640eeb1058053bbdb8c1b72b9e7243e3eaf70 | 64,079 |
import json
def storage_to_vc_record(record: StorageRecord) -> VCRecord:
"""Convert an Indy-SDK stored record into a VC record."""
cred_tags = {}
contexts = []
types = []
schema_ids = []
subject_ids = []
issuer_id = None
given_id = None
for tagname, tagval in (record.tags or {}).it... | 00ce064bcb2c35c5752e4cc7351a8a5a9015bf62 | 64,080 |
def _generate_open_blob(maze, num_points):
"""Try to generate an open connected blob of points in the maze.
Args:
maze: Instance of .maze.Maze.
num_points: Int. Number of connected points to have in the blob.
Returns:
blob_matrix: False or binary matrix of same size as maze. On... | 01cade95dbd211e27f149b71d0572e73a87232c6 | 64,081 |
def describe_list_indices(full_list):
"""
Describe the indices of the given list.
Parameters
----------
full_list : list
The list of items to order.
Returns
-------
unique_elements : list
A list of the unique elements of the list, in the order in which
they firs... | 664bcfd63dd0d5d5114ce24a4c7b2850b61364c5 | 64,082 |
def load_metadata_txt(file_path):
"""
Load distortion coefficients from a text file.
Parameters
----------
file_path : str
Path to a file.
Returns
-------
tuple of floats and list
Tuple of (xcenter, ycenter, list_fact).
"""
if ("\\" in file_path):
... | d1220c39fd9e69b76b1aa6f3e73cd9eef708c451 | 64,083 |
def compare_structures(cell_ref, cell_calc, symmetry_tolerance):
"""Compare two PhonopyAtoms instances."""
symprec = symmetry_tolerance.value
cell_diff = np.subtract(cell_ref.cell, cell_calc.cell)
if (np.abs(cell_diff) > symprec).any():
succeeded = Bool(False)
succeeded.label = "False"
... | 69805e1c6c27b12c2c3f56ff570d32a508e903d5 | 64,084 |
from typing import List
def get_client_parameters(func: dict, enums: dict) -> List[ClientParam]:
"""Create a list of ClientParam objects for the given function."""
inputs = [p for p in func["parameters"] if common_helpers.is_input_parameter(p)]
inputs = common_helpers.filter_parameters_for_grpc_fields(in... | dd182542f63e0d99adee344ed51927e7e52cb7b1 | 64,085 |
from typing import Iterable
import numbers
from typing import Optional
from typing import Any
from typing import Iterator
import collections
import itertools
def simple_ma(
window_size: int,
iterable: Iterable[numbers.Number],
*,
prepend: Optional[Any] = _NO_VALUE,
) -> Iterator[numbers.Number]:
"... | 11319afc732a401dee748aba29dc7bd5415c1a34 | 64,086 |
import types
def decodePayload(payload, tag, key=None, userKeys=(), retNym=None):
"""Given a 28K payload and a 20-byte decoding tag, attempt to decode the
original message. Returns either a SingletonPayload instance, a
FragmentPayload instance, or None.
key: an RSA key to decode encrypt... | 675c503de5a335da5c0b415686792c4473bb4a1c | 64,087 |
from typing import Tuple
def scaffold_split_one(data: MoleculeDataset) -> Tuple[MoleculeDataset,
MoleculeDataset,
MoleculeDataset]:
"""
Split a dataset by scaffold such that train has all molecules fr... | d36b32e1c3270b054706099d241bc3a9c2b75502 | 64,088 |
def _write_cubeface_evtk(model, file_name, data_label, nsteps, real_coords=True):
"""
Writes out the model as a cuboid with six rectangular surfaces
Parameters
----------
model : GeologicalModel object
Geological model to export
file_name : string
Name of file that model is expo... | e68c32ed76c87fe271fbe2e28a0db701359bc28a | 64,089 |
def _contour(darray, surjection=surjection, **kwargs):
""" Wrapper around DataArray.plot.contour """
return biject(darray, surjection=surjection).plot.contour(**kwargs) | 83e5999270d6d5341649c6a9f4bc241d195e8892 | 64,090 |
from typing import Dict
def is_valid_jwt_json(jwt_json: Dict) -> bool:
"""
Check your jwt dict.
Parameters
----------
jwt_json: Dict
your jwt dict.
Returns
-------
bool
True if jwt_json is valid , False else
"""
return (
HEADER in jwt_json
and ... | 005b8f039b3318e4135d311adacdd3aacf3c9b69 | 64,091 |
def has_fragment(data):
"""Return true if the node has a fragment.
:param dict data: A PyBEL data dictionary
:rtype: bool
"""
return _node_has_variant(data, FRAGMENT) | e993c516a632515b97b3505e8d7a8fe3334aaf2b | 64,092 |
import json
def dumps(mongo_doc, **kwargs):
"""json.dumps() for PillarSDK documents."""
return json.dumps(mongo_doc, cls=PillarJSONEncoder, **kwargs) | 582527250016ef6b13c3e3cc8f94e4459594d783 | 64,093 |
def get_jpg_out_extension():
"""get extension for output JGEG files
(should include the delimiter (.)"""
return __CONF['jpg_out_extension'] | fa07ce6912b16a8ddc73689e47fd3ab615a5499b | 64,094 |
def combine_expressions(
expressions,
relation='AND',
unique=True,
licensing=Licensing(),
):
"""
Return a combined LicenseExpression object with the `relation`, given a list
of license ``expressions`` strings or LicenseExpression objects. If
``unique`` is True remove duplicates before co... | 17f787550a176bd8b3d6d110c234ddb6f5d4c1c6 | 64,095 |
from typing import OrderedDict
def gen_top(service_uri, no_pages, num_mem, label=None):
"""
Generate the top level collection page.
:param service_uri: base uri for the AS paged site.
:param no_pages:
:param num_mem:
:param label:
:return: dict
"""
top = OrderedDict()
top['@co... | 14b330e0ad57b08462b3854eba2771e859344df2 | 64,096 |
def pinv(X, y):
"""
Calculate the optimal values of the parameters using the pseudoinverse
approach as you saw in class.
Input:
- X: Inputs (n features over m instances).
- y: True labels (1 value over m instances).
Returns two values:
- theta: The optimal parameters of your model.
... | 9b253ba4cb4c7ec3b4cd2dacb34ab2cbdb43404f | 64,097 |
def reverse_words(text):
"""
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces
in the string should be retained.
:param text: string of words.
:return: all words in the string reversed.
"""
return " ".join(x[::-1] for x in text.split(" ")... | 350b2e60cff7fb4fcfb6f71fd2459d1d5a5d4558 | 64,098 |
def u6():
"""Create a U6 test fixture."""
params = {
'concept_id': 'ensembl:ENSG00000278757',
'symbol': 'U6',
'label': 'U6 spliceosomal RNA',
'previous_symbols': [],
'aliases': [],
'xrefs': [],
'symbol_status': None,
'location_annotations': [],
... | 5643599e2efb7590e773c64127066d14c7e31d64 | 64,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.