content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def remove_redundant_latents(
graph: nx.DiGraph, tag: Optional[str] = None
) -> Tuple[nx.DiGraph, Set[str]]:
"""Remove redundant latent variables.
:param graph: A latent variable DAG
:param tag: The tag for which variables are latent
:returns: The graph, modified in place
"""
remove = set(_... | 5,290,500 |
def test_nexus_interleave(writer):
"""Test Nexus Generation - Interleaved"""
n = writer.make_nexus(interleave=True)
assert re.search(r"#NEXUS", n)
assert re.search(r"BEGIN DATA;", n)
assert re.search(r"DIMENSIONS NTAX=3 NCHAR=2;", n)
assert re.search(r"MATRIX", n)
# char1
assert re.searc... | 5,290,501 |
def get_chattering_species(atom_followed="C"):
"""
return chattering species
the chatteing reaction infomation is just for reference, will not use it
as long as the paired chattering species is provided, should be fine
better make them in the same order
"""
fast_transitions = [{}]
trapp... | 5,290,502 |
def word_accuracy(predictions, labels):
"""predictions and labels are of shape Batches x NUM_Digits_Pred and Batches x NUM_Digits_Label
"""
predictions, labels = pad_pred_label(predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
if labels.dtype != predictions.d... | 5,290,503 |
def inherit_doc(cls):
"""
This decorator simply add docstrings from parent class to subclass methods if no documentation
exists on the subclass method.
"""
for name, func in vars(cls).items():
if isinstance(func, types.FunctionType) and not func.__doc__:
for parent in cls.__bases... | 5,290,504 |
def editSearch(request, search_id=None):
"""
Handler for editing an existing search
"""
#load the search passed in
if search_id:
search = Search.objects.get(id=search_id)
if search.user != request.user and search.isPublic == False:
return HttpResponse("<p style='text-ali... | 5,290,505 |
def predict_squad(input_file_path, output_file, vocab_file,
doc_stride, predict_batch_size, max_query_length,
max_seq_length, do_lower_case,
version_2_with_negative=False)->int:
"""Makes predictions for a squad dataset."""
eval_examples = read_squad_examples(
... | 5,290,506 |
def solution(A):
"""
This one is a tricky one as the solution requires doing a bit of research on
how to best detect overlapping ranges (a circle projected onto a axis
becomes simply a range from A to B).
The best performance can be achieved with the following approach:
1. First pre-process all... | 5,290,507 |
def patched_novoed_api(mocker):
"""Patches NovoEd API functionality"""
return mocker.patch("novoed.tasks.api") | 5,290,508 |
def create_layer_with_task_specific_linear_heads(num_classes_for_tasks):
"""Returns a `pathnet_lib.ComponentsLayer` with linear task specific layers.
This is a small helper function to create a layer of fully connected
components for multiple classification tasks (with possibly different
numbers of classses). ... | 5,290,509 |
def deserialize_albumentation_transform(tf_dict: dict) -> A.BasicTransform:
"""Deserialize an albumentations transform serialized by
`serialize_albumentation_transform()`.
If the input dict contains a `lambda_transforms_path`, the
`lambda_transforms` dict is dynamically imported from it and passed to
... | 5,290,510 |
def increment(version, major=False, minor=False, patch=True):
"""
Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying pa... | 5,290,511 |
def fpn_classifier_graph(rois, feature_maps, image_meta,
pool_size, num_classes, train_bn=True):
"""Builds the computation graph of the feature pyramid network classifier
and regressor heads.
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
coordinates... | 5,290,512 |
def is_binary_file(path):
"""
:type path: str
:rtype: bool
"""
assume_text = set([
'.cfg',
'.conf',
'.crt',
'.css',
'.html',
'.ini',
'.j2',
'.js',
'.json',
'.md',
'.pem',
'.ps1',
'.psm1',
... | 5,290,513 |
def make_matcher(patterns):
"""Returns a function that evaluates if a path match one of the patterns.
The compared paths are first converted to unicode and decomposed.
This is neccesary because the way `os.walk` read unicode paths could vary.
For instance, it might returns a decomposed unicode string r... | 5,290,514 |
def remove_nesting(dom, tag_name):
"""
Unwrap items in the node list that have ancestors with the same tag.
"""
for node in dom.getElementsByTagName(tag_name):
for ancestor in ancestors(node):
if ancestor is node:
continue
if ancestor is dom.documentElemen... | 5,290,515 |
def test_add_frequency(variant):
"""docstring for test_variant"""
assert variant['frequencies'] == []
variant.add_frequency(name='1000G', value=0.01)
assert variant['frequencies'] == [{'label': '1000G', 'value': 0.01}] | 5,290,516 |
def preprocess(count, df):
"""
Preprocesses CSV file where only words, hashtags, and emojis are kept
"""
num_tweets = len(df)
cleaned_tweets = []
print("Beginning processing of ",num_tweets," tweets at: ",str(datetime.now()))
for i in range(num_tweets):
# cleaned_tweetid ... | 5,290,517 |
def load_data(database_filepath):
"""Parameters:
database_filename: string. Filename of SQLite database containing the cleaned message data.
Returns:
X: Dataframe containing messages used as the predictive column.
Y: Dataframe containing the categories we are trying to predict.
category_... | 5,290,518 |
def validate_truthy(name, val):
"""Validate that ``val`` is truthy.
Validate that ``val`` is truthy according to
https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
Parameters
----------
val : any
Configuration variable to validate.
Returns
-------
boolean... | 5,290,519 |
def extract_articles(wiki_name, wiki_prefix):
"""
Parse wikia dump into json files
:param wiki_name: name of the wikia dump to parse
:type wiki_name: str
:param wiki_prefix: prefix for special pages of this wiki (will be ingored)
:type wiki_prefix: str
"""
# Adapt ingore list
xml_ig... | 5,290,520 |
def fundamentals(
symbol, period="quarter", token="", version="stable", filter="", format="json"
):
"""Pulls fundamentals data.
https://iexcloud.io/docs/api/#advanced-fundamentals
Updates at 8am, 9am UTC daily
Args:
symbol (str): Ticker to request
period (str): Period, either 'annu... | 5,290,521 |
def create_user_profile(sender, instance, created, **kwargs):
"""Create user profile for newly created users."""
if created:
Profile.objects.create(user=instance) | 5,290,522 |
def handler(event, context):
""" Attempt to allocate 4 IP Ranges from a VPC CIDR Block"""
print "Started execution of Autosubnet lambda function..."
print "Function ARN %s" % context.invoked_function_arn
print "Incoming event %s" % json.dumps(event)
global debug
tablename = ''
stack_id = ''... | 5,290,523 |
def create_mask(indexer, shape, data=None):
"""Create a mask for indexing with a fill-value.
Parameters
----------
indexer : ExplicitIndexer
Indexer with -1 in integer or ndarray value to indicate locations in
the result that should be masked.
shape : tuple
Shape of the arra... | 5,290,524 |
def _expand_to_beam_size(data, beam_size, batch_size, state_batch_axis=None):
"""Tile all the states to have batch_size * beam_size on the batch axis.
Parameters
----------
data : A single mx.np.ndarray or nested container with mx.np.ndarray
Each mx.np.ndarray should have shape (N, ...) when st... | 5,290,525 |
def get_simple_gadgets(input_file):
"""Checks if a dump of the gadgets already exists and loads them. Otherwise,
it finds all the gadgets in the current input file, dumps them and also
returns them (simple form)."""
try:
gad_in = util.open_gadgets(input_file, "rb")
simple_gadgets = pickle.load(gad_in)
... | 5,290,526 |
def warningIndex():
"""
Build an object that is a wrapper around the warning channel index from the C++
extension. i.e. {pyre::journal::warning_t::index_t}
"""
#
return Index(lookup=journal.lookupWarningInventory, inventory=Enabled) | 5,290,527 |
def gen_lm1b_train_dataset(file_pattern, num_step):
"""
Returns: The training dataset (tf.data.Dataset) that has been repeated
and shuffled
"""
file_names = []
for file_name in glob.glob(file_pattern):
file_names.append(file_name)
if not file_names:
raise ValueError
# cre... | 5,290,528 |
def setup():
""" creates necessary c-level types
"""
names = populate_inttypes()
result = []
for name in names:
tp = platform.types[name.upper()]
globals()['r_' + name] = platform.numbertype_to_rclass[tp]
globals()[name.upper()] = tp
tpp = lltype.Ptr(lltype.Array(tp, ... | 5,290,529 |
def profile_redirect():
"""In use to redirect after login complete.
Flask-login does not allow us to redirect dynamically to the current
language so we set that fake view to proper redirect.
"""
# Do not use `current_user.detail_url` here as we do not have
# a current language yet, hence guessi... | 5,290,530 |
def get_openapi_description(endpoint: str, method: str) -> str:
"""Fetch a description from the full spec object."""
return openapi_spec.openapi()["paths"][endpoint][method.lower()]["description"] | 5,290,531 |
def union(coords_list):
"""
Combine the given coordinates by collecting the unique, sorted coordinate values in each dimension.
Arguments
---------
coords_list : list
List of :class:`Coordinates`.
Returns
-------
coords : :class:`Coordinates`
Coordinates wit... | 5,290,532 |
def DrawGeometryAddVertexBuffers(builder, vertexBuffers):
"""This method is deprecated. Please switch to AddVertexBuffers."""
return AddVertexBuffers(builder, vertexBuffers) | 5,290,533 |
def get_audio_features_dictionary(tracks: List) -> Dict:
"""Short summary.
Parameters
----------
tracks : List
Description of parameter `tracks`.
Returns
-------
Dict
Description of returned object.
"""
LIMIT = 100
track_ids = [d['track']['id'] for d in track... | 5,290,534 |
def test_handle_team_event_delete_team(team_deleted_payload):
"""Test that teams can be deleted if they are in the db."""
mock_facade = mock.MagicMock(DBFacade)
webhook_handler = TeamEventHandler(mock_facade)
rsp, code = webhook_handler.handle(team_deleted_payload)
mock_facade.delete.assert_cal... | 5,290,535 |
def run_post_order(self):
"""A function that can be bound to the `run` property of any TreeSearch
instance dynamically. This would replace the self with a pointer to that
instance making it behave like an instance method.
"""
print("Running a Post-Order DFS search on {}".format(
self.type)) | 5,290,536 |
def run_ntp(temps, tous):
""" Fonction qui permet de lancer le test NTP
Paramètres : temps, un int et tous un boolean
Return : un tuple de int, (nb_test, test_ok)
"""
# Initialisation des variables
sec = 0
num_lines = 0
thread_time = temps
test_ok = 0
nb_test = 0
if ... | 5,290,537 |
def get_scan_info(tod=None, az=None, ctime=None):
"""
Analyze az info (for tod, or pass in an az and ctime).
Returns a struct with results.
"""
if az is None:
az = tod.az
if ctime is None:
ctime = tod.ctime
output = moby2.libactpol.analyze_scan(
numpy.asarray(az, dty... | 5,290,538 |
def __update_categorical(self, condition, values):
"""
Returns an updated version of this column.
All entries for which the corresponding **condition** is True,
are updated using the corresponding entry in **values**.
Args:
condition (Boolean column): Condition according to which the updat... | 5,290,539 |
def epsilon_greedy(epsilon=None):
"""An epsilon-greedy distribution."""
def sample_fn(key: Array, preferences: Array, epsilon=epsilon):
return distrax.EpsilonGreedy(preferences, epsilon).sample(seed=key)
def probs_fn(preferences: Array, epsilon=epsilon):
return distrax.EpsilonGreedy(preferences, epsilon... | 5,290,540 |
def cosine_similarity(topics, segmented_topics, per_topic_postings, measure, gamma, num_docs):
"""
This function calculates the indirect cosine measure. Given context vectors
_ _ _ _
u = V(W') and w = V(W*) for the word sets of a pair S_i = (W', W*) indirect
... | 5,290,541 |
def REPLACE(
old_text: func_xltypes.XlText,
start_num: func_xltypes.XlNumber,
num_chars: func_xltypes.XlNumber,
new_text: func_xltypes.XlText
) -> func_xltypes.XlText:
"""REPLACE replaces part of a text string, based on the number of
characters you specify, with a different text ... | 5,290,542 |
def main(argv):
"""Parses the arguments and starts the program."""
global username, password, openssl, forwardAddr, datastoreKey
try:
opts, args = getopt.getopt(argv, "hl:u:p:f:", ["help","location=","username=","password=","forward="])
except getopt.GetoptError:
usage()
... | 5,290,543 |
def _remove_duplicate_paths(
path_list: List[ShortestPath]
) -> List[ShortestPath]:
"""Remove each duplicated path from the given list and return a new path
list."""
# Map each unique path to its stringified action list.
unique_path = {}
for path in path_list:
# Stringify the path's MCS ... | 5,290,544 |
def link_other(label, url, path, wrapper=SPAN, **kwargs):
"""
Only wrap label in anchor if given target URL, ``url``, does not match the
``path``. Given a label, this function will match the page URL against the
path to which the anchor should point, and generate the anchor element
markup as necessa... | 5,290,545 |
def report_to_github(repo, pull_request, sha, suite, docs):
"""
Report test results to Github
:param repo: repo name
:param pull_request: pull request number
:param sha: pull request SHA
:param suite: Test suite
:param docs: documentation of statuses
:return: nothing
"""
if... | 5,290,546 |
def _moon_ul_alt(observer, moon, t):
"""Returns the altitude of the moon's upper limb in degrees when seen from
observer at terrestrial time t.
Calculates the moon's apparent semidiameter from the location of
``observer``
"""
moon_distance = observer.at(ts.tt(jd=t)).observe(moon).apparent(... | 5,290,547 |
def prob5(n):
"""Return a sparse n x n tridiagonal matrix with 2's along the main
diagonal and -1's along the first sub- and super-diagonals.
"""
raise NotImplementedError("Problem 5 Incomplete") | 5,290,548 |
def sort_files(curr_dir: str):
"""Setting up drift evaluation settings.
Function for setting up drift evaluation settings like output
filename, getting file lists etc.
Parameters
----------
curr_dir : str
Returns
-------
measlist : list of str
"""
curr_dir = DirPerkeo(cu... | 5,290,549 |
def test_s2_date_exceptions():
"""Tests if the expected exceptions are properly raised."""
with pytest.raises(ValueError, match="Start date out of range"):
search.sentinel2(22, "K", "HV", start_date=datetime(2014, 1, 1))
with pytest.raises(ValueError, match="Invalid date range"):
search.sen... | 5,290,550 |
def fisher_exact_test(c1, c2, c3, c4) -> StructExpression:
"""Calculates the p-value, odds ratio, and 95% confidence interval with Fisher's exact test for a 2x2 table.
Examples
--------
.. doctest::
>>> hl.eval_expr(hl.fisher_exact_test(10, 10,
... 10,... | 5,290,551 |
def SBHostOS_ThreadDetach(*args):
"""SBHostOS_ThreadDetach(thread_t thread, SBError err) -> bool"""
return _lldb.SBHostOS_ThreadDetach(*args) | 5,290,552 |
def Columns(objects):
"""Returns a padded Urwid Columns object that is left aligned."""
# Objects is a list of widgets. Widgets may be optionally specified
# as a tuple with ('weight', weight, widget) or (width, widget).
# Tuples without a widget have a weight of 1."""
return urwid.Padding(Tab... | 5,290,553 |
def addDynamic(*args, **kwargs):
"""
Makes the "object" specified as second argument the source of an existing field or emitter specified as the first
argument. In practical terms, what this means is that a field will emanate its force from its owner object, and an
emitter will emit from its owner objec... | 5,290,554 |
def splitall(path):
"""
Split a path to a list.
Example:
>>>splitall('/public/home/user/code')
['public','home','user','code']
"""
allparts = []
while True:
path, p1 = op.split(path)
if not p1:
break
allparts.append(p1)
allparts = allparts... | 5,290,555 |
def _insert_entry_node(entry_node, way_nodes):
""" insert node reference in the correct position of way_nodes """
insert_position = _find_insert_position(entry_node, way_nodes)
way_nodes.insert(insert_position, entry_node)
return way_nodes | 5,290,556 |
def diff_hostlogg(params1, params2):
"""Differnece in parameters when param2teff changes bu +100"""
rvs = [0]
gammas = [0]
s1 = combine_spectrum(params1, params2, rvs, gammas, plot=False).squeeze()
params_new = [params1[0], params1[1]+0.5, params1[2]]
s2 = combine_spectrum(params_new, params2, r... | 5,290,557 |
def files_import(tenant_url, access_token, source, destination):
""" Imports a remote URI to a remote storage system
If 'source' is an agave source then prefix the uri with 'agave://'. For
example, source = 'agave://data-sd2e-community/test.txt'.
"""
# Set request url.
endpoint = "{0}/{1}/{2}"... | 5,290,558 |
def task__iso_digest() -> types.TaskDict:
"""Compute the SHA256 digest of the ISO."""
return helper.Sha256Sum(
input_files=[ISO_FILE],
output_file=config.BUILD_ROOT/'SHA256SUM',
task_dep=['_iso_build']
).task | 5,290,559 |
def load_file(filename : str, *, timeout:Optional[float] = None) -> None:
"""Load a filename as a Cryptol module, like ``:load`` at the Cryptol
REPL.
"""
__get_designated_connection().load_file(filename, timeout=timeout) | 5,290,560 |
def test_tests_were_collected(request: str):
"""
@param request: “Requesting” fixtures
"""
assert len(request.session.items) > 1 | 5,290,561 |
def test_fbeta_score_no_prediction():
"""Test of `fbeta_score` with no prediction."""
y_pred = np.array([0])
y_true = np.array([1])
assert fbeta_score(y_pred, y_true, 0.5) == 0 | 5,290,562 |
def scenario_folder(model_code, scenario):
"""
Path to the folder of the given scenario.
:param model_code: code of the model
:param scenario: name of the scenario
"""
return model_folder(model_code) + scenario + _SEP | 5,290,563 |
def make_grid_2d(numPix, deltapix, subgrid_res=1):
"""
creates pixel grid (in 2d arrays of x- and y- positions)
default coordinate frame is such that (0,0) is in the center of the coordinate grid
:param numPix: number of pixels per axis
:param deltapix: pixel size
:param subgrid_res: sub-pixel ... | 5,290,564 |
def asNormalizedJSON(value):
"""Answer the value as normalized object, where all values are converted into
base objects, dict, list and string.
>>> src = dict(aa='bb', cc=[1,2,3,4], dd=dict(ee=123, ff='ABC'), gg={3,4,5,5,6,6,7,7})
>>> result = asNormalizedJSON(src)
>>> sorted(result.keys())
['a... | 5,290,565 |
def months_of_buffer():
"""
Real Name: Months of Buffer
Original Eqn: INTEG ( Income-Expenses, Initial Buffer)
Units: Months
Limits: (None, None)
Type: component
Subs: None
This is the stock at any given time of the money in the bank, or remaining
familial goodwill, etc.
"""... | 5,290,566 |
def test_recwalk():
""" aux: test recwalk() """
def list_paths_posix(recwalk_result):
""" helper function to convert all paths to relative posix like paths (to ease comparison) """
return [auxf.path2unix(os.path.join(os.path.relpath(x, pardir),y)) for x,y in recwalk_result]
indir = path_samp... | 5,290,567 |
def format_trim_dims(data, dim=None, seed=0,
encode=encode_aa_seq_atchley,
count=encode_count_binary):
""" Fill in the zeros or trim extra dimensions
Args: (x, c, y) and the expected dimension
Returns: (xs, cs, ys)
"""
if dim is no... | 5,290,568 |
def RimportLibrary(lib_name):
""" Helper function to import R libraries
using the rpy2 binder
"""
if not rpackages.isinstalled(lib_name):
base.source("http://www.bioconductor.org/biocLite.R")
biocinstaller = rpackages.importr("BiocInstaller")
biocinstaller.biocLite(lib_name)
... | 5,290,569 |
def to_ea(seg, off):
"""
Return value of expression: ((seg<<4) + off)
"""
return (seg << 4) + off | 5,290,570 |
def tf(seconds):
"""
Formats time in seconds to days, hours, minutes, and seconds.
Parameters
----------
seconds : float
The time in seconds.
Returns
-------
str
The formatted time.
"""
days = seconds // (60*60*24)
seconds -= days * 60*60*24
hours = sec... | 5,290,571 |
def _set_frame(frag):
"""Set the HSPFragment frames (PRIVATE)."""
frag.hit_frame = (frag.hit_start % 3 + 1) * frag.hit_strand
frag.query_frame = (frag.query_start % 3 + 1) * frag.query_strand | 5,290,572 |
def main():
""" Handels command line args. """
debug = False
usage = dedent("""\
%prog [options]
Updates a server's sources, vendor libraries, packages CSS/JS
assets, migrates the database, and other nifty deployment tasks.
""".rstrip())
options = OptionParser(usage=usag... | 5,290,573 |
def is_prime(n):
"""
Returns True if `n` is a prime number.
Uses a sieve based approach.
"""
if n < 2:
return False
ps = primes()
p = next(ps)
while p * p <= n:
if n % p == 0:
return False
p = next(ps)
return True | 5,290,574 |
def depth_search_tree(node, depth: int = 0, parent=None):
"""
Yields all taxonomy tree nodes
:param node:
:param depth:
:param parent:
:return:
"""
if node is None:
return
yield node, depth, parent
for child in node["children"]:
yield from depth_search_tree(chil... | 5,290,575 |
def validate_sampleSet(queryDict):
"""
validate the sampleSet input.
returns a boolean isValid and a text string for error message, None if input passes validation
Note: Input length willl not be validated since maxLength has been specified in the form.
"""
logger.debug("sample_validator.valida... | 5,290,576 |
def run(file_path):
"""Runs the file path as a M# application"""
def interpret(file):
if pathlib.Path(file).suffix is not ".m#":
raise
source = ""
with open(file, 'r') as stream:
for content in stream:
content = content.lower().strip()
... | 5,290,577 |
def test_no_args_errors(capsys):
"""Test that an error is reported when no expression is provided."""
with pytest.raises(SystemExit) as exinfo:
main([])
capture = capsys.readouterr()
assert capture.out == ""
assert capture.err.endswith("error: the following arguments are required: regex\n")
... | 5,290,578 |
def greyed(color, colorDict=None):
"""Convert color code '#RRGGBB' and '#RRGGBBAA' to a grey color
(R, G, B, A).
It also supports RGB(A) from uint8 in [0, 255], float in [0, 1], and
QColor as color argument.
:param str color: The color to convert
:param dict colorDict: A dictionary of color na... | 5,290,579 |
def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for CBOW training objective."""
contexts_data, contexts_row, contexts_col = contexts
centers = mx.nd.array(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(contexts_data, (contexts_row, contexts_... | 5,290,580 |
def handle_data(data: str) -> Tuple[str, str, str] or None:
"""
Cleansing of data from the port
:param data: line from Serial port
:return: None
"""
if data not in ['', None]: # data can be empty string quite often
data = data.rstrip()
try:
if len(data) == 3:
... | 5,290,581 |
def parse_lines(lines, start_time=None, verbose=False):
"""
Args:
start_time: parse only log time after the specified time string, such as "1998-08-23 21:12:08"
Yields:
{}
"""
if not lines:
yield None
# LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %O \"%{Referer}i\"... | 5,290,582 |
def is_distribution_editable(name):
"""Is distribution an editable install?"""
distribution = pkg_resources.get_distribution(name)
return any(
os.path.isfile(
os.path.join(location, distribution.project_name + '.egg-link'),
)
for location in sys.path
) | 5,290,583 |
def run_subvalidator(text):
"""Checks if the run statement is properly formatted
Parameters
----------
text : str
input statement
"""
valid_keywords = ['logger', 'threads']
valid_logger_values = ['csv', 'sqlite']
kwargs = dict([kwarg.split('=') for kwarg in text.split(None)[1:]... | 5,290,584 |
def test_lambda_handler(monkeypatch: MonkeyPatch) -> None:
"""Test the main method of lambda function"""
read = MagicMock()
read.read.return_value = '[{"solidRating": 1}]'
urlopen = MagicMock(return_value=read) # type: ignore
monkeypatch.setattr(lambda_function.settings, "MSW_API", "my_key")
mo... | 5,290,585 |
def compute_average_pose(poses: typing.Iterable[Transform]) -> Transform:
"""
Given a collection of poses, find the average pose
:param poses: A collection of Transform objects to average
:return: The average pose, as a Transform
"""
pose_data = [(pose.location, pose.rotation_quat(w_first=True))... | 5,290,586 |
def test_path_list_wildcard(solar_system):
"""### Wildcard as an Index."""
# The **wildcard** word can be used as a list index. It is useful for iterating over attributes.
all_outer = [planet for planet in find(path.star.planets.outer[wildcard].name, solar_system)]
assert all_outer == ["Jupiter", "Sa... | 5,290,587 |
def predict_tile(model,
raster_path=None,
numpy_image=None,
patch_size=400,
patch_overlap=0.05,
iou_threshold=0.15,
return_plot=False):
"""For images too large to input into the model, predict_tile cuts the
i... | 5,290,588 |
def process_keyfile(ctx, param, value):
"""Read keyfile and load JSON."""
if value is not None:
try:
auth_info = json.load(value)['twitter']
except:
click.echo('A valid JSON keyfile is required!')
raise
return auth_info
else:
return value | 5,290,589 |
def login_link(request):
"""
This assumes your login link is the Shibboleth login page for your server
and uses the 'target' url parameter.
"""
full_path = quote(request.get_full_path())
login = reverse('shibboleth:login')
ll = "%s?target=%s" % (login, full_path)
return {'login_link': ll... | 5,290,590 |
def gui_browse(type, heading, shares="files", mask="", enablemultiple=False):
"""
Let user select something filesystem related (depends on "type")
"""
dialog = xbmcgui.Dialog()
return dialog.browse(type, heading, shares, mask, enablemultiple) | 5,290,591 |
def score_all(subject_list, goal):
"""
Subject_list can either be a normal list or a tuple list.
Return a dictionary of each subject as a tuple list paired up with its score.
"""
if type(subject_list[0]) is list:
subject_list = tuple(tuple(subject) for subject in subject_list)
ret = ... | 5,290,592 |
def splot_rgb_lines(path_evr = None,
elements = [[],[],[]],
orbs = [[],[],[]],
labels = ['','',''],
ax = None,
skipk = None,
elim = [],
max_... | 5,290,593 |
def scrape(username, password, year):
"""
Scrape OSIRIS
:param username: Username to log in with
:param password: Password to log in with
:param year: Year to scrape
:return: void
"""
try:
print("OSIRIS course list scraper")
print("Copyright (c) %d - Luke Paris (Paradoxis... | 5,290,594 |
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar."""
assert dateIsBefore(year1, month1, day1, year2, month2, day2)
days = 0
while dateIsBefore(... | 5,290,595 |
def process_layer_parameters(layer, logger, caffe_net,
arg_params, aux_params, log_format):
"""Check layer weights translated to caffe
Args:
layer : layer generated by caffe dag
logger: logger to log
caffe_net: caffe network
arg_params: Argument para... | 5,290,596 |
def exif_info2time(ts):
"""
changes EXIF date ('2005:10:20 23:22:28') to number of seconds since 1970-01-01
Borrowed from http://code.activestate.com/recipes/550811-jpg-files-redater-by-exif-data/
"""
tpl = time.strptime(ts + "UTC", "%Y:%m:%d %H:%M:%S%Z")
return time.mktime(tpl) | 5,290,597 |
def _MakeServerArgs(channel: communication.Channel,
interface: interface_registry.Interface) -> List[str]:
"""Returns the args to run the unprivileged server command."""
named_flags = [
"--unprivileged_server_pipe_input",
str(channel.pipe_input.Serialize()),
"--unprivileged_se... | 5,290,598 |
def test_twilio_to_non_mobile_number(get_twilio):
"""
GIVEN a valid Twilio object
WHEN sending text to a non-mobile number
THEN assert error "to" number is not a mobile number
"""
t = get_twilio
t.to = '+15005550009'
with pytest.raises(MessageSendError) as resp:
t.send()
re... | 5,290,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.