content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def graph_merge(grph, comm=None):
"""
Merge graph states across multiple processes.
Each process has the same graph of objects, but those objects have
different states based on which tasks a process has run locally.
This function reconciles the state of all objects between processes
and re-broa... | 47,000 |
def number_of_a_char(element: Element):
"""
get number of linked char, for example, result of `<a href="#">hello</a>world` = 5
:param element:
:return: length
"""
if element is None:
return 0
text = ''.join(element.xpath('.//a//text()'))
text = re.sub(r'\s*', '', text, flags=re.S... | 47,001 |
def draw_random_sub_samples(random_sub_samples,datafolder='data',force_overwrite=False):
""" draw random sub-sample of pnrs
Args:
random_subsamples (dict): keys 'dataset' (str), 'year' (int), and 'seed' to random number generator
datafolder (str): path to where results are saved
"... | 47,002 |
def Try(array):
"""Finds [a_0 >= a1 >= ...] so that PI(2*a_i+1) >= threshold."""
global ans
if Prod(primes, array) > ans:
return
if petools.Product([2*a+1 for a in array]) >= threshold:
ans = Prod(primes, array)
else:
for a in range(1, array[-1]+1):
Try(array+[a]) | 47,003 |
def main():
"""
Get credentials from vault. Poke backup gateway. Push stats to influxdb
"""
vault = get_hvac_client()
bg_creds = vault.secrets.kv.v1.read_secret(BG_GATEWAY_SECRETS_PATH)
influxdb_creds = vault.secrets.kv.v1.read_secret(INFLUXDB_CREDS_PATH)
powerwall = Powerwall(BG_GATEWAY_HO... | 47,004 |
def preprocessing_fn(batch):
"""
Standardize, then normalize sound clips
"""
processed_batch = []
for clip in batch:
signal = clip.astype(np.float64)
# Signal normalization
signal = signal / np.max(np.abs(signal))
# get pseudorandom chunk of fixed length (from SincN... | 47,005 |
def DemangleRemainingSymbols(raw_symbols, tool_prefix):
"""Demangles any symbols that need it."""
to_process = [s for s in raw_symbols if s.full_name.startswith('_Z')]
if not to_process:
return
logging.info('Demangling %d symbols', len(to_process))
names = _DemangleNames((s.full_name for s in to_process)... | 47,006 |
def elast_quad9(coord, params):
"""
Quadrilateral element with 9 nodes for classic elasticity
under plane-strain
Parameters
----------
coord : coord
Coordinates of the element.
params : list
List with material parameters in the following order:
[Young modulus, Poisso... | 47,007 |
def test_user_cli():
"""
title: Test that OpenCAS does not allow to change parameters in CLI by non-root user.
description: |
Checking if changing parameters in CLI by non-root user is forbidden by OpenCAS,
but is permitted with 'sudo' command.
pass_criteria:
- ... | 47,008 |
def peek(audio_file_path: Union[str, Path], output: str = "np"):
"""
Returns a tuple of audio data and its sampling rate
The audio data can be a numpy array or list
"""
data, sr = sf.read(audio_file_path, dtype="float32")
data = data.transpose()
if output == "list":
return data.tolis... | 47,009 |
def parse_rangelist(rli):
"""Parse a range list into a list of integers"""
try:
mylist = []
for nidrange in rli.split(","):
startstr, sep, endstr = nidrange.partition("-")
start = int(startstr, 0)
if sep:
end = int(endstr, 0)
if... | 47,010 |
def intersect_by_tf(emotion_dict):
""" Takes multiple emotion word lists and intersects them by their term frequency, leading to the emotional
difference between sets of any size.
Args:
emotion_dict: dict of summed up emotional scores based on the tf scores of the underlying words
Retur... | 47,011 |
def test_no_data():
"""Test no data should return Failure."""
test = [{}, ['keys']]
t_result = fetch_data_by_keys(*test)
assert not is_successful(t_result)
assert 'keys' in str(t_result.failure()) | 47,012 |
async def test_async_register_device_longpress_fails(hass, pywemo_device):
"""Device is still registered if ensure_long_press_virtual_device fails."""
with patch.object(pywemo_device, "ensure_long_press_virtual_device") as elp:
elp.side_effect = PyWeMoException
assert await async_setup_component... | 47,013 |
def transcript_segments(location_descriptors, gene_descriptors):
"""Provide possible transcript_segment input."""
return [
{
"transcript": "refseq:NM_152263.3",
"exon_start": 1,
"exon_start_offset": -9,
"exon_end": 8,
"exon_end_offset": 7,
... | 47,014 |
def minhashing_alg6(dna, idx, shingles, buckets, k, rows, p, a, b, n):
"""
DEFAULT MINHASH ALGORITHM
Uses hash functions in the form ((a*pos+b) mod p) mod N,
where a and b random integers and p is prime and p > N.
Computes original position of shingle by finding all shingles and
enumerating them, then store them ... | 47,015 |
def perform_data_filtering_q2(data):
"""
Takes the original DataFrame.
Returns the altered DataFrame necessary for Q2.
"""
# redoing the dataframe columns based on different values
df = data
diseased = df['num'] != 0
df['num'] = np.where(diseased, 'diseased', 'healthy')
males = df['s... | 47,016 |
def player_with_name_and_value(source):
"""
source: pn.widgets.DiscretePlayer()
target: consists of source player's name, value and player itself
With pn.widgets.DiscretePlayer, we don't get name and
value updates in textual form. This method is useful
in case we want name and continuous value ... | 47,017 |
def _cached_diff(expression, var):
"""
Derive expression with respect to a single variable.
:param expression: an expression to derive
:type expression: :class:`~sympy.Expr`
:param var: a variable
:type var: :class:`~sympy.Symbol`
:return: the derived expression
:type: :class:`~sympy.Ex... | 47,018 |
def evaluateSLDA(f_gold, f_results):
""" Evaluation Metrics for SLDA. """
print "Starting evaluation"
counts = {"0": [0., 0., 0., 0.], "1": [0., 0., 0., 0.], "2": [0., 0., 0., 0.]}
conf = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
with copen(f_gold, encoding="utf-8") as gold_f:
with open(f_results)... | 47,019 |
def _get_mult_op_ ( klass1 , klass2 ) :
"""Get the proper multiplication operator
"""
t = klass1 , klass2
ops = _mult_ops_.get( t , None )
if ops : return ops ## RETURN
## try to load the operators
try :
ops = Ostap.Math.MultiplyOp ( klass1 , klass2 )
... | 47,020 |
def datetime_into_columns(df, column, weekday = False, hour_minutes = False, from_type = 'object'):
"""
The function converts a column with a date from either int64 or object type
into separate columns with day - month - year
user can choose to add weekday - hour - minutes columns
Keyword argument... | 47,021 |
def cis_codif_h1_moms(probe, starttime, endtime, sensitivity='high',
try_download=True):
"""
Load H+ moments from CIS instrument.
See https://caa.estec.esa.int/documents/UG/CAA_EST_UG_CIS_v35.pdf for more
information on the CIS data.
Parameters
----------
probe : stri... | 47,022 |
def readlines(file_path):
""" Read lines from fname, if the fname is loaded get the buffer."""
buffer = getbuffer(file_path)
if buffer and int(vim.eval('bufloaded(%d)' % buffer.number)):
return buffer
try:
with open(file_path, 'r') as fo:
# we are not decoding: since we hav... | 47,023 |
def random_avg_subdir(myinput, dims = "", n = 20):
"""
Get the average of n faces chosen from different subdirectories of myinput.
You can also pass a list of directories into myinput instead of a string
representing the target directory
"""
results = []
if isinstance(myinput, list) == False:
s... | 47,024 |
def convert_range_image_to_point_cloud(
frame, range_images, camera_projections, range_image_top_pose, ri_indexes=(0, 1)
):
"""Convert range images to point cloud. modified from
https://github.com/waymo-research/waymo-open-dataset/blob/master/waymo_open_dataset/utils/range_image_utils.py#L612
Args:
... | 47,025 |
def get_counts(circ: MyCircuit, n_shots: int, seed: int) -> Dict[Tuple[int, ...], int]:
"""Helper method for tests to summarise the shot table from the simulator
:param circ: The circuit to simulate
:type circ: MyCircuit
:param n_shots: The number of samples to take
:type n_shots: int
:param se... | 47,026 |
def length(
inputs: tf.Tensor,
axis: int = -1,
keepdims: bool = False,
epsilon: float = 1e-10,
name: str = None
) -> tf.Tensor:
"""
Computes the vector length (2-norm) along specified ´axis´ of given Tensor ´inputs´.
Optionally an epsilon can be added to the squared n... | 47,027 |
def class_label_matrix(labels, img_sizes, num_classes):
""" Computes the class label matrix of the training data. """
# Class label matrix
Y = list()
# Modeling the object detection problem as a binary classification problem (none, detection)
if num_classes == 2:
print('Modeling as a bin... | 47,028 |
def default_lambda_consumer(env_id):
"""Create a default lambda consumer for the snapshot restore test."""
return st.consumer.LambdaConsumer(
metadata_provider=DictMetadataProvider(
CONFIG_DICT["measurements"],
SnapRestoreBaselinesProvider(env_id)
),
func=consume_... | 47,029 |
def thresholdPolyData(poly, attr, threshold, mode):
"""
Get the polydata after thresholding based on the input attribute
Args:
poly: vtk PolyData to apply threshold
atrr: attribute of the cell array
threshold: (min, max)
Returns:
output: resulted vtk PolyData
"""
... | 47,030 |
def TCh_GetNum(*args):
"""
TCh_GetNum(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetNum(*args) | 47,031 |
def view_by_letter(name, words):
"""Filter to anagrams starting with input letter."""
print(f"Remaining letters: {name}")
u_in = input("select a starting letter or press Enter to see all: ")
subset = []
for candidate in words:
if candidate.startswith(u_in):
subset.append(candidat... | 47,032 |
def writeFGSSPostageStampRequestById(outfile, requestName, results, xsize, ysize, psRequestType = 'byid', optionMask = 2049, imageType = 'warp', psJobType = 'stamp', skycell = 'null', email = 'qub2@qub.ac.uk', camera = 'gpc1', coordMask = 2):
"""writeFGSSPostageStampRequestById.
Args:
outfile:
requ... | 47,033 |
def reduce_sequence(sequence, desired_length):
"""Reduces a sequence to the desired length by removing some of its elements uniformly."""
if len(sequence) < desired_length:
raise RuntimeError('Cannot reduce sequence to longer length.')
indexes = N.arange(desired_length) * len(sequence) / desired_len... | 47,034 |
def encode_label(text):
"""Encode text escapes for the static control and button labels
The ampersand (&) needs to be encoded as && for wx.StaticText
and wx.Button in order to keep it from signifying an accelerator.
"""
return text.replace("&", "&&") | 47,035 |
def dash_table_from_data_frame(df: pd.DataFrame, *, id, **kwargs):
"""Returns a dash_table.DataTable that will render `df` in a simple HTML table."""
df_all_columns = df.reset_index()
return dash_table.DataTable(
id=id,
columns=[{"name": i, "id": i} for i in df_all_columns.columns],
... | 47,036 |
def _triple():
"""Return a (type, value, tb) triple."""
try:
one()
except IndexError:
return exc_info()
else:
raise AssertionError('We should have had an IndexError.') | 47,037 |
def integrate_into_db(path):
"""Add Chinese support for the database by referencing `mooncell` data.
Some column names in the database will be modified(using `cn` and `jp` prefixes)
to distinguish between Chinese and Japanese texts.
Some custom tables(contents from `mooncell`) will be added.
"""
... | 47,038 |
def calcRSI(df):
"""
Calculates RSI indicator
Read about RSI: https://www.investopedia.com/terms/r/rsi.asp
Args:
df : pandas.DataFrame()
dataframe of historical ticker data
Returns:
pandas.DataFrame()
dataframe of calculated RSI indicators + original data
... | 47,039 |
def sample_images2(imgs, model, path, idx=None,save=False):
"""Saves a generated sample from the test set"""
true_map = Variable(imgs['B'].type(Tensor))
save_image(true_map, os.path.join(path, 'test_results/gt', str(idx)) +'.jpg', normalize=True)
fake_B = model(Variable(imgs['A'].type(Tensor)))
if s... | 47,040 |
def jarvis(input_path, output_path):
"""Simple filename cleansing for exported TIF filenames (as these are normally a mess following export via ImageJ)
Parameters
----------
input_path : str
folder where input files are stored
output_path : str
folder where renamed files should be c... | 47,041 |
def grep_annotations_multiple_files(files_list, regex, base_path, grep_type):
"""
:todo Refactor and remove the ugly type option
"""
annotations_list = []
for f in files_list:
annotations = []
if grep_type == "code":
annotations = grep_code_annotations(f, regex, base_path... | 47,042 |
def test_c_py_compose_transforms_module():
"""
Test combining Python and C++ transforms
"""
ds.config.set_seed(0)
def test_config(arr, input_columns, output_cols, op_list):
data = ds.NumpySlicesDataset(arr, column_names=input_columns, shuffle=False)
data = data.map(operations=op_lis... | 47,043 |
def add_header(input_array, codec, length, param):
"""Add the header to the appropriate array.
:param the encoded array to add the header to
:param the codec being used
:param the length of the decoded array
:param the parameter to add to the header
:return the prepended encoded byte array"""
... | 47,044 |
def jaccard_loss(logits, true, eps=1e-7):
"""Computes the Jaccard loss, a.k.a the IoU loss.
Note that PyTorch optimizers minimize a loss. In this
case, we would like to maximize the jaccard loss so we
return the negated jaccard loss.
Args:
true: a tensor of shape [B, H, W] or [B, 1, H, W].
... | 47,045 |
def registerPlayerToTournament(player, tournament):
"""Adds an existing player to an existing tournament.
Args:
player: the player's id
tournament: the tournament's id
"""
con = None
try:
con = connect()
cur = con.cursor()
cur.execute("""INSERT INTO t_tour... | 47,046 |
def _get_positional_body(*args, **kwargs):
"""Verify args and kwargs are valid, and then return the positional body, if users passed it in."""
if len(args) > 1:
raise TypeError("There can only be one positional argument, which is the POST body of this request.")
if "options" in kwargs:
raise... | 47,047 |
def resize_image_with_padding(im, new_dims, interp_order=1):
"""
Resize an image array with interpolation.
Parameters
----------
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
interp_order : interpolation order, default is linear.
Returns
-------
i... | 47,048 |
def _get_run_stats(calc_docs: List[Calculation]) -> Dict[str, RunStatistics]:
"""Get summary of runtime statistics for each calculation in this task."""
run_stats = {}
total = dict(
average_memory=0.0,
max_memory=0.0,
elapsed_time=0.0,
system_time=0.0,
user_time=0.0,
... | 47,049 |
def naming_convention(file_dir, file_name):
"""Rename files with 8-character hash"""
long_hash = sha1sum(os.path.join(file_dir, file_name))
file_prefix, file_sufix = file_name.split('.')
new_name = '{file_prefix}-{short_hash}.{file_sufix}'.format(
file_prefix=file_prefix,
short_hash=long... | 47,050 |
def test_blank_execution_environment(cli, runtime, ee_tag, tmp_path, data_dir):
"""Just makes sure that the build process does not require any particular input"""
bc = tmp_path
ee_def = data_dir / 'blank' / 'execution-environment.yml'
cli(
f'ansible-builder build -c {bc} -f {ee_def} -t {ee_tag} ... | 47,051 |
def mvn_log_pdf(x, mean, covariance):
"""
This function calculates the log-likelihood of x for a multivariate normal distribution parameterised by the
provided mean and covariance.
:param x: The location(s) to evaluate the log-likelihood. Must be [B x D], where B is the batch size and D is the
dimen... | 47,052 |
def test_construct_default():
"""Test constructing with defaults."""
version = Version(3)
assert version.major == 3
assert version.minor == 0
assert version.build == 0
assert version.revision == 0 | 47,053 |
def question_input (user_decision=None):
"""Obtains input from user on whether they want to scan barcodes or not.
Parameters
----------
user_decision: default is None, if passed in, will not ask user for input. string type.
Returns
-------
True if user input was 'yes'
False is... | 47,054 |
def depth(d):
"""Check dictionary depth"""
if isinstance(d, dict):
return 1 + (max(map(depth, d.values())) if d else 0)
return 0 | 47,055 |
def make_exploration_figures(IMAGE_SIZE, MAGNIFICATION, TYPES_SHORT, TYPES_LONG, SUBTYPES_SHORT, SUBTYPES_LONG):
""" make all the figures for the data exploration """
# load data
engine = sql.create_engine('sqlite:///'+str(IMAGE_SIZE[0])+'_'
+str(IMAGE_SIZE[1])+'_'+MAGNIF... | 47,056 |
def validate_analysis_possible(f):
"""
Decorator that validates that the amount of information is
sufficient for attractor analysis.
:param f: function
:return: decorated function
"""
def f_decorated(*args, **kwargs):
db_conn, *_ = args
if db_conn.root.n_aggregated_attractor... | 47,057 |
def get_short_chan_id(source: hex, dest: hex) -> bytes:
"""Return a short channel id (bytes) based on source and destination provided.
"""
channel = [
channel
for channel in config.rpc.listchannels(source=source)["channels"]
if channel["destination"] == dest
][0]["short_channel_i... | 47,058 |
def register_logging(app):
"""日志处理器"""
class RequestFormatter(logging.Formatter):
def format(self, record):
record.url = request.url
record.remote_addr = request.remote_addr
return super(RequestFormatter, self).format(record)
request_formatter = RequestFormatter(... | 47,059 |
def get_rel(href, method, rule):
"""Returns the `rel` of an endpoint (see `Returns` below).
If the rule is a common rule as specified in the utils.py file, then that rel is
returned.
If the current url is the same as the href for the current route, `self` is
returned.
Args:
href (str)... | 47,060 |
def test_fetch_reads_all_dsets():
""" Should return all reads except read_2, which has fraction_A = 0.7"""
database = "scratch/filter/test.db"
reads = filt.fetch_reads_in_datasets_fracA_cutoff(database, None, 0.5)
assert set(list(reads.read_name)) == set(["read_1", "read_3", "read_4", "read_5"]) | 47,061 |
def is_exist(self, connectivity):
"""Check the existence of a cell defined by a connectivity (vector of points indices).
The order of points indices does not matter.
Parameters
----------
self : CellMat
an CellMat object
connectivity : ndarray
an array of node tags
Returns
... | 47,062 |
def get_current_identity_arn(boto3_session: Optional[boto3.Session] = None) -> str:
"""Get current user/role ARN.
Parameters
----------
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
Returns
-------
str... | 47,063 |
def proxy_signature_is_valid(request, secret):
"""
Return true if the calculated signature matches that present in the query string of the given request.
"""
# Allow skipping of validation with an explicit setting.
# If setting not present, skip if in debug mode by default.
skip_validation = ge... | 47,064 |
def remove_whitespace(sentences):
"""
Clear out spaces and newlines
from the list of list of strings.
Arguments:
----------
sentences : list<list<str>>
Returns:
--------
list<list<str>> : same strings as input,
without spaces or newlines.
"""
return [[w.... | 47,065 |
def generate_jwt(payload, expiry, secret=None):
"""
生成jwt
:param payload: dict 载荷
:param expiry: datetime 有效期
:param secret: 密钥
:return: jwt
"""
_payload = {'exp': expiry}
_payload.update(payload)
if not secret:
secret = current_app.config['JWT_SECRET']
token = jwt.... | 47,066 |
def test_github_token_env_var_exists():
"""tests correctly named env var for GitHub access exists
needed for higher API rate limit to run necessary queries vs large cpython repo
"""
assert os.getenv("GITHUB_ACCESS_TOKEN") is not None | 47,067 |
def authentication(uuid):
"""Allow a client to request/recieve an authentication key."""
if request.method == "POST":
with peewee_db.atomic():
if RestClient.get_or_none(RestClient.uuid == uuid):
return json.jsonify({"msg": "UUID already exits."}), 409
else:
... | 47,068 |
def one_sided_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1.,
low_counts_threshold=1e-8):
"""From openai.baselines.common.plot_util.py
perform one-sided (causal) EMA (exponential moving average)
smoothing and resampling to an even grid with n points.
Does not do extrapol... | 47,069 |
def settings_value(setting_name):
"""Return value for a given setting variable.
{% settings_value "LANGUAGE_CODE" %}
"""
return getattr(settings, setting_name, "") | 47,070 |
def setup_osx():
"""
INCOMPLETE
Requires brew. Update the OSX host and install the necessary third party software, then
follow the setup steps all OSes have in common.
"""
sudo('easy_install pip')
sudo('pip install virtualenv')
sudo('brew install nginx')
setup_common() | 47,071 |
def mongo_stat(server, args_array, **kwargs):
"""Method: mongo_stat
Description: Function stub holder for mongo_perf.mongo_stat.
Arguments:
(input) server
(input) args_array
(input) **kwargs
class_cfg
"""
status = True
if server and args_array and kwar... | 47,072 |
def copy_directory(source, copy_loc):
"""Given a source directory, copy ONLY the files in the directory
to the target directory, creating parent directories as necessary"""
ensure_hierarchy(copy_loc)
source = os.fsencode(source)
for file in os.scandir(source):
if file.is_file(follow_sy... | 47,073 |
def train_new_TFIDF(docs, save_as=None):
"""
Trains a new TFIDF model.\n
If a user abstract is given, it is used for the training.
Parameters
----------
docs : `[String]`. Documents to train on\n
save_as : `String`. Name to save model as.
Returns
-------
`TfidfVectorizer : The ... | 47,074 |
def generate_sphere_points(n):
"""
Returns list of coordinates on a sphere using the Golden-
Section Spiral algorithm.
"""
points = []
inc = math.pi * (3 - math.sqrt(5))
offset = 2 / float(n)
for k in range(int(n)):
y = k * offset - 1 + (offset / 2)
r = math.sqrt(1 - y*y)
phi = k * inc
p... | 47,075 |
def get_options():
"""
Purpose:
Parse CLI arguments for script
Args:
N/A
Return:
N/A
"""
parser = ArgumentParser(description="Produce to Kafka Topic")
required = parser.add_argument_group("Required Arguments")
optional = parser.add_argument_group("Optional Argume... | 47,076 |
def _estimate_log_gaussian_prob(X, means, precisions_chol, covariance_type):
"""Estimate the log Gaussian probability.
Parameters
----------
X : array-like of shape (n_samples, n_features)
means : array-like of shape (n_components, n_features)
precisions_chol : array-like
Cholesky decomp... | 47,077 |
def descendants(region_id, allowed_ids, rm: RegionMeta):
"""Get all filtered descendant IDs of a given region ID.
A descendant is only accepted if it's in ``allowed_ids`` or is a
leaf region.
This is mimicking Dimitri's algorithm, I'm not sure about why this must
be that way.
"""
all_desce... | 47,078 |
def search_classification(request):
"""
Filters the classification by name.
"""
filters = json.loads(request.GET.get('filters', {}))
fields = filters.get('fields', [])
page = int_arg(request.GET.get('page', 1))
classifications = Classification.objects.get_queryset()
if 'name' in fields... | 47,079 |
def get_zone_id(ctx, param, zone_name):
"""Return the id for a zone by name."""
del ctx #unused
del param #unused
cf = CloudFlare.CloudFlare()
zones = cf.zones.get(params={'name': zone_name})
if len(zones) != 1:
raise click.ClickException('Invalid zone name: {}'.format(zone_name))
re... | 47,080 |
def solve(letters: List[str], dictionary: trie.Node) -> List[str]:
"""Finds all words that can be made using the given letters.
"""
center_letter = letters[0]
words = set()
queue = deque([letter for letter in letters])
while queue:
candidate = queue.popleft()
is_word, is_prefix ... | 47,081 |
def datetime_from_milliseconds_since_epoch(ms_since_epoch: int, timezone: datetime.timezone = None) -> datetime.datetime:
"""Converts milliseconds since epoch to a datetime object.
Arguments:
----------
ms_since_epoch {int} -- Number of milliseconds since epoch.
Keyword Arguments:
... | 47,082 |
def cleanup():
"""Cleanup routine"""
global db
global logger
if db is not None:
db.close()
db.closeLoggingStreams()
logger.info('Closing main logger streams.')
for handler in logger.handlers:
handler.stream.write('-------------------------------------------------------------\n')
handler.stream.write('\n\n... | 47,083 |
def input_file(path):
"""
Read common text file as a stream of (k, v) pairs where k is line number
and v is line text
:param path: path to the file to read
:return: lazy seq of pairs
"""
return zip(count(), __input_file(path)) | 47,084 |
def lik_constant(vec, rho, t, root=1, survival=1, p1=p1):
"""
Calculates the likelihood of a constant-rate birth-death process, conditioned
on the waiting times of a phylogenetic tree and degree of incomplete sampling.
Based off of the R function `TreePar::LikConstant` written by Tanja Stadler.
T.... | 47,085 |
async def test_run_with_valid_python_wait_finish() -> None:
"""
Test that valid python code is successfully executed.
Checks that:
- Zip file is extracted and robot.py is run
- Output is written to the log file
- The correct status is passed to the state manager
"""
ucl, sith = StatusIn... | 47,086 |
def window_bounds(
window: Window,
affine: Affine,
offset: str = 'center'
) -> tuple[float, float, float, float]:
"""Create bounds coordinates from a rasterio window
Parameters:
window: Window
affine: Affine
offset: str
Returns:
coordinate bounds (w, s, e, n)
... | 47,087 |
def get_k8s_model(model_type, model_dict):
"""
Returns an instance of type specified model_type from an model instance or
represantative dictionary.
"""
model_dict = copy.deepcopy(model_dict)
if isinstance(model_dict, model_type):
return model_dict
elif isinstance(model_dict, dict):... | 47,088 |
def merge_specs(specs_):
"""Merge TensorSpecs.
Args:
specs_: List of TensorSpecs to be merged.
Returns:
a TensorSpec: a merged TensorSpec.
"""
shape = specs_[0].shape
dtype = specs_[0].dtype
name = specs_[0].name
for spec in specs_[1:]:
assert shape[1:] == spec.shape[1:], "incompatible shap... | 47,089 |
def main(cfg):
"""Execute the program.
Argument cfg, containing directory paths, preprocessed input dataset
filenames and user-defined options, is passed by ESMValTool preprocessor.
"""
provlog = ProvenanceLogger(cfg)
lorenz = lorenz_cycle
comp = computations
logger.info('Entering the d... | 47,090 |
def makeMapItem(pl_id):
""" Recupere les items d'un player sur la map (stand ou pub). Utilise les fonctions makeMapItemStand et Pub.
:param arg1: id du joueur
:type arg1: int
:return: collection des objets appartenant au joueur, avec leur position
:rtype: Collection d'objets Json
"""
mapItem = []
mapItem.a... | 47,091 |
def get_test_result_records(page_number, per_page, filters):
"""Get page with applied filters for uploaded test records.
:param page_number: The number of page.
:param per_page: The number of results for one page.
:param filters: (Dict) Filters that will be applied for records.
"""
return IMPL.... | 47,092 |
def new_graph(**kwargs) -> Plot:
"""[summary]
:return: [description]
:rtype: Plot
"""
return GraphPlot(kwargs) | 47,093 |
def _average_path_length(n_samples_leaf):
"""
Taken from sklearn implementation of isolation forest:
https://github.com/scikit-learn/scikit-learn/blob/fd237278e/sklearn/ensemble/_iforest.py#L480
For each given number of samples in the array n_samples_leaf, this calculates average path length of unsuccee... | 47,094 |
def test_finally_exception():
"""Test 'finally_error' logic.
* it should return 'current' exception if it exists
* otherwise, it returns 'default_class(default_message)'
"""
with pytest.raises(RuntimeError):
try:
helper_raise_error(RuntimeError)
finally:
rais... | 47,095 |
def get_pkg_license(pkgname):
"""
Given a package reference (as from requirements.txt),
return license listed in package metadata.
NOTE: This function does no error checking and is for
demonstration purposes only.
"""
pkgs = pkg_resources.require(pkgname)
pkg = pkgs[0]
for line in pk... | 47,096 |
def _set (obj, attribute, value):
"""
Helper function to add an attribute directly into the instance
dictionary, bypassing possible __getattr__ calls
@param obj Any python object
@param attribute String containing attribute name
@param value Any python object
"""
obj.__dict__[attribute] = va... | 47,097 |
def parse(date):
"""
convert date from different input formats:
Parameters
----------
date : STR
FLOAT (unix timestamp)
Python native datetime.date object
pandas datetime object
Returns
-------
datetime.date
"""
out = False
try... | 47,098 |
def cleanup():
""" Remove old backups
"""
if os.path.isfile('%s/%s' % (bkp_location, bkp_filename)):
try:
os.remove('%s/%s' % (bkp_location, bkp_filename))
logging.info('%s Removed old backup: %s/%s'
% (datetime.now().strftime('%Y%m%d--%H-%M-%S'),
... | 47,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.