content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def heliocentric_velocity_corr_kms(ra, dec, mjd) :
"""
Heliocentric velocity correction routine.
See http://docs.astropy.org/en/stable/coordinates/velocities.html for more details.
The computed correction can be added to any observed radial velocity to determine
the final heliocentric radial velocit... | 2828c6aef538407b41f46498318d01ad8fd76935 | 65,632 |
def rev_parse(rev: str, *, abbrev: bool = False) -> str:
"""Compute the hash for a revision.
Args:
rev: A Git revision in any format known to the Git CLI.
abbrev: Return a branch or tag name instead of a git sha
Returns:
ref: A 40 character hex-encoded SHA-1 hash representing the I... | 3bd38dd29235593d93a1f55fd2422504f7367295 | 65,633 |
def generate_key():
"""Generate a MongoDB ObjectID-compatible string."""
return str(ObjectId()) | 72524f8552703af2ace52d937f3dec5279c09a49 | 65,634 |
from typing import List
from typing import Optional
def TabWidget(
tabs: List[Tab],
owner: Optional[QWidget] = None,
name: Optional[str] = None,
) -> QTabWidget:
"""[summary]"""
tabWidget = QTabWidget()
for tab in tabs:
tabWidget.addTab(tab.widget, tab.label)
return tabWidget | b9db8694c4dcf5ae25e9ed09a1c2f21db7669fe1 | 65,635 |
def isclassof(classinfo):
"""Creates a partial application of isinstance.
Args:
classinfo: The classinfo argument for isinstance.
Returns:
(Callable[[object], bool]): A function `f(obj)` that returns
`isinstance(object, classinfo)`
"""
return partial(flip(is... | b0dec9b1ec6f8dc4368e717232cfd1fa49cc8862 | 65,636 |
def generate_population_of_solutions():
""" Generate a number of random solutions and sort them by best first """
solutions = []
for i in range(1, POPULATION_NUMBER):
solution = generate_random_solution()
res = solution.test_solution()
solutions.append((solution, res))
return s... | f24421b88329eff0b2221b3755daa88ec2cc20ff | 65,637 |
def get_client_permissions(client_id: str) -> Permissions:
"""Return effective client permissions."""
client = Session.get(Client, client_id)
if not client:
raise x.ODPClientNotFound
return {
scope.id: '*' if not client.provider else [client.provider_id]
for scope in client.scop... | 288948ea1b0373957e902648244f1af24eb967cf | 65,638 |
def to_unicode(s):
"""Convert str s to unicode
:param str s: string
:return: "unicode" version of s (unicode in py2, str in py3)
"""
if PY_VERSION == 2:
s = unicode(s)
return s | 38e792f3599b272907d28ed8a9d8b822fc6ea5b1 | 65,639 |
def question_data_path(instance, filename):
"""Returns Questions data path."""
# question data will be uploaded to MEDIA_ROOT/question_<id>/<filename>
return 'question_{0}/{1}'.format(instance.title.replace(" ", "_"),
filename)
# return 'question_{0}/{1}'.format(inst... | dc268bb4e3ff0d00ac3bb8ba8299ce0629951487 | 65,641 |
from typing import Counter
def get_dice_frequencies(throw):
"""
Returns a dictionary with the counts of unique dice, pairs, three of a kind etc
Examples:
'222333' returns {'Three of a kind': ['2', '3']}
'123344' returns {'Pair': ['3', '4'], 'Single': ['1', '2']}
"""
# use the Counter funct... | 4f7962d0b35dd37bf2be28bb32d385e5c703b0f7 | 65,642 |
def load(modulefile, flags=''):
"""Load modulefile(s) into the shell environment."""
return module('load {0} {1}'.format(modulefile, flags)) | 1ba43fa75a24627e06bde3f5f8129b85e5a05420 | 65,643 |
def load_hashbits(filename):
"""Load a hashbits object from the given filename and return it.
Keyword argument:
filename -- the name of the hashbits file
"""
hashtable = _Hashbits(1, [1])
hashtable.load(filename)
return hashtable | 85aac0cb53d6f0d71257da66c720d4418bae651c | 65,644 |
def assert_api_call(
client,
url,
payload,
expected,
expect_authenticated=False,
expect_status=status.HTTP_200_OK,
use_defaults=True,
):
"""Run the API call and perform basic assertions"""
assert bool(get_user(client).is_authenticated) is False
response = client.post(reverse(url... | 2ea1677485f8662f0d6f55b1e3adb45d37ceb02c | 65,645 |
def find_artist(name):
"""
Given an artist name, return an artist object
from search results.
returns None if no artist is found.
"""
q = 'artist:{}'.format(name)
s = get_spotify()
result = s.search(q, limit=1, type='artist', market=user_country())
items = result['artists']['items']
... | 61511c97de487055671a079560eb71ac2d318829 | 65,646 |
import builtins
def float(name, default=None, allow_none=False, fallback=None):
"""Get a string environment value or the default.
Args:
name: The environment variable name
default: The default value to use if no environment variable is found
allow_none: If the return value can be `Non... | 241a79882f11b97ac725660effce11dc67aa0c64 | 65,647 |
def wrappable_filter(value, autoescape=None):
"""
Places zero-width breaking spaces in text to allow it to wrap
before a underscore (_) or fullstop (.). The browser will use this
as a hint as to where to wrap the text if required.
"""
# Escape the input text so that it's safe to display
... | 5d6b61c55116093bd3a9642b217740e222e01289 | 65,649 |
def by_name(name):
"""Return a platform object that corresponds to the given name or None
if there is no match.
Args:
name (str): name of the platform
"""
platform_cls = cls_by_name(name)
return platform_cls() if platform_cls else None | ab7394df8ee50508d4e8e1a0f86f7d7ac380243c | 65,650 |
def _compscale(data):
"""
Automatically computes a scaling for the wavefunctions in the plot.
Args:
data (dict): The data neccesarry for computing the scale factor. Needs
to contain 'wfuncs' and 'energies'.
Returns:
scale (float): The computed scale.
"""
wfuncs = d... | 0c33313c86c38568a1713de28e5f5b44b2b0207c | 65,651 |
def get_nodes(G,**kwargs):
"""
search nodes having the given attributes
:param G: graph where nodes are searched
:param kwargs: atom= , in_cycle=
:return: a list of nodes
:rtype: list
"""
nodes=[]
if G!=None:
for n in G.nodes():
match=True
for k,v... | 058475407fd0ad7104fb9eb90a8118ee130ae98f | 65,652 |
def deviceagents():
"""Get all DeviceAgent data from the DB.
Args:
None
Returns:
Agent data
"""
# Get data
data = db_deviceagent.get_all_device_agents()
# Return
return jsonify(data) | 1d6313cad1ce5ad22b9dcec0d925ed5a0c4b8481 | 65,653 |
from typing import OrderedDict
import tarfile
import re
def import_votes_internal(
vote_type,
principal,
domain,
session,
date_,
dataset_name,
expats,
vote,
municipality
):
"""
Import test datasets in internal formats. For one vote, ther... | 4421f33103a6e71a1e3e78891a852efdfce1bb60 | 65,654 |
def scipy_sparse_to_sympy(m, **options):
"""Convert a scipy.sparse matrix to a sympy matrix."""
return Matrix(m.todense()) | 4c7ad5530f89a31767fa782c6c4f2a69239cd350 | 65,656 |
from numpy.lib.stride_tricks import as_strided
def cross_correlation(x, y, maxlag):
"""
Cross correlation with a maximum number of lags.
`x` and `y` must be one-dimensional numpy arrays with the same length.
This computes the same result as
numpy.correlate(x, y, mode='full')[len(a)-maxlag-1:... | ef881c37e13ca39bb80a14c65bd2dd0767172e0c | 65,657 |
def part1(bags):
"""
>>> part1(read_input())
254
"""
reverse = defaultdict(list)
for colour, bags in bags.items():
for (_, bag) in bags:
reverse[bag].append(colour)
queue = ['shiny gold']
colours = set()
while queue:
colour = queue.pop(0)
for ... | bd8c1e91fbd49203aee1eaca0a4697553d9cf630 | 65,658 |
def count(name: str = "") -> "Expr":
"""
Count the number of values in this column
"""
return col(name).count() | 0573bc477ab5301391496e07a4757c453c077978 | 65,659 |
from typing import List
def largest_less_than(indexes: List[int], line_num: int, pos: int) -> int:
"""Replacement func for python str.rfind using indexes """
return indexes[line_num - 1] if indexes and count_occurrences(indexes, pos) else -1 | 7320eaacaa395778590eb0c3077ae0223b82166f | 65,660 |
from functools import reduce
def equal(list_):
"""
Returns True iff all the elements in a list are equal.
>>> equal([1,1,1])
True
"""
return reduce(
lambda a, x: a and (x[0] == x[1]),
zip(list_[1:], list_[:-1]),
True,
) | 65b8a9b5652ecd6b3cc9709dd7e56b4e1258caf4 | 65,661 |
def encode_query_string_for_alb(params: QueryParams) -> bytes:
"""Encode the query string parameters for the ALB event. The parameters must be
decoded and then encoded again to prevent double encoding.
According to the docs:
"If the query parameters are URL-encoded, the load balancer does not deco... | 2dc0ddafff93d55148c60a1baaf57a25f28daf42 | 65,662 |
import inspect
def get_code():
"""
Return source code of Fibonacci sequence logic's implementation.
"""
return inspect.getsource(get_sequence) | f164f873d591650df55cb7dd08546f261a5582a7 | 65,663 |
import six
def swapaxes(a, axis1, axis2):
"""Swaps the two axes.
Args:
a (cupy.ndarray): Array to swap the axes.
axis1 (int): The first axis to swap.
axis2 (int): The second axis to swap.
Returns:
cupy.ndarray: A view of ``a`` that the two axes are swapped.
.. seeals... | 25b007ad3a749ff27a37d6b12060c95885aed165 | 65,664 |
from datetime import datetime
import tqdm
def scrape(league):
"""Scrape data
:param league: league ID
"""
# Start timer
startTime = datetime.now()
# Scrape player IDs and teams from a public league
data = set()
groups = ["QB", "WR", "RB", "TE", "K", "DEF"]
s = create_session()
... | 9180c9d007600d8b7ee826f7befd2143f491ad3c | 65,666 |
def fit_potential_to_snap(snap, rho_func, m_range=(1, 20), m_bins=50, q=None,
return_p=False, *args, **kwargs):
"""Fit an ellipsoidal density function of the form rho_func(m,p[0],p[1],....) to the snapshot.
Returns pot : the best fitting potential.
Must supply initial parameters f... | 65025e1763da04791d48d1c27d93e5869779e757 | 65,667 |
import copy
def process_dataframe_dft(df, data_path = '/data/utils', origin=False, dim=False, AX_sub_only=False):
""" Featurize the preprocessed NiCOLit dataset with DFT and physico-chemical descriptors already computed and stored as csv files and return additionnal data as yields, DOIs, coupling partner class an... | 044f9ba411cb73d52194bdcf696301cdf1b1c915 | 65,668 |
import requests
def commit_transaction(rivine_explorer_address, rivine_explorer_api_password, transaction):
"""
Commits a singed transaction to the chain
@param transaction: Transaction object to be committed
"""
data = transaction.json
url = '{}/transactionpool/transactions'.format(rivine_ex... | 235779ac09a4f8350847c17de2a1f86fda15671b | 65,669 |
def test_expand_dims_grad():
""" test_expand_dims_grad """
input_tensor = Tensor(np.array([[2, 2], [2, 2]]))
expand_dims = P.ExpandDims()
def fn(x):
output = expand_dims(x, 0)
return output
out = fn(input_tensor)
gfn = grad_all_with_sens(fn)
sens = Tensor(np.ones_like(out.a... | 7ba132785f3299b4b2f03a298ef04e8cee184a4a | 65,670 |
import trace
def plot_eigenvalues(mc: tmc, dpi: int = 100) -> oplot:
"""
The function plots the eigenvalues of the Markov chain on the complex plane.
:param mc: the target Markov chain.
:param dpi: the resolution of the plot expressed in dots per inch (by default, 100).
:return: None if Matplotl... | 4b9ca996d7cbb6cf243d02da55cd9a410fa4c15c | 65,671 |
from typing import List
def _effective_dir_path_exists(mb: MACIDBase, start: str, finish: str, effective_set: List[str]) -> bool:
"""
checks whether an effective directed path exists
"""
start_finish_paths = find_all_dir_paths(mb, start, finish)
for path in start_finish_paths:
if _path_is... | e81ff58c400748e54058f26de1db9151944ca1ae | 65,672 |
def dequeue(queue_id, output_type, output_shape, queue_name=""):
""" Dequeue. """
result = gen_npu_cpu_ops.dequeue(
queue_id=queue_id,
output_type=output_type,
output_shape=output_shape,
queue_name=queue_name)
return result | 02c7b0bd1d94873d90bcccbcc12886c1629dcaa8 | 65,673 |
def yields_from_leung_nomoto_2020(feh):
"""
Supernova data source: Leung & Nomoto, 2020, ApJ, Vol 888, Issue 2, Id 80
The seven datasets are provided for Z/Zsun values of 0, 0.1, 0.5, 1, 2, 3 and 5.
Using Zsun = 0.0169 the corresponding FeH values are -1, -0.301, 0.0, 0.301, 0.4771 and 0.69897.
We u... | 21ad4bf1eab2193a97f98594c60a5e3db18e4a74 | 65,674 |
from pathlib import Path
def add_path_to_local_dataset_list(paths_list: list) -> Path:
"""Take a list with folders and/or file names and add it to the local dataset path
Args:
paths_list: A list with folders and/or file needed to be added to the path
Returns:
The full pat... | 5c0144370a62082c9e14e96b72d2b69c1838c6b3 | 65,675 |
def stocking_event_dict(db):
"""return a dictionary representing a complete, valid upload event.
This dictionary is used directly to represent a stocking event, or
is modified to verify that invalid data is handled appropriately.
"""
event_dict = {
"stock_id": None,
"lake": "HU",
... | bed85f03438700754d52a0d858d7a41ee5079406 | 65,676 |
def highest_hpx_level_from_largest_hpx(max_hpx):
"""
given the largest hpx value it returns the corresponding hpx level
"""
for i in range(12):
if (max_hpx < number_of_healpixels(i)):
break
return(i) | ca1df1b87582e43c4d9b71399c3d54c2d1e5bd51 | 65,677 |
import socket
def get_device_description():
"""
This info is later shown in the "Open sessions" overview in the client. Should be something so the user knows where
this session is coming from.
:return:
:rtype:
"""
return 'Console Client ' + socket.gethostname() | 2881b58e5854156adc57fb834284d55fc961cc55 | 65,678 |
import torch
def preemphasis(signal, coeff=0.95):
"""perform preemphasis on the input signal.
:param signal: The signal to filter.
:param coeff: The preemphasis coefficient. 0 is no filter, default is 0.95.
:returns: the filtered signal.
"""
signalroll = torch.roll(signal, 1)
signalroll[0]... | 2bb30b13b737554471b45ad4dfcdb3a5890865fe | 65,679 |
def estLr(meta, cpu=1, plot=False, fout=None):
"""
Estimation the linear relationship between genomic distance and interaction frequency.
"""
ds = Parallel(n_jobs=cpu, backend="multiprocessing")(
delayed(preObs)(meta["data"]["cis"][key]["ixy"], cut=0, binSize=10000)
for key in meta["data... | 6faabec52f157b0ba9afab47859f12010b072721 | 65,681 |
def login(
request: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(configuration.get_db),
):
"""
Login user
Args:
request (OAuth2PasswordRequestForm, optional): OAuth2PasswordRequestForm.
db (Session, optional): Session. Defaults to Depends(configuration.get_db).
... | 7bb60b2b840e367d93fc072e0a085f7490091605 | 65,682 |
def f_3b(beta, x):
""" implicit definition of the circle """
return (x[0]-beta[0])**2 + (x[1]-beta[1])**2 - beta[2]**2 | 960417c0c462f41e0345ae3331c86b820faaa73e | 65,683 |
def dict_to_str(dct):
"""Convert a dict to a string."""
def convert(dct):
for k, v in dct.items():
if isinstance(v, ftrack_api.entity.base.Entity):
v = str(v)
else:
v = repr(v)
yield '{}={}'.format(k, v)
return ', '.join(convert(dct... | 6a8690645ce9d46f2536f508254fc14203327d59 | 65,684 |
def db_keys():
""" Endpoint Function to interact with PupDB's keys() method. """
return {'keys': list(DB.keys())}, 200 | c8f282a10a068e92746f97a1a9ddff5789e63b9a | 65,686 |
import random
def random(states_size, alphabet_size, acceptance=0.5):
"""Constructs a random DFA with "states_size" states and "alphabet_size" inputs. Each
transition destination is chosen uniformly at random, so the resultant DFA may have
unreachable states. The optional "acceptance" parameter indicates ... | 21b61f986231e470df33a8c48dd21163feab04f0 | 65,688 |
from typing import Union
from typing import Iterable
def predict_from_binary_tree(
X: Union[list, np.ndarray],
children_left: Union[list, np.ndarray],
children_right: Union[list, np.ndarray],
feature: Union[list, np.ndarray],
threshold: Union[list, np.ndarray],
value: Union[list, np.ndarray],
... | 39e447137891705a5b8e1800a0421c1d284edc28 | 65,689 |
def unique_hosts(hosts: str) -> str:
"""
Verify all hosts are unique.
If more than one host is passed to the hosts parameter, ensure no two hosts
are identical as Bobber can't be run concurrently on the same host.
Parameters
----------
hosts : str
A ``string`` of the comma-separate... | 824b1aa6fc590995f77a901a3b3ddcd93160f69d | 65,691 |
def get_zaehlsprengel_gdf(year=2020):
"""
Get geopandas.GeoDataFrame of Zählsprengel districts from Statistik Austria
"""
file = f'data/OGDEXT_ZSP_1_STATISTIK_AUSTRIA_{year}0101.zip'
url = f'http://data.statistik.gv.at/data/OGDEXT_ZSP_1_STATISTIK_AUSTRIA_{year}0101.zip'
if not exists(file):
... | 28d9e6c36b060a440cf77ec6ab4cb9741d4342d1 | 65,693 |
def get_price_current(list_all_tickers: list, symbolTicker: str) -> float:
"""This function returns the current price of an asset
Args:
list_all_tickers (list): List with all assets
symbolTicker (str): Tick base
Returns:
float: returns the current price
"""
result = ... | 04a7d00797b12075b64462b9a8ea585c526c8609 | 65,696 |
def convert_dir_regex_to_dir_prefix_regex(dir_regex):
"""
The patterns used to match directory names (and file names) are allowed
to match a prefix of the name. This 'feature' was unintentional, but is
being retained for compatibility.
This means that a regex that matches a directory name can't be... | bb9843984d9a724380eab2509095fccc03e280e1 | 65,697 |
async def consume_aiter(iterable):
"""consume an async iterable to a list"""
result = []
async for item in iterable:
result.append(item)
return result | 897c8e9380f9c631f2dd8721884ec1ccbe462d48 | 65,699 |
def main():
"""Render the homepage."""
return render_template('index.html') | 1763707c63ef5525370e5d37241c434a8fc0a2ab | 65,701 |
def event_fraction(match_events, Ntimes, shape_list, Nfreqs=None):
"""
Calculates the fraction of times an event was caught by the flagger for
each type of event. Narrowband occupancy levels are calculated over the whole
spectrum, instead of just the channel a particular event may have belonged to.
... | 43d56bfe79246ef5e98beb08ad4ac5171ea44ae1 | 65,702 |
def make_hap_seqs(haps, options):
"""Makes a chromosome sequence for each haplotype"""
seq_h5 = tables.open_file(options.seq)
node_name = "/%s" % options.chrom
if node_name not in seq_h5:
raise ValueError("chromosome %s is not in sequence h5 file" % options.chrom)
seq_node = se... | 239de09be2bbe4b103fcdea2ab05cd2160f0c0bf | 65,703 |
import hashlib
def cluster_name(cluster, build):
"""Return or select a cluster name."""
if cluster:
return cluster
if len(build) < 20:
return 'e2e-%s' % build
return 'e2e-%s' % hashlib.md5(build).hexdigest()[:10] | d2f2fe3d434357237ba9c645f3253447fc4ac953 | 65,704 |
def task_returner(task) -> dict:
"""
* 根据不同的task状态生成不同的返回值
Args:
task:
Returns:
"""
if task.state == "PENDING":
response = {
"state": "empty task",
"info": {"current": 0, "total": 4, "status": "empty task"},
}
elif task.state == "FILL DATA":
... | 9d020f70d2f0a00e1a0042e9cba86e58d41f41e0 | 65,705 |
def group_sum_by_keys(ungrouped, group_key, sum_key):
"""Groups dictionaries by a common value and then returns the sum of
this a second value for each group."""
grouped = group_by_key(ungrouped, group_key)
summed = sum_groups_by_key(grouped, sum_key)
return summed | b648df157abe656bd97c9d6df9f70f7990dbbbb9 | 65,706 |
import ipaddress
def validate_ip(ip):
"""
Checks if an IP address is valid for lookup.
Will return False if an IP address is reserved or invalid.
Resource: https://en.wikipedia.org/wiki/Reserved_IP_addresses
"""
try:
return not ipaddress.ip_address(ip).is_private
except Value... | 5d10a41e6bc6d645cbef24e8e4128baaf67aa997 | 65,710 |
def flatten_dct(obj, separator):
"""
Flattens an objects so deep keys and array indices become concatinated strings
E.g. {a: {b: [1, 3]}} => {'a.b.0': 1, 'a.b.1': 2}
@param {Object} obj The object to flattened
@param {Object} separator Key segment separator, probably either '.' or '__'
@returns ... | 3a25e49f05c6fbe5ada9bec5276744be3e888c45 | 65,711 |
def _connect_to_environment(port, settings):
"""Helper function for connecting to a running dm_memorytask environment."""
if settings.level_name not in MEMORY_TASK_LEVEL_NAMES:
raise ValueError(
'Level named "{}" is not a valid dm_memorytask level.'.format(
settings.level_name))
server_add... | 5ca6e825d685f6186a9d0ea272c0621377e9d304 | 65,712 |
def circlemaker(r=10.):
"""
Creates circle mask of radius r.
"""
# Based on <https://stackoverflow.com/questions/10031580/
# how-to-write-simple-geometric-shapes-into-numpy-arrays>
# Mask grid extent (+1 to ensure we capture radius).
rhext = int(r) + 1
xx, yy = np.mgrid[-rhext:rhext + ... | 4af623ca8d822dfdaab38eed34867a102d46e164 | 65,713 |
def rupture_name_to_id_ix(
ensemble: "gm_data.Ensemble",
erf_ffp: str,
rupture_names: np.ndarray,
):
"""Convertes the rupture names to rupture_id_ix values"""
return rupture_id_to_ix(ensemble, rupture_name_to_id(rupture_names, erf_ffp)) | 33ee98f521892235adb71c07553377029f097c10 | 65,714 |
import six
def convert_unicode(text):
"""If the provided string is a binary string, this filter converts it
to UTF-8 (unicode).
"""
if isinstance(text, str) and six.PY2:
return text.decode("utf8")
else:
return text | 5fc868e11da09444bc285c251e8cbae7dc502d77 | 65,716 |
def extract(opts):
"""
support extraction (checkout) of a mercurial cache into a build directory
With provided extraction options (``RelengExtractOptions``), the extraction
stage will be processed. A Mercurial extraction process will populate a
working tree based off the cached Mercurial repository... | 68f57f6f57b5811d21807c4c45766fba9e7adcb5 | 65,717 |
import time
def eval_metrics(model_ova, X, y, pred, cert_tw, time_cert, deltas, weak_learner, eps_eval, log, n_trials_attack, check_bounds=True):
""" Evaluation metrics for validation and test sets. """
if X.shape[0] == 0: # if no examples provided (e.g., the validation set is empty)
return 1.0, 1.0,... | 5296082cd9cfc070d936fb6000521daacf505a32 | 65,718 |
def graph_from_edgelist(E, directed=False):
"""Make a graph instance based on a sequence of edge tuples.
Edges can be either of from (origin,destination) or
(origin,destination,element). Vertex set is presume to be those
incident to at least one edge.
vertex labels are assumed to be hashable.
"""
g = Grap... | 42831be2a7a868ec86c5244cb5e2faf221f029ea | 65,720 |
def init_symbol_table():
"""
Returns a Python dictionary mapping strings (symbol names) to
integers (address refered to by that symbol), initialized with
all of the Hack assembly predefined symbols.
"""
predefined_symbols = {
'SP': 0,
'LCL': 1,
'ARG': 2,
... | 7a64be8add2565d3dff5302df82088af7b3383e6 | 65,721 |
from operator import mul
def product_using_accumulate(n, term):
"""An implementation of product using accumulate.
>>> product_using_accumulate(4, square)
576
>>> product_using_accumulate(6, triple)
524880
"""
"*** YOUR CODE HERE ***"
return accumulate(mul, 1, n, term) | e9b250ac90bfc6d330fb0510e48d3af391fc7508 | 65,722 |
def _get_balena_os_version(etc_issue_contents):
"""
Return a balenaOS version string such as "2.53.0", given the contents
of the "/etc/issue" file in the etc_issue_contents argument.
"""
m = match('balenaOS (.+?) ', etc_issue_contents)
return m[1] if m is not None else "" | 8d33b37c33c7ff29bf66cf0fc2f7297a4de336aa | 65,723 |
import string
def AddExonInformation(sequence,
exons,
gap_char="-",
mask_lowercase=False,
mask_char="x"):
"""add exon information to an aligned string.
lowercase characters will be masked.
"""
new_chars = []
... | 16f858e5ce62e15d929624ef15a934f4776ed3cc | 65,724 |
def get_sdp_path(doc, subj: int, obj: int):
"""
'Convulsions that occur after DTaP are caused by a fever, and fever may cause headache.'
----> [Convulsions, caused, by, fever]
Get shortest dependency path without networkx lib. Usues spacy's LCA (lowest common ancestor) matrix
Adapted from:https:... | 23f994d17e3b496fe6d8d8dcd06527675c9f0795 | 65,725 |
def hookable(hookable_method):
"""Decorator which checks for corresponding hooks and calls them if they exist
When this decorator is applied to a method, it checks for the existence of `_before_method()`
and `_after_method()` hooks, and calls them before/after the correspdoning method if they do.
This... | 10d9e879feabf73bcfb41615ebe2c1df86a7e395 | 65,726 |
def is_integer(val):
"""Returns whether the given value is an integer.
Args:
val (object): value to check
Returns:
``True`` if the given value is an integer, otherwise ``False``.
"""
try:
val += 1
except TypeError:
return False
return True | ba038448c04b3072c08547c963aa24bf3cbc97b2 | 65,727 |
import re
from typing import Counter
def grant_permission_to_tag(session, tag_id, permission_id, argument=''):
# type: (Session, int, int, str) -> bool
"""
Grant a permission to this tag. This will fail if the (permission, argument) has already
been granted to this tag.
Args:
session(mode... | 57a25a5e2d5db43f60d15ba81062919d6ca1dd28 | 65,728 |
def split_one_block(data, expected_hdr=None):
"""Extract a sequence of MPEG audio frames from a single block of data.
Args:
data: A data buffer containing the data to be split into MPEG frames.
Returns:
A list of (hdr, data_buffer) pairs.
If 'hdr' is None, data buffer contains non-MPEG-a... | 3ebc217d85772f926732f1f79e1f6b7d36b924a6 | 65,729 |
def plot_acq_function_2d(
acq_func: AcquisitionFunction,
mins: TensorType,
maxs: TensorType,
grid_density: int = 20,
contour=False,
log=False,
title=None,
xlabel=None,
ylabel=None,
figsize=None,
):
"""
Wrapper to produce a 2D/3D plot of an acq_func for a grid of size grid... | 06a7805f4180e82b957c62f5532c48bd8f245777 | 65,730 |
async def get_task(
user: UserEntity = Depends(dep_current_user),
project_name: str = Depends(dep_project_name),
task_id: str = Depends(dep_task_id),
):
"""Retrieve a task by its ID."""
task = await TaskEntity.load(project_name, task_id)
await task.ensure_read_access(user)
return task.as_us... | 36b070ad55d39c228d28f22fc53c879efee7a083 | 65,731 |
from typing import Callable
def compute_t_level(task_graph: TaskGraphBase, cost_fn: Callable[[Task, Task], float]):
"""
Calculates the T-level (the earliest possible time to start the task).
"""
t_level = {}
for task in task_graph.tasks.values():
t_level[task] = 0.0
graph_dist_crawl(t... | 2d38c28b7cdd88ee6473a09219c3f3185cde5269 | 65,733 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import Callable
import html
from typing import List
def get_layout(
fit: nonlinear_fit,
name: str = "Lsqfit GUI",
meta_config: Optional[Dict[str, Any]] = None,
meta_values: Optional[Dict[str, Any]] = None,
use_d... | 169cddd6ba23419fcad2c343ad3e87c730828f54 | 65,734 |
def compute_std_and_max_point(data_array, selection_keys=None):
"""
Compute the standard deviations and maxima points for a subset of keys of a dictionary.
:param data_array: dictionary containing the data for the computations
:param selection_keys: list containing the keys to use. The entire dictionary... | c417edb86fc7cc935fbe9993ddf0ad7ba3ae8787 | 65,735 |
def calculate_income_tax(income: float) -> float:
"""Use this function for calculating the income tax for the users income.
This function is used for just calculating the income tax for a given income and
returning both the income tax and the leftover income.
:param income: the users pre-tax income.
... | f5e9aaa954ad5aac2008eb9c39d4b66b9ebdd04b | 65,736 |
def short_client():
"""This client is to be used with the dev server set to issue tokens
with very short expirations in order to test out the expired token
handling code
"""
return DocumentCloud(
username=USERNAME,
password=PASSWORD,
base_uri=BASE_URI,
auth_uri=AUTH_U... | 87c082419de466bf4cda99b68af0eb54c230828c | 65,737 |
def imshow(image, ax=None):
"""
Image show given a tensor as input
:param image: (torch tensor) the image data as a Torch tensor
:param ax: (matplotlib Axis) not required, will be used if given or created otherwise
:return: (matplotlib Axis)
"""
if ax is None:
fig, ax = plt.subplots(... | 58abd325dad41a3e3a2fde63a9ed5e57d47788ac | 65,738 |
def __format_value(arg: Primitive) -> str:
"""Formats a value to a string. If the value is a string,
it will be enclosed with quotes.
Args:
arg (Primitive): The value to format.
Returns:
str: The formatted argument.
"""
val: str = str(arg)
if arg is str:
val = '"... | 622722c4046c6c8482b9a655d1e001aca0a570b2 | 65,739 |
def compute_mean_var_f(
x, Xsamples, Ysamples, l, sigma, sigma0, NKInv=None, fullcov=False, dtype=tf.float32
):
"""
NKsampleInv = inv(KXsampleInv + eye(n)*sigma0)
l: 1 x d
Ysamples: m x 1
Xsamples: m x d
x: n x d
return: mean: n x 1
var : n x 1
"""
if NKInv is None:
... | 8e7698e706cbd410f08e1b959b42d90fc6e1027a | 65,740 |
from typing import List
from typing import Tuple
def read_overlap_data(config: DictConfig, mo_paths: List[str]) -> Tuple[Matrix, Matrix]:
"""Read the Molecular orbital coefficients."""
mos = retrieve_hdf5_data(config.path_hdf5, mo_paths)
# Extract a subset of molecular orbitals to compute the coupling
... | f295cd8e1c7cb4f19eb2621c9c4d6c8a9e35cacc | 65,742 |
import random
def random_contig_length(invalid_data):
"""
Generate Random Contig Length
return: int.
"""
return random.randint(10,50000), global_valid_data | 8e27074408e5347c2d385f2078725efa23189503 | 65,743 |
def average_gradients(total_grads_and_vars):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
total_grads_and_vars: List of lists of (gradient, variable) tuples.
The outer list ... | 7354f574dcbf9478c5081508232cadd9e76a8217 | 65,744 |
def add_links(self, value):
"""
This creates a Link header from the links
Parameters
----------
self : lib.schema.riak.objects.Link
The Link schema object
value : dict
The headers of the request to add the links to
"""
links = getattr(self, 'links', [])
if links:
... | 3d507ce928b227399ca325d5a55cab6b5ae07791 | 65,747 |
def count_all(text, content):
"""
统计数量
:param text:
:param content:
:return:
"""
word_dict = {}
word_list = [word.split(',') for word in content]
for item in word_list[0]:
if item not in word_dict:
word_dict[item] = 1
else:
word_dict[item] +=... | 26bd5e471927219a33e42e3188c983e2034b2e7b | 65,748 |
def children(level, idx):
"""
Return all the children of the Healpix pixel idx at level (in nested format)
:param level: Resolution level
:param idx: Pixel index
:return: All the parents of the pixel
"""
chld = []
for ind in range(4):
chld.append((level + 1, 4 * idx + ind))
... | ef1a127270a689fc7c05eb2f2b40abb7e6efc2ce | 65,749 |
def _ProcessSetLine(tline, expvals, card, errmsg):
"""process the line and obtain the cards names and values"""
# tline:: is the text line to be processed
# expvals:: is the range [a,b] of expected values
# card:: name of the card
# errmsg:: additional error message added to InputCardError
... | 2c841bba5070c9fed418d41903542db7812e3902 | 65,751 |
def update_courses(request_ctx, account_id, course_ids, event, **request_kwargs):
"""
Update multiple courses in an account. Operates asynchronously; use the `ProgressController#show <https://github.com/instructure/canvas-lms/blob/master/app/controllers/progress_controller.rb>`_
to query the status of an o... | 9108ea18ed9f7b3876f3d590212f76ddd09c9aba | 65,752 |
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_get(uuid, node_uuid, node_rule_group_uuid, inter_rule_group_uuid): # noqa: E501
"""data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_r... | a6d89c8711fa2c5efc5e5c3154b7beb8e26bfa8f | 65,753 |
def get_namespaces(return_separator=False, return_root=False):
"""returns namespaces
Args:
return_separator(bool): return separator
Returns:
list of unicode: namespaces
"""
cmds.namespace(set=ROOT_NAMESPACE)
namespaces = set()
if return_root:
namespaces.add(ROOT_NAM... | fa0122c31100fd994ffc305ae2a4719e660ecb01 | 65,754 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.