content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def allpathsX(args):
"""
%prog allpathsX folder tag
Run assembly on a folder of paired reads and apply tag (PE-200, PE-500).
Allow multiple tags separated by comma, e.g. PE-350,TT-1050
"""
p = OptionParser(allpathsX.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sy... | 5,314,400 |
def copy_proto_go_source(target, source, env):
"""Copy go source file generated by protobuf into go standard directory. """
shutil.copy2(str(source[0]), str(target[0]))
return None | 5,314,401 |
def add_credentials(request):
"""
Create credentials for SolarWinds integration.
"""
action_url = reverse('add_credentials')
if request.method == 'POST':
form = SolarWindsConectionForm(request.POST)
if form.is_valid():
form.save()
msg = "The SolarWinds credent... | 5,314,402 |
def test_generated_names(heavy_atom_name, ref_hydrogen_names):
"""
Test correct generation of hydrogen names for atoms that are not in
the library, based on known examples.
"""
name_lib = hydride.AtomNameLibrary()
gen = name_lib.generate_hydrogen_names("", heavy_atom_name)
test_hydrogen_name... | 5,314,403 |
def add_recipe_to_config(env, db):
"""Add a column for storing the build recipe to the build configuration
table."""
cursor = db.cursor()
build_config_schema_v3 = Table('bitten_config', key='name')[
Column('name'), Column('path'), Column('active', type='int'),
Column('recipe'), ... | 5,314,404 |
def parsePifKey(pif, key):
"""Parse a single pif key for single scalar values; return nan if no scalar found.
:param pif: PIF to access
:type pif: pif
:param key: key to access data
:type key: string
:returns: scalar value or np.nan
:rtype:
"""
if (key in ReadView(pif).keys()):
... | 5,314,405 |
def check_multimetric_scoring(estimator, scoring):
"""Check the scoring parameter in cases when multiple metrics are allowed.
Parameters
----------
estimator : sklearn estimator instance
The estimator for which the scoring will be applied.
scoring : list, tuple or dict
A single str... | 5,314,406 |
def dummy_workflow():
"""Return dummy Snakemake workflow object"""
mock_workflow = MagicMock()
return mock_workflow | 5,314,407 |
def get_multi_lock_or_null_context(multi_lock_context, *args, **kwargs):
"""Return either a MultiLock or a NULL context
Parameters
----------
multi_lock_context: bool
If True return MultiLock context else return a NULL context that
doesn't do anything
*args, **kwargs:
Argum... | 5,314,408 |
def load_cme_scenarios():
"""
Load in the CME scenarios from their HDF5 file and return them in a dictionary.
"""
project_dirs = get_project_dirs()
datafile_path = os.path.join(project_dirs['out_data'], 'CME_scenarios.hdf5')
datafile = h5py.File(datafile_path, 'r')
cme_scenarios = {}
... | 5,314,409 |
async def ping(ctx):
"""Pong! (Latencey)"""
t = await client.say('Pong!')
ms = (t.timestamp-ctx.message.timestamp).total_seconds() * 1000
await client.edit_message(t, new_content='Pong! Took: {}ms'.format(int(ms))) | 5,314,410 |
def argument_decorator(f):
"""Decorates a function to create an annotation for adding parameters
to qualify another.
.. literalinclude:: /../examples/argdeco.py
:lines: 5-25
"""
return parser.use_mixin(
DecoratedArgumentParameter, kwargs={'decorator': f}) | 5,314,411 |
async def get_open_api_endpoint(api_key: APIKey = Depends(get_api_key)):
"""To check if my authorisation process was succesfull"""
return "Certification is accepted" | 5,314,412 |
def ReadMaleResp2015():
"""Reads respondent data from NSFG Cycle 9.
returns: DataFrame
"""
usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw',
'evrmarry', 'wgt2013_2015',
'marend01', 'rmarital', 'fmarno', 'mar1diss']
df = ReadResp('2013_2015_MaleSetup.dct... | 5,314,413 |
def dpush():
"""Push Docker image to Dockerhub. Requires `docker login`."""
print(yellow("Pushing docker images to DockerHub..."))
local("docker push dbcawa/tsc") | 5,314,414 |
def keyword_list(request):
"""
This is a view that will show all the keywords.
This view should also show the number of datasets for each keyword.
Maybe that is a template problem.
"""
k = Keyword.objects.all()
if "q" in request.GET:
q = request.GET["q"]
keyword_list = k.fil... | 5,314,415 |
def parse_date(datestr):
""" Parses an ISO 8601 formatted date from Gophish """
return dateutil.parser.parse(datestr) | 5,314,416 |
def block_resnet152(pretrained=False, progress=True, device='cpu', **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _block_resnet(... | 5,314,417 |
def encode_categorical_features(dataframe, categorical_features):
"""Encode categorical features and add to the column of the dataframe."""
transformations = []
# Ordinal encoding
ordinal_encoded_output_cols = ["ordinal_indexed_"+categorical_feature for categorical_feature in categorical_features]
indexer = Stri... | 5,314,418 |
def gen_nondeferred_mock(return_value=_sentinel, func_dict=None, spec=None, name='NDMock',
side_effect=_sentinel):
"""
Get a mock which cannot be mistaken for a Deferred
@param return_value : A return value, passed directly to the Mock constructor if set
@param func_dict: A dic... | 5,314,419 |
def npm_localfile(package, version):
"""Get the local filename of a npm package"""
return os.path.join("npm2", npm_filename(package, version)) | 5,314,420 |
def url2domain(url):
""" extract domain from url
"""
parsed_uri = urlparse.urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
domain = re.sub("^.+@", "", domain)
domain = re.sub(":.+$", "", domain)
return domain | 5,314,421 |
def rhythm_track(file_path: PathType) -> dict:
"""Perform rhythm track analysis of given audio file.
Args:
file_path: Path to audio file.
Returns:
Rhythm track parameters and data.
"""
snd = load_audio(file_path)
onsets = FluxOnsetDetector(snd.data, snd.fps)
segs = segment... | 5,314,422 |
def draw_circle(lbound, diameter, canvas, color, selected, tags=(), stroke_width=1):
"""Draw a circle element, given a lower bound and diameter."""
if selected:
outline = "#004500"
width = stroke_width * 3
else:
outline = "black"
width = stroke_width
bbox = (lbound[0], l... | 5,314,423 |
def setupLogging(
level: int = None, log_filename: str = None, log_to_console: bool = False
):
"""
Sets up the WranglerLogger w.r.t. the debug file location and if logging to console.
args:
level: the level of logging that will be recorded
log_filename: the location of the log file that... | 5,314,424 |
def patch_fuzzy_age(patch_meta: PatchMeta):
"""
Converts ages to one of the following
prenatal
90+ (years)
X0-X9 (years) - if above 0 aka prenatal and below 90
Important - works on the combined age field, if you have historic data with age_units
run patch_merge_age_units first
:param pa... | 5,314,425 |
def get_package_dbpath():
"""Return the default database path"""
return os.path.join(os.path.abspath(os.path.dirname(__file__)), DBNAME) | 5,314,426 |
def save_agent(output_dir, batch_id, model, optimizer, scheduler, keep_last=3):
"""Store agent to disk."""
fpath = os.path.join(output_dir, 'ckpt.%08d' % (batch_id))
logging.info('Saving: %s', fpath)
torch.save(
dict(model=model.state_dict(),
optim=optimizer.state_dict(),
... | 5,314,427 |
def repo(request, repo_id):
"""Show repo page and handle POST request to decrypt repo.
"""
repo = get_repo(repo_id)
if not repo:
raise Http404
if request.method == 'GET':
return render_repo(request, repo)
elif request.method == 'POST':
form = RepoPassowrdForm(reques... | 5,314,428 |
def plot_predicted_treatment_effect(cf, figsize, npoints, num_workers):
"""Plot the predicted treatment effect from a Causal Forest.
Args:
cf (CausalForest): Fitted Causal Forest.
figsize (tuple): The figure size.
npoints (int): Number of points for meshgrid.
num_workers (int): ... | 5,314,429 |
def create_progress_bar(total, desc, **kwargs):
"""Helper creating a progress bar instance for a given parameters set.
The bar should be closed by calling close() method.
"""
return ProgressBar(
total=total,
desc=desc,
# XXX: click.get_text_stream or click.get_binary_stream don'... | 5,314,430 |
def central_angle_names(zma):
""" distance coordinate names
"""
return vmat.central_angle_names(vmatrix(zma)) | 5,314,431 |
async def analyst_command(ctx, ticker=""):
"""Displays analyst recommendations [Finviz]"""
try:
# Debug
if cfg.DEBUG:
logger.debug("!stocks.dd.analyst %s", ticker)
# Check for argument
if not ticker:
raise Exception("Stock ticker is required")
... | 5,314,432 |
def cylinder_circles(nodeA, nodeB, radius, element_number=10):
"""
Return list of two circles with defined parameters.
"""
vector = (np.array(nodeA) - np.array(nodeB)).tolist()
ptsA = circle(nodeA, vector, radius, element_number)
ptsB = circle(nodeB, vector, radius, element_number)
return ... | 5,314,433 |
def test_conversions_matrix_compact_axis_angle():
"""Test conversions between rotation matrix and axis-angle."""
R = np.eye(3)
a = pr.compact_axis_angle_from_matrix(R)
pr.assert_compact_axis_angle_equal(a, np.zeros(3))
R = pr.active_matrix_from_intrinsic_euler_xyz(
np.array([-np.pi, -np.pi,... | 5,314,434 |
def test_adding_forms3(live_server, selenium, is_legacy_edge):
"""
Test behavior when adding a form to a formset with 4 visible forms of 4
initial forms.
"""
# Load webpage for test
params = {'template_name': 'interaction/adding_forms_3.html'}
test_url = f'{live_server.url}?{urlencode(params... | 5,314,435 |
def test_neighbors_pickle_nofit(tmpdir, datatype, data_info):
"""
Note: This test digs down a bit far into the
internals of the implementation, but it's
important that regressions do not occur
from changes to the class.
"""
nrows, ncols, n_info, k = data_info
model = cuml.neighbors.Near... | 5,314,436 |
def play():
"""
Main game loop.
Initialises game object. Checks for winning or draw conditions and asks for user input.
"""
game = Game.new_game()
instructions = "Player {} choose a cell with numbers 1-9: "
while True:
cls()
goto(1, 1)
game.draw_board(show_board)
... | 5,314,437 |
def get_at_index(obj, index):
"""Возвращает объект списка с определенным индексом.
Индексация списка 1...n
"""
try:
return obj[index - 1]
except IndexError:
return None | 5,314,438 |
def mass_distance_matrix(ts, query, w):
"""
Computes a distance matrix using mass that is used in mpdist_vector
algorithm.
Parameters
----------
ts : array_like
The time series to compute the matrix for.
query : array_like
The time series to compare against.
w : int
... | 5,314,439 |
def create_tube(inner_radius=0.5, outer_radius=1.0, height=1.0, slices=64, stacks=64):
"""generates the vertices, normals, and indices for a tube mesh
:param inner_radius: tube inner radius
:type inner_radius: float
:param outer_radius: tube outer radius
:type outer_radius: float
:param height:... | 5,314,440 |
def get_room_id(room_name):
"""
This function will find the Spark room id based on the {room_name}
Call to Spark - /rooms
:param room_name: The Spark room name
:return: the Spark room Id
"""
payload = {'title': room_name}
room_number = None
url = SPARK_URL + '/rooms'
header = {'... | 5,314,441 |
def dump(*args, **kwargs): # real signature unknown
""" Converts arbitrary object recursively into JSON file. Use ensure_ascii=false to output UTF-8. Pass in double_precision to alter the maximum digit precision of doubles. Set encode_html_chars=True to encode < > & as unicode escape sequences. """
pass | 5,314,442 |
def openstack_ceilometer(today, **kwargs):
"""
Pricing plugin for openstack ceilometer.
"""
clear_ceilometer_stats(today)
new = total = 0
for site in settings.OPENSTACK_CEILOMETER:
logger.info(
"Processing OpenStack ceilometer {}".format(site['WAREHOUSE'])
)
t... | 5,314,443 |
def spkezp_vector(k1, in11, str1, str2, k2):
"""spkezp_vector(SpiceInt k1, ConstSpiceDouble * in11, ConstSpiceChar * str1, ConstSpiceChar * str2, SpiceInt k2)"""
return _cspyce0.spkezp_vector(k1, in11, str1, str2, k2) | 5,314,444 |
def __compute_bounds_of_monom_power(monom: Expr, power: Number):
"""
Computes the bounds of monom**power by just taking the bounds of monom and raising it to the given power.
This is only sound if the given power is odd or the monom is always positive
"""
n = symbols("n", integer=True, positive=True... | 5,314,445 |
def rowSpacing(beta, sazm, lat, lng, tz, hour, minute):
"""
This method determines the horizontal distance D between rows of PV panels
(in PV module/panel slope lengths) for no shading on December 21 (north
hemisphere) June 21 (south hemisphere) for a module tilt angle beta and
surface azimuth sazm,... | 5,314,446 |
def _check_buildopts_arches(mmd, arches):
"""
Returns buildopts arches if valid, or otherwise the arches provided.
:param mmd: Module MetaData
:param arches: list of architectures
:return: list of architectures
"""
buildopts = mmd.get_buildopts()
if not buildopts:
return arches
... | 5,314,447 |
def hopwise_qry_encoder(qry_seq_emb,
qry_input_ids,
qry_input_mask,
is_training,
bert_config,
qa_config,
suffix="",
project=True,
project_dim=No... | 5,314,448 |
def construct_acyclic_matching_along_gradients(morse_complex,
delta=np.inf):
""" Finds an acyclic matching in filtration order along gradients
Inspired by [MN13] p. 344 MorseReduce
:param morse_complex: A morse complex
:param delta: Only construct matches... | 5,314,449 |
def create_qr_code(doc, method):
"""Create QR Code after inserting Sales Inv
"""
region = get_region(doc.company)
if region not in ['Saudi Arabia']:
return
# if QR Code field not present, do nothing
if not hasattr(doc, 'qr_code'):
return
# Don't create QR Code if it already exists
qr_code = doc.get("qr_c... | 5,314,450 |
def handle_getname(bot, ievent):
""" arguments: <nick> - fetch username of nick. """
try: nick = ievent.args[0]
except IndexError:
ievent.missing("<nick>")
return
userhost = getwho(bot, nick)
if not userhost:
ievent.reply("can't find userhost of %s" % nick)
return
... | 5,314,451 |
def test_algebra_reverse_mode_gradient_product_band_band(bandwidth1, bandwidth2, n):
"""
Testing reverse mode gradients of product_band_band against algebra
"""
l1, u1 = bandwidth1
l2, u2 = bandwidth2
with tf.compat.v1.Session(graph=tf.Graph()):
print("\nChecking gradients for ", (l1, u... | 5,314,452 |
def r2tth(x,dist):
"""Convert a numpy array of azimuthal radii to 2 theta"""
return np.arctan(x/dist)*180/np.pi | 5,314,453 |
def is_notebook():
"""
code from https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook
"""
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
... | 5,314,454 |
def init_bert_params(module):
"""
Initialize the weights specific to the BERT Model.
This overrides the default initializations depending on the specified arguments.
1. If normal_init_linear_weights is set then weights of linear
layer will be initialized using the normal distribution and
... | 5,314,455 |
def test_multisurf_pipeline():
"""Check: Data (Binary Endpoint, Discrete Features): MultiSURF works in a sklearn pipeline"""
np.random.seed(320931)
clf = make_pipeline(MultiSURF(n_features_to_select=2),
RandomForestClassifier(n_estimators=100, n_jobs=-1))
assert np.mean(cross_v... | 5,314,456 |
def crypto_lettre(dico: dict, lettre: str) -> str:
"""
Fonction qui renvoie une lettre cryptée d'après le dictionnaire associé
:param ASCIIrandom:
:param lettre: lettre MAJUSCULE
:return: la lettre cryptée en MAJUSCULE
"""
return dico[lettre] | 5,314,457 |
def compare_two_expval_steps(stepA, stepB):
"""Compares two steps used to compute expectation values."""
assert stepA["name"] == stepB["name"]
assert stepA["config"] == stepB["config"]
# Checking the inputs: part by part
assert (
stepA["inputs"][0]["backend_specs"]
== stepB["inputs"... | 5,314,458 |
def read_tusc(path):
"""Helper function to read in the Tuscany shapefile"""
path_shapefiles, regions, provinces, territories, municipalities, crs = read_files.read_shapefile_data(path, 'shape_files_path.json')
df_reg_tus = read_files.read_shapefiles_in(True, path_shapefiles, regions, crs)
return df... | 5,314,459 |
def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,
correct_label, keep_prob, learning_rate):
"""
Train neural network and print out the loss during training.
:param sess: TF Session
:param epochs: Number of epochs
:param batch_size: Batch s... | 5,314,460 |
def save_omas_json(ods, filename, objects_encode=None, **kw):
"""
Save an ODS to Json
:param ods: OMAS data set
:param filename: filename or file descriptor to save to
:param objects_encode: how to handle non-standard JSON objects
* True: encode numpy arrays, complex, and uncertain
... | 5,314,461 |
def preprocess_config(config, path, all_cols=True, model_cols=None, modify_config=None):
"""Preprocess the config
Args:
* config: original config
* path: path to load column names
Returns:
* config: preprocess config.
If design_all_cols is true, then read col_names from train_loa... | 5,314,462 |
def monoscale(array, color=MONOSCALE_SHADOWLEVEL, as_type=None, slice_size=SLICE_SIZE):
"""
Converts a grayscale array into a monoscale array.
This deletes shadow level 1 and sets the other shadow values to a uniform value.
The Poisson spot markings remain unchanged.
Note: After conversion, the opt... | 5,314,463 |
def _mergeChannels(st):
"""
function to find longest continuous data chunck and discard the rest
"""
st1 = st.copy()
st1.merge(fill_value=0.0)
start = max([x.stats.starttime for x in st1])
end = min([x.stats.endtime for x in st1])
try:
st1.trim(starttime=start, endtime=end)
e... | 5,314,464 |
def create_pattern(templates: List[str], input_str: str, pretty: bool = False):
"""
create all patterns based on list of input templates using the input string.
Args:
templates: list of templates/stencils
input_str: string to apply templates on to create patterns
pretty: used to pr... | 5,314,465 |
def dehaze(
image: xpArray,
size: int = 21,
downscale: int = 4,
minimal_zero_level: float = 0,
correct_max_level: bool = True,
in_place: bool = True,
internal_dtype=None,
):
"""
Dehazes an image by means of a non-linear low-pass rejection filter.
Parameters
----------
im... | 5,314,466 |
def token_price_chart_arken(token, symbol):
"""Lookup for prices via Arken API and return price chart image"""
timeframe = get_timeframe(INTERVAL) * 50 # Number of candlesticks
end_time = datetime.now()
# Convert datetime to Unix time
start_time = int(datetime.timestamp(end_time - timedelta(minute... | 5,314,467 |
def code_info(x, version, is_pypy=False):
"""Formatted details of methods, functions, or code."""
return format_code_info(get_code_object(x), version, is_pypy=is_pypy) | 5,314,468 |
def main():
""" Main method """
arcadeWindow: Window = Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
gameView: PyTrekView = PyTrekView()
arcadeWindow.set_exclusive_keyboard(exclusive=False)
arcadeWindow.show_view(gameView)
gameView.setup()
arcadeRun() | 5,314,469 |
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
substrings = []
a_substrings = get_substrings(a, n)
b_substrings = get_substrings(b, n)
# For every substring in list of substrings a:
for a_substring in a_substrings:
# For every substring in list of substrings... | 5,314,470 |
def all_ids(conn, protein=False, verbose=False):
"""
Get all the available IDs in the database
:param conn: the database connection
:param protein: Whether the object refers to protein (True) or DNA (False). Default=DNA
:param verbose: More output
:param verbose: More output
:return: A list ... | 5,314,471 |
def mc_control_epsilon_greedy(env, gamma, n_episode, epsilon):
"""
Obtain the optimal policy with on-policy MC control with epsilon_greedy
@param env: OpenAI Gym environment
@param gamma: discount factor
@param n_episode: number of episodes
@param epsilon: the trade-off between exploration and e... | 5,314,472 |
def v_slide(params):
"""
"""
paths = Paths()
try:
try:
scn_file = OpenSlide(paths.slice_80)
except OpenSlideUnsupportedFormatError:
logging.error("OpenSlideUnsupportedFormatError!")
return
except OpenSlideError:
logging.error("Open... | 5,314,473 |
def svn_wc_maybe_set_repos_root(*args):
"""
svn_wc_maybe_set_repos_root(svn_wc_adm_access_t adm_access, char path, char repos,
apr_pool_t pool) -> svn_error_t
"""
return _wc.svn_wc_maybe_set_repos_root(*args) | 5,314,474 |
def graph_semantics(g):
"""Convert a networkx.DiGraph to compounds and reactions for grid_land."""
compounds = {}
reactions = {}
for node, attributes in g.nodes.items():
if attributes.get("reaction"):
reactants = [e[0] for e in g.in_edges(node)]
products = [e[1] for e in ... | 5,314,475 |
def _depth_to_space_ds_tbe():
"""DepthToSpace TBE register"""
return | 5,314,476 |
def plot_water_levels(station, dates, levels):
"""When given a station object, a set of dates and a set of levels, plots a graph of level vs time with the typical
high/low levels."""
# Imports necessary stuff
import matplotlib.pyplot as plt
import datetime
# Plots the levels and times found abo... | 5,314,477 |
def fetching_latest_quiz_statistics(request_ctx, course_id, quiz_id, all_versions, **request_kwargs):
"""
This endpoint provides statistics for all quiz versions, or for a specific
quiz version, in which case the output is guaranteed to represent the
_latest_ and most current version of the quiz.
... | 5,314,478 |
def make_api_key(size=32):
"""Generate a random API key, should be as random as possible
(not predictable)
:param size: the size in byte to generate
note that it will be encoded in base58 manner,
the length will be longer than the aksed size
"""
# TODO: os.urandom collect entropy fr... | 5,314,479 |
def relocate_estimates_data(ws):
"""
"""
### Country group
ws = relocate(ws, 'B', 7, 11, 'B', 34)
ws = relocate(ws, 'D', 7, 11, 'C', 34)
ws = format_numbers(ws, ['C'], (34,40), 'Comma [0]', 3)
ws = relocate(ws, 'B', 7, 11, 'E', 34)
ws = relocate(ws, 'E', 7, 11, 'F', 34)
ws = format... | 5,314,480 |
def replace_channel_in_key(meta,new_band_id):
"""
Replace the band id in the CX header key.
Parameters
----------
meta : str
CX line header.
new_band_id : int
id for the new (zoom) band.
Returns
-------
new_meta : str
new CX line header.
... | 5,314,481 |
def check_cells_fit(cell_no, min_cell_distance, space_range=[[0,10],[0,10],None]):
""" given the number of cells (cell_no), and the minimal distance
between the cells and the space_ranges (x,y,z) it returns True if the
cells can fit within this range and False if not. If any of the
dimensions does not... | 5,314,482 |
def set_axes(ax, title='', xlabel='', ylabel='', yscale='linear', xscale='linear',
fontsize=14, yticks=True, xticks=True):
"""Standardised formatting of labels etc.
"""
if not yticks:
ax.axes.tick_params(axis='both', left='off', labelleft='off')
if not xticks:
ax.axes.tick_p... | 5,314,483 |
def parse_args() -> argparse.Namespace:
"""Parse CLI arguments.
:return: Namespace object holding parsed arguments as attributes.
This object may be directly used by garminexport/garminbackup.py.
"""
parser = argparse.ArgumentParser(
prog="garminbackup",
description=(
"P... | 5,314,484 |
def findDuplicates(fileName):
"""查找重复曲目"""
print("Finding duplicate tracks in "+ fileName +" ...")
# 读取播放列表
# P-list文件将对象表示为字典,而播放列表文件使用的是一个字典的字典字典(值仍为一个字典);readPlist读入一个P-list文件作为输入,返回一个字典字典
plist = plistlib.readPlist(fileName)
# 从播放列表字典中获取Tracks键的值--声轨字典存为tracks
tracks = plist['Tracks']
... | 5,314,485 |
def conform_keys(
valid,
suspect,
default=NoDefault,
message="Removed spurious key '{}' from input dictionary."
):
"""
Takes a collection "valid" and a dictionary "suspect" and removes all keys
from "suspect" that don't exist in "valid", issuing a warning for each
composed of the given message formatted... | 5,314,486 |
def _read_sub_atoms(atom: tuple) -> list:
"""
A special method for parsing a stream that isn't from the
original file.
:param atom: a tuple containing atom data
:return: a set of sub atoms
"""
byte_stream = io.BytesIO(atom[2])
atoms = _read_atoms(byte_stream, atom[0] - 8)
return ato... | 5,314,487 |
def bassGura(A, B, desiredPoles, C=None, E=None):
"""
use Bass-Gura formalism to compute gain matrix, G, that places poles of the closed-loop meta-system \hat A- \hat B*G
at desired locations
Inputs:
A (numpy matrix/array, type=real) - system state matrix
B (numpy matrix/array, type=rea... | 5,314,488 |
def dwarf(allstar,mhrange=[-2.5,1.0],loggrange=[3.8,5.5],teffrange=[3000,7500],apokasc_cat='APOKASC_cat_v4.4.2.fits',out='logg',calib=False) :
""" logg calibration for dwarfs, from asteroseismic and isochrones
"""
if calib :
param = 'PARAM'
else :
param = 'FPARAM'
gd=apselect.select... | 5,314,489 |
def subscribe(project, tempdir):
"""
Subscribe to a project using the Application Manager. Waits for updates to the project and
analyses any unchecked deployments continually.
"""
def checkForUDs(project, tempdir):
import time
time.sleep(1) #We currently seem to have to give the metadata a little time to updat... | 5,314,490 |
def get_marks(record, transcript):
""" (str, str) -> list of float
Return a list of final course marks from transcript that can be used for
admission, computed based on information in record.
>>> record = 'Eyal de Lara,Fort McMurray Composite High,2016,MAT,90,92,ENG,92,NE,BIO,77,85,BSci'
>>> trans... | 5,314,491 |
def zip(*iterables: Any) -> "Iter[Tuple[T, ...]]":
""" Replacement for the builtin ``zip`` function. This version returns
an instance of Iter_ to allow further iterable chaining."""
return Iter(_zip(*iterables)) | 5,314,492 |
def loadConversations(fileName, lines,
fields=["character1ID", "character2ID", "movieID", "utteranceIDs"],
delimiter=" +++$+++ "):
"""
Args:
fileName (str): file to load
field (set<str>): fields to extract
Return:
dict<dict<str>>: the extra... | 5,314,493 |
def optimize_schedule_rotations(schedule, sregistry):
"""
Transform the schedule such that the tensor temporaries "rotate" along
the outermost Dimension. This trades a parallel Dimension for a smaller
working set size.
"""
# The rotations Dimension is the outermost
ridx = 0
rmapper = de... | 5,314,494 |
async def test_datapoints_greater_than_degree(
hass: HomeAssistant, caplog: LogCaptureFixture
):
"""Tests 3 bad data points."""
config = {
DOMAIN: {
"test": {
CONF_SOURCE: "sensor.uncalibrated",
CONF_DATAPOINTS: [
[1.0, 2.0],
... | 5,314,495 |
def test_generate_xml_with_empty_root(client: Eve, sample_schema: dict):
"""Test to xml can be generated with an empty root
:param Eve client: Mockerena app instance
:param dict sample_schema: Sample schema data
:raises: AssertionError
"""
sample_schema["num_rows"] = 1
sample_schema["file_... | 5,314,496 |
def preload_family(family, executor):
"""Preload all sites of a single family file."""
msg = 'Preloading sites of {} family{}'
pywikibot.output(msg.format(family, '...'))
codes = Family.load(family).languages_by_size
for code in exceptions.get(family, []):
if code in codes:
code... | 5,314,497 |
def test_function_application():
"""Tests applying a function to an uncertainty"""
result = Uncertainty(5, 2).apply(math.sqrt)
expected = Uncertainty(2.2, 0.4)
assert round(result.value, 1) == expected.value
assert round(result.abs_uncertainty(), 1) == expected.abs_uncertainty() | 5,314,498 |
def parse_config(config_fn):
"""Deprecated.
Called from pbsmrtpipe, for now.
"""
return parse_cfg_file(config_fn) | 5,314,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.