content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calculate_mean_probas(time_ser, model):
"""Calculate the metric to evaluate based on average probabilities
Args:
time_ser (np.ndarray): dynophore time series
model (HMM): Fitted HMM
Returns:
np.float: Probability of prediting the given time series based on the fitted model
... | 29,300 |
def baxter_callback(data):
"""!
Computes the configuration of baxter's arm whenever the data are available, then extracts the rotation
matrix from 0 to e.e and the position of the e.e. with respect to 0. It also computes the jacobian matrix.
In case all the other callbacks have been called then it compu... | 29,301 |
def compute_t(i, automata_list, target_events):
"""
Compute alphabet needed for processing L{automata_list}[i-1] in the
sequential abstraction procedure.
@param i: Number of the automaton in the L{automata_list}
@type i: C{int} in range(1, len(automata_list)+1)
@param automata_list: List of a... | 29,302 |
def cleaner(f_stop):
"""
Clear the data from the data dictionary
"""
if len(data) > 0:
print(f'LOG: Cleaned {len(data)} items!')
data.clear()
if not f_stop.is_set():
threading.Timer(5000, cleaner, [f_stop]).start() | 29,303 |
def cal_min_sim(y):
"""Calculate the minimal value given multiple trajectories from different isomers"""
y = y.copy()
if len(y.shape) == 2: # add one more dimension if only two provided
y = y[np.newaxis, :]
n_sim, nT, nP = y.shape
y_min_sim = np.min(y, axis = 0)
return y_min_... | 29,304 |
async def create_rsa_key(
hub,
ctx,
name,
vault_url,
key_ops=None,
enabled=None,
expires_on=None,
not_before=None,
tags=None,
**kwargs,
):
"""
.. versionadded:: 2.0.0
Create a new RSA key or, if name is already in use, create a new version of the key. Requires the ke... | 29,305 |
def _parse_size_string(size):
"""
Parse a capacity string.
Takes a string representing a capacity and returns the size in bytes, as an
integer. Accepts strings such as "5", "5B", "5g", "5GB", " 5 GiB ", etc.
Case insensitive. See `man virsh` for more details.
:param size: The size string to p... | 29,306 |
def connect(cfg=None, jar=None):
""" Connect to MF using a token with authority to access the data collection
:return: A new :py:class:`Session`
Example::
>>> from MFQuery.MF import MF
>>> cfg = "$HOME/aterm.cfg"
>>> jar = "$HOME/aterm.jar"
>>> wath = MF.connect(cfg,jar) # doctest: +SKI... | 29,307 |
def main(): # pragma: no cover
"""
Main func
"""
parser = setup_argparser()
args = parser.parse_args()
log_level = "DEBUG" if args.verbose else "INFO"
setup_logger(log_level)
call_ibm_webhook(args) | 29,308 |
def get_exp_lr(base_lr, xs, power=4e-10):
"""Get learning rates for each step."""
ys = []
for x in xs:
ys.append(base_lr / np.exp(power*x**2))
return ys | 29,309 |
def dashboard():
""" Main dashboard function. Run stats across all accounts. """
start = time.time()
instance_count = 0
user_count = 0
sg_count = 0
elb_count = 0
aws_accounts = AwsAccounts()
accounts = aws_accounts.all()
pool = Pool(10)
results = pool.map(get_account_stats, acc... | 29,310 |
def strip_new_line(str_json):
"""
Strip \n new line
:param str_json: string
:return: string
"""
str_json = str_json.replace('\n', '') # kill new line breaks caused by triple quoted raw strings
return str_json | 29,311 |
def rebuild_from_dat(inputDatfile, outputSessionName):
"""
Rebuilds a pymanip HDF5 file from the ASCII dat file.
"""
if not has_panda:
print("Pandas is not available.")
else:
with inputDatfile.open() as in_f:
data = pd.read_csv(in_f, sep=" ")
liste_var = list... | 29,312 |
def fromAtoB(x1, y1, x2, y2, color='k', connectionstyle="arc3,rad=-0.4",
shrinkA=10, shrinkB=10, arrowstyle="fancy", ax=None):
"""
Draws an arrow from point A=(x1,y1) to point B=(x2,y2) on the (optional)
axis ``ax``.
.. note::
See matplotlib documentation.
"""
if ax is No... | 29,313 |
def test_bandit(src_dir):
"""Run Bandit."""
bandit = plumbum.local["bandit"]
with plumbum.local.cwd(PROJECT_ROOT_DIR):
result = bandit("-ll", "-r", src_dir)
if result:
print("\nBandit:", result) | 29,314 |
def exp(input_):
"""Wrapper of `torch.exp`.
Parameters
----------
input_ : DTensor
Input dense tensor.
"""
return torch.exp(input_._data) | 29,315 |
def capsule_sdf(mesh_verts, mesh_normals, query_points, query_normals, caps_rad, caps_top, caps_bot, foreach_on_mesh):
"""
Find the SDF of query points to mesh verts
Capsule SDF formulation from https://iquilezles.org/www/articles/distfunctions/distfunctions.htm
:param mesh_verts: (batch, V, 3)
:pa... | 29,316 |
def test_just_single_point_plotting():
"""
Testing this because this has caused problems since for a single point min == max
"""
x = [2.34]
plot(x) | 29,317 |
def get_lat_lon(fp, fs=FS):
"""
get lat lon values for concat dataset
"""
logger.info(f"{str(datetime.datetime.now())} : Retrieving lat lon")
with xr.open_dataset(fs.open(fp)) as ds:
lat, lon = ds["latitude"].values, ds["longitude"].values
logger.info(f"{str(datetime.datetime.now())} : R... | 29,318 |
def one_hot_encode(vec, vals=10):
"""
For use to one-hot encode the 10- possible labels
"""
n = len(vec)
out = np.zeros((n, vals))
out[range(n), vec] = 1
return out | 29,319 |
def COUNTA(*args) -> Function:
"""
Returns a count of the number of values in a dataset.
Learn more: https//support.google.com/docs/answer/3093991
"""
return Function("COUNTA", args) | 29,320 |
def stop():
""" Syncs the database and then starts the development server. """
stop_django() | 29,321 |
def decode_url_json_string(json_string):
"""
Load a string representing serialised json into
:param json_string:
:return:
"""
strings = json.loads(h.unescape(json_string),
object_pairs_hook=parse_json_pairs)
return strings | 29,322 |
def syn_test_helper():
"""Provides the SynapseTestHelper as a fixture per function."""
helper = SynapseTestHelper()
yield helper
helper.dispose() | 29,323 |
def init_argparser():
"""
Define and parse commandline arguments.
"""
# training settings
parser = argparse.ArgumentParser(description="PyTorch MNIST Example")
parser.add_argument("--experiment", type=str, help="Choose the experiment.")
parser.add_argument(
"--batch-size",
ty... | 29,324 |
def generate(traj: pca3dvis.trajectory.ProjectedTrajectory,
markers: typing.Tuple[typing.Tuple[np.ndarray, dict]],
titles: typing.Tuple[str],
outfolder: str,
draft: bool = False,
clusters: bool = True):
"""Generates a video and corresponding sna... | 29,325 |
def write_enum(enum, writer):
"""
Write class representing Avro enum schema
:param schema.EnumSchema enum:
:param TabbedWriter writer:
:return:
"""
fullname = clean_fullname(enum.fullname)
namespace, type_name = ns_.split_fullname(enum.fullname)
writer.write('''\nclass {name}Class(ob... | 29,326 |
def svn_wc_merge2(*args):
"""
svn_wc_merge2(enum svn_wc_merge_outcome_t merge_outcome, char left,
char right, char merge_target, svn_wc_adm_access_t adm_access,
char left_label, char right_label,
char target_label, svn_boolean_t dry_run,
char diff3_cmd, apr_array_header_t merge... | 29,327 |
def test_finetuning_callback_warning(tmpdir):
"""Test finetuning callbacks works as expected."""
seed_everything(42)
class FinetuningBoringModel(BoringModel):
def __init__(self):
super().__init__()
self.backbone = nn.Linear(32, 2, bias=False)
self.layer = None
... | 29,328 |
def idempotent(function):
"""Shallows 304 errors, making actions repeatable."""
@wraps(function)
def decorator(*args, **kwargs):
with suppress(GitlabCreateError):
return function(*args, **kwargs)
return decorator | 29,329 |
def write_binary_file(output_path, data):
"""Writes the given bytes stored in the bytearray 'data' to a binary file
at the location pointed to by 'output_path'."""
with open(output_path, "wb") as f:
f.write(data) | 29,330 |
def enclose(g):
"""
Create a one-wide permimeter along the edges of the grid.
"""
w, h = g.size()
wi, hi = 0, 0
while wi < w: # Top
g.put(wi, hi, False)
wi += 1
wi -= 1
while hi < h: # Right
g.put(wi, hi, False)
hi += 1
wi, hi = 0, 0
while hi <... | 29,331 |
def newline_formatter(func):
"""
Wrap a formatter function so a newline is appended if needed to the output
"""
def __wrapped_func(*args, **kwargs):
"""
Wrapper function that appends a newline to result of original function
"""
result = func(*args, **kwargs)
# Th... | 29,332 |
def sigma_splitter(float_arr: List[float]) -> Tuple[List[List[int]], List[List[int]], List[List[int]]]:
"""
separates the NCOF score into the 1-3 sigma outliers for the NCOF input
@param float_arr: List[float]
@return: inliers , pos_outliers , neg_outliers: List[List[int]], List[List[int]], List[List[in... | 29,333 |
def populate_diff_chunks(files, enable_syntax_highlighting=True,
request=None):
"""Populates a list of diff files with chunk data.
This accepts a list of files (generated by get_diff_files) and generates
diff chunk data for each file in the list. The chunk data is stored in
the... | 29,334 |
def cosine_beta_schedule(timesteps, s = 0.008, thres = 0.999):
"""
cosine schedule
as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
"""
steps = timesteps + 1
x = torch.linspace(0, timesteps, steps, dtype = torch.float64)
alphas_cumprod = torch.cos(((x / timesteps) + s) / (1 + s) * t... | 29,335 |
def start_generator(args):
"""
Triggers the execution of the generator given the parameters from arguments
"""
start(
brokerServers=args.brokerServers.split(',') or env.DEFAULT_BROKER_SERVERS.split(','),
topic=args.topic or env.DEFAULT_TOPIC,
total_messages=int(
args.... | 29,336 |
def construct_from_yaml(
constructor: Callable[..., T],
yaml_dict: Optional[Dict[str, Any]] = None,
) -> T:
"""Build ``constructor`` from ``yaml_dict``
Args:
constructor (Callable): The constructor to test (such as an Hparams class)
yaml_dict (Dict[str, Any], optional): The YAML. Defaul... | 29,337 |
def text_to_document(text, language="en"):
""" Returns string text as list of Sentences """
splitter = _sentence_splitters[language]
utext = unicode(text, 'utf-8') if isinstance(text, str) else text
sentences = splitter.tokenize(utext)
return [tokenize(text, language) for text in sentences] | 29,338 |
def get_top_playlists_route(type):
"""
An endpoint to retrieve the "top" of a certain demographic of playlists or albums.
This endpoint is useful in generating views like:
- Top playlists
- Top Albums
- Top playlists of a certain mood
- Top playlists of a certain mood from pe... | 29,339 |
def parse_host(incomplete_uri: str) -> str:
"""Get netloc/host from incomplete uri."""
# without // it is interpreted as relative
return urllib.parse.urlparse(f"//{incomplete_uri}").netloc | 29,340 |
def inner_by_delta(vec1: Vec, vec2: Vec):
"""Compute the inner product of two vectors by delta.
The two vectors are assumed to be from the same base and have the same
number of indices, or ValueError will be raised.
"""
indices1 = vec1.indices
indices2 = vec2.indices
if vec1.label != vec2.... | 29,341 |
def setup_drake(*, version, build='nightly'):
"""Installs drake on Google's Colaboratory and (if necessary) adds the
installation location to `sys.path`. This will take approximately two
minutes, mostly to provision the machine with drake's prerequisites, but
the server should remain provisioned for 12... | 29,342 |
def remove_mapping(rxn_smi: str, keep_reagents: bool = False) -> str:
"""
Removes all atom mapping from the reaction SMILES string
Parameters
----------
rxn_smi : str
The reaction SMILES string whose atom mapping is to be removed
keep_reagents : bool (Default = False)
whether to... | 29,343 |
def test_multiple_jobs(caplog, no_job_dirs):
"""Test with multiple jobs.
From: https://ci.appveyor.com/project/racker-buildbot/luv
:param caplog: pytest extension fixture.
:param str no_job_dirs: Test with --no-job-dirs.
"""
jobs_artifacts = [
('v5wnn9k8auqcqovw', 'luajit.exe', 675840)... | 29,344 |
def generate_bot_master_get_results_message(message_id, receiving_host, receiving_port):
"""
:rtype : fortrace.net.proto.genericmessage_pb2.GenericMessage
:type receiving_port: int
:type receiving_host: str
:type message_id: long
:param message_id: the id of this message
:param receiving_ho... | 29,345 |
def update_comments_in_parent(reference_doctype, reference_name, _comments):
"""Updates `_comments` property in parent Document with given dict.
:param _comments: Dict of comments."""
if not reference_doctype or not reference_name or frappe.db.get_value("DocType", reference_doctype, "issingle"):
return
try:
#... | 29,346 |
def print_encoding_dic(obj, f=stdout):
"""
Generate and print the definition of encoding dictionary
"""
print(
"""\
/// map from composed character (normal) to decomposed components (HFS+)
///
/// # Examples
///
/// ```ignore
/// assert_eq!((*MAP_TO_HFS).get(&'\\u{00E9}')... | 29,347 |
def readLogData(username,level,root='.'):
"""
Extracts key events from a log
"""
filename = getFilename(username,level,extension='log',root=root)
log = []
start = None
for line in fileinput.input(filename):
elements = line.split()
if elements[2] == MESSAGE_TAG:
no... | 29,348 |
def get_type1(pkmn):
"""get_type1(pkmn) returns Type 1 of the Pokémon with the name 'pkmn' """
return __pokemon__[pkmn]['Type 1'] | 29,349 |
def load_json(fname):
"""
Load a JSON file containing a riptide object (or list/dict/composition thereof)
"""
with open(fname, 'r') as f:
return from_json(f.read()) | 29,350 |
def build(dockerfile, force_rm, no_cache, quiet, rm, tag, path):
"""
Build a new image from the source code at PATH.
"""
build_dockerfile = os.path.join(path, DOCKERFILE)
if dockerfile and os.path.exists(build_dockerfile):
click.echo('A Dockerfile already exists at {}, refusing to run!'
... | 29,351 |
def cargo_build(name, srcs, binaries, cargo_flags, profile = "release", target = None, env_paths = {}, deps = []):
""" Builds cargo binaries.
Args:
name: name of the target.
srcs: list of input labels.
binaries: names of binaries to build.
cargo_flags: extra flags to pass to cargo.
... | 29,352 |
def get_stock_data(symbol, start_date, end_date, source="phisix", format="c"):
"""Returns pricing data for a specified stock and source.
Parameters
----------
symbol : str
Symbol of the stock in the PSE or Yahoo.
You can refer to these links:
PHISIX: https://www.pesobility.com/... | 29,353 |
def extract_borderless(result) -> list:
"""
extracts borderless masks from result
Args:
result:
Returns: a list of the borderless tables. Each array describes a borderless table bounding box.
the two coordinates in the array are the top right and bottom left coordinates of the bounding box.
... | 29,354 |
def get_frequent_length_k_itemsets(transactions, min_support=0.2, k=1, frequent_sub_itemsets=None):
"""Returns all the length-k itemsets, from the transactions, that satisfy
min_support.
Parameters
----------
transactions : list of list
min_support : float, optional
From 0.0 to 1.0. Per... | 29,355 |
def long_slice(image_path, out_name, out_dir, slice_size):
"""slice an image into parts slice_size tall"""
img = Image.open(image_path)
width, height = img.size
upper = 0
slices = int(math.ceil(height/slice_size))
for i, _ in enum(range(slices)):
left = 0
upper = upper
... | 29,356 |
def create_news_markup():
"""
Метод, создающий клавиатуру для новостей кино
:return: telebot.types.ReplyKeyboardMarkup
"""
news_markup = types.ReplyKeyboardMarkup()
news_markup.row(Commands.GET_BACK_COMMAND)
return news_markup | 29,357 |
def NVDA_restarts():
"""Ensure NVDA can be restarted from keyboard."""
spy = _nvdaLib.getSpyLib()
spy.wait_for_specific_speech("Welcome to NVDA") # ensure the dialog is present.
spy.wait_for_speech_to_finish()
# Get handle of the message window for the currently running NVDA
oldMsgWindowHandle = _getNvdaMessageW... | 29,358 |
def get_bibtex_query_set(params):
"""Returns bibtex objects which match the search parameters.
Args:
params: dict which is maded by `parse_GET_params`
Returns:
QuerySet
request_dict
"""
bibtex_queryset = Bibtex.objects.all()
# Book_style
book_style = params.get("b... | 29,359 |
def _generate_description_from(command, name, description):
"""
Generates description from the command and it's optionally given description. If both `description` and
`command.__doc__` is missing, defaults to `name`.
Parameters
----------
command : `None` or `callable`
The command's fu... | 29,360 |
def test_source_observation(gcc_bin: str):
"""Test observation spaces."""
with gym.make("gcc-v0", gcc_bin=gcc_bin) as env:
env.reset()
lines = env.source.split("\n")
assert re.match(r"# \d+ \"adpcm.c\"", lines[0]) | 29,361 |
def uses_na_format(station: str) -> bool:
"""
Returns True if the station uses the North American format,
False if the International format
"""
if station[0] in NA_REGIONS:
return True
elif station[0] in IN_REGIONS:
return False
elif station[:2] in M_NA_REGIONS:
retur... | 29,362 |
def openFile(prompt,key = "r",defaulttype = None, defaultname = None):
"""
Method to open a text file with sanity checking, optional defaults and reprompt on failure.
This is the main used callable function to open files.
:param prompt: the prompt to be displayed
:type prompt: str
:param key: ... | 29,363 |
def dsphere(n=100, d=2, r=1, noise=None, ambient=None):
"""
Sample `n` data points on a d-sphere.
Parameters
-----------
n : int
Number of data points in shape.
r : float
Radius of sphere.
ambient : int, default=None
Embed the sphere into a space with ambient dimensi... | 29,364 |
def topological_sort_by_down(start_nodes=None, all_nodes=None):
"""
Topological sort method by down stream direction.
'start_nodes' and 'all_nodes' only one needs to be given.
Args:
start_nodes (list[NodeGraphQt.BaseNode]):
(Optional) the start update nodes of the graph.
all... | 29,365 |
def generate_and_upload_doxygen():
"""Generate Doxygen."""
# Create empty dir and add static_footer.txt
recreate_dir(DOXYGEN_WORKING_DIR)
static_footer_path = os.path.join(DOXYGEN_WORKING_DIR, 'static_footer.txt')
shutil.copyfile(os.path.join('tools', 'doxygen_footer.txt'),
static_footer_pat... | 29,366 |
def test_sigmat():
"""
Test the support functionality for attached signature cryptographic material
"""
with pytest.raises(EmptyMaterialError):
sigmet = SigMat()
assert SigTwoDex.Ed25519 == 'A' # Ed25519 signature.
assert SigTwoDex.ECDSA_256k1 == 'B' # ECDSA secp256k1 signature.
... | 29,367 |
def test_fail(testdir):
"""Fail example. Should fail for several reasons."""
testdir.makefile('.t', r"""
Output needing escaping:
$ printf '\00\01\02\03\04\05\06\07\010\011\013\014\016\017\020\021\022\n'
foo
$ printf '\023\024\025\026\027\030\031\032\033\034\035\036\037\040\047\n'
bar
Wrong output and... | 29,368 |
def check_directories(directories):
"""Checks if all given directories are really directories and on the same
device.
Parameters:
directories (list of strings) - The directories to check.
Returns:
The tuple (ok, ok_dirs) where ok is a boolean and ok_dirs a list of
d... | 29,369 |
def pqm_incoming_message_thread(thread_name, dealer_id_string, poll_timeout, no_activity_sleep,
action_queue, notification_queue, received_message_queue):
"""
This thread is responsible for handling incoming messages from PQMs.
An outside thread can command this thread to ta... | 29,370 |
def download_accessions(force_download=False):
"""Downloads the compound accessions
:param bool force_download: If true, overwrites a previously cached file
:rtype: str
"""
if os.path.exists(ACCESSION_DATA_PATH) and not force_download:
log.info('using cached data at %s', ACCESSION_DATA_PATH... | 29,371 |
def ssh_zero_retry():
""" Fixture to provide quick access to changing the ssh retry count. This is useful for speeding
up mocked ssh commands. """
# Save the original interval off
original_retry_count = environment.EPYTHON_SSH_RETRIES
# Set the updated interval to zero
environment.EPYTHON_SSH_... | 29,372 |
def parseYear(year, patterns):
""""This function returns a string representing a year based on the input and a list of possible patterns.
>>> parseYear('2021', ['%Y'])
'2021'
>>> parseYear('2021', ['(%Y)', '%Y'])
'2021'
>>> parseYear('(2021)', ['%Y', '(%Y)'])
'2021'
"""
parsedYear = None
for p in ... | 29,373 |
def fit_oxy_nii(target_row,
velocity_column = None,
data_column = None,
IP = "center",
**kwargs):
"""
Fits oxygen bright line to spectrum for future subtraction
Parameters
----------
target_row: `SkySurvey` row
... | 29,374 |
def get(url, accept=None, headers=None):
"""
Make a basic HTTP call to CMR using the POST action
Parameters:
url (string): resource to get
body (dictionary): parameters to send, or string if raw text to be sent
accept (string): encoding of the returned data, some form of json is expe... | 29,375 |
def image_reproject_from_healpix_to_file(source_image_hdu, target_image_hdu_header, filepath=None):
""" reproject from healpix image to normal wcs image
:param source_image_hdu: the HDU object of source image (healpix)
:param target_image_hdu_header: the HDU object of target image (wcs)
:param f... | 29,376 |
def flux_reddening_wl(wl, flux_wl, ebv, Rv=None, law=LawFitz, mode=ReddeningLaw.MW):
"""
Apply extinction curves to flux(lambda) values
:param wl: [A]
:param flux_wl: [ergs s^-1 cm^-2 A^-1]
:param ebv: E(B-V)
:param Rv: R_V
:param law: the variant of extinction curves
:param mode: type... | 29,377 |
def test_cray_artifacts_create(cli_runner):
""" Test cray artifacts create ... """
runner, cli, _ = cli_runner
# Missing bucket name
result = runner.invoke(cli, ['artifacts', 'create', ])
assert result.exit_code == 2 | 29,378 |
def genRandomString( size: int = 5, upper: bool = False, lower: bool = False, mix: bool = False, numbers: bool = True) -> str:
"""
Generates a random string of the given size and content.
:param numbers: Numbers are included in the string. Default True.
:param upper: Uppercase only. Default False.
:param lower: Lo... | 29,379 |
def process_whole_image(model, images, num_crops=4, receptive_field=61, padding=None):
"""Slice images into num_crops * num_crops pieces, and use the model to
process each small image.
Args:
model: model that will process each small image
images: numpy array that is too big for model.predic... | 29,380 |
def compute_covariance(model, xy, XY=None):
"""Returns the covariance matrix for a given set of data"""
if xy.size == 1:
dist = 0
elif XY is None:
dist = squareform(pdist(xy))
else:
dist = cdist(xy, XY)
C = model(dist)
return C | 29,381 |
def prob1(cur: sqlite3.Cursor) -> pd.DataFrame:
"""List how many stops are in the database.
Parameters
----------
cur (sqlite3.Cursor) : The cursor for the database we're accessing.
Returns
-------
(pd.DataFrame) : Table with the solution.
"""
cur.execute("SELECT COUNT(... | 29,382 |
def q_fn(x):
"""
The Q-function assesses all possible actions that can be taken, given a state.
Two layer feed forward neural network. All layers are fully connected, biases initialized with 0.
The constants above define the layer sizes.
:param x: Batch input tensor to the network.
:return: Acti... | 29,383 |
def getPlayer(env, name, decoder):
"""Get user's player data"""
players = getPlayers(env, decoder)
if name in players.keys():
return players[name]
else:
return False | 29,384 |
def test_esd_lbaas_stcp_lbaas_persist(track_bigip_cfg, ESD_Pairs_Experiment):
"""Validate application of a pair of tags."""
apply_validate_remove_validate(ESD_Pairs_Experiment) | 29,385 |
def set_nonblocking_pipe(pipe): # type: (typing.Any) -> None
"""Set PIPE unblocked to allow polling of all pipes in parallel."""
descriptor = pipe.fileno() # pragma: no cover
if _posix: # pragma: no cover
# Get flags
flags = fcntl.fcntl(descriptor, fcntl.F_GETFL)
# Set nonblock ... | 29,386 |
def step_impl(context):
"""Check that context.last_executor_id is executed"""
executor = context.manager.get_executor(context.last_executor_id)
assert executor.executed is True | 29,387 |
def get_config_errors(conf, filename="<no name>"):
"""
Validate a configuration object and return the list of errors found.
"""
rv = []
# Give a clearer error message than what jsonschema would give
# Something like: None is not of type 'object'
if not isinstance(conf, dict):
msg = ... | 29,388 |
def process_vcf( info ):
"""
pass izip object of line object and other needed vars
info[0] = list of vcf lines from VCF object iterator.
info[1] = clf object
info[2] = dataset dictionary
info[3] = filter arg supplied by user
info[4] = min classification frequency supplied by user (defaults to None)
"""
... | 29,389 |
def createLayerOnFrameDepend(job, layer, onjob, onlayer, onframe):
"""Creates a layer on frame dependency
@type job: string
@param job: the name of the dependant job
@type layer: string
@param layer: the name of the dependant layer
@type onjob: string
@param onjob: the name of the job to dep... | 29,390 |
def compute_task1_f1_score(truth, solutions):
""" compute f1 score for task 1
:param truth: list of ground truth values for all problem-ids
:param solutions: list of solutions for all problem-ids
:return: f1 score
"""
task1_truth, task1_solution = extract_task_results(truth, solutions, 'multi-au... | 29,391 |
def multiply(t1,t2):
"""
Multiplies (expands) two binary expressions t1 and t2 based on the distributive rule
Args:
t1 (str): first binary expression
t2 (str): second binary expression
Returns:
A string representing the expansion of the boolean algebraic... | 29,392 |
def source_remove_all(obj_type, obj_id, name, analyst=None):
"""
Remove a source from a top-level object.
:param obj_type: The CRITs type of the top-level object.
:type obj_type: str
:param obj_id: The ObjectId to search for.
:type obj_id: str
:param name: The name of the source.
:type ... | 29,393 |
def driver(dbname):
"""
Determine driver module
:Parameters:
`dbname` : ``str``
DB name (section token in db.conf)
:Return: Driver module
:Rtype: ``module``
:Exceptions:
- `DBConfigurationError` : DB not configured
- `KeyError` : DB name not found
- `ImportErro... | 29,394 |
def d1tile_x_d2(d1: Union[float, np.ndarray],
d2: np.ndarray) -> np.ndarray:
"""
Create array of repeated values with dimensions that match those of energy array
Useful to multiply frequency-dependent values to frequency-time matrices
:param d1: 1D input vector, nominally frequency/scal... | 29,395 |
def load_ascii_font(font_name):
"""
Load ascii font from a txt file.
Parameter
---------
font_name : name of the font (str).
Return
------
font : font face from the file (dic).
Version
-------
Specification : Nicolas Van Bossuyt (v1. 27/02/17)
Notes
-----
Load font in figlet format (http://www.figlet... | 29,396 |
def get_all_gradients_for_Q4( theta, X, Y ):
"""
Do the same thing as Q(iv) but it is actually only for storing and
observing the sample gradient and whole gradient for the Q(iv) step
Output the sample grdient and whole grdient data
"""
# Get difference of uclidean distance
def get_differen... | 29,397 |
def static(ctx):
"""Run static analysis."""
print(f'🎉🌩️ All static analysis passed.') | 29,398 |
def findSubsetIndices(min_lat,max_lat,min_lon,max_lon,lats,lons):
"""Array to store the results returned from the function"""
res=np.zeros((4),dtype=np.float64)
minLon=min_lon; maxLon=max_lon
distances1 = []; distances2 = []
indices=[]; index=1
for point in lats:
s1 = max_lat-point # ... | 29,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.