content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _load_edge_data(graph, regions):
"""Load and return all relevant edges from the graph."""
has_seat = _load_edges_from_query(
graph,
'SELECT inV().@rid AS in_rid, outV().@rid AS out_rid FROM Has_Seat')
# The edges in the existing dataset point from parent to child region / settlement.
... | d7a002c6214b614e95edc42d850dc9df51a26462 | 3,658,725 |
def get_story_assignee(jira_sheet, process):
""" Accessor for Story Assignee
Accessor method for retrieving the value for Story Assignee on the
JIRA Stories Sheet.
There is a check to make certain the process in question is amongst those
qualified to exist.
Args:
jira_sheet: A variabl... | 3f49c10e540b001cf0f4eebf69a1821a16ec9476 | 3,658,726 |
def predict_mhalo(obs_dsigma, mock_use, logms_mod_tot, logms_mod_inn, sig_logms=None):
"""Halo mass and its scatter in each bin.
Parameters
----------
obs_dsigma: list
List of observed DeltaSigma profiles.
mock_use: numpy array
UniverseMachine mock catalog.
logms_mod_tot : ndarr... | 0c68d773155f997d85361ae663bf0eaae09be258 | 3,658,727 |
def create_agent_model(env, lr=1e-4, h_size=128, epsilon=0.2, beta=1e-3, max_step=5e6, normalize=False, num_layers=2):
"""
Takes a Unity environment and model-specific hyper-parameters and returns the
appropriate PPO agent model for the environment.
:param env: a Unity environment.
:param lr: Learni... | ef43219e9e12ba46c81ed3a39ecb1b82e8953585 | 3,658,728 |
from typing import List
def decode_to_sequence(encoded_sequence: Bytes) -> List[RLP]:
"""
Decodes a rlp encoded byte stream assuming that the decoded data
should be of type `Sequence` of objects.
Parameters
----------
encoded_sequence :
An RLP encoded Sequence.
Returns
------... | cb33dd9da8deb2096ce3ad205a743c4c22c0f4c8 | 3,658,729 |
def list_field_override_choices(override_map=None, html=True):
"""
This returns either a list of allowable choices, or an HTML-formatted unordered list (default).
"""
if override_map:
if html:
choices = '<b>These are the allowable field override choices for field name:<ul>'
... | 9b29493af651d95d67f8bd2c4283f53e737e7c5c | 3,658,730 |
import six
def _safe_resolve_url(url):
"""
Previously, resolve_url_lazy would fail if the url was a unicode object.
See <https://github.com/fusionbox/django-authtools/issues/13> for more
information.
Thanks to GitHub user alanwj for pointing out the problem and providing
this solution.
""... | 9b06bc346ebe03b1e5209aa8c108b76aae895089 | 3,658,733 |
def get_metrics(
reset: bool = False, include_custom: bool = True, raise_errors: bool = True,
) -> pd.DataFrame:
"""
Returns table of available metrics used for CV.
Example
-------
>>> from pycaret.datasets import get_data
>>> boston = get_data('boston')
>>> from pycaret.regression im... | 1d2ed9372aa6f26cd740e6987a2e94baaef647dc | 3,658,734 |
def get_unique_wikilinks(filepath):
"""Get UNIQUE wikilinks from a md file.
The links' order of appearance in the file IS preserved in the output.
This accounts for:
- Aliases / alt text, so [[Lorem ipsum|L.I.]]
will be represented as 'Lorem ipsum'.
- Header text links, so [[Lorem ipsum#Dummy t... | ca02428942d8a555d606a5c4b8190859917c22c7 | 3,658,735 |
def parse_single_example(serialized_example, params):
"""Parses a singel serialized TFExample string."""
decoder = tf_example_decoder.TfExampleDecoder()
data = decoder.decode(serialized_example)
image = data['image']
source_id = data['source_id']
source_id = dataloader_utils.process_source_id(source_id)
h... | e274a6ebfe7e7aa51dc7bc6b779ef222081a7e47 | 3,658,736 |
def eval_blocking(lamb, mu, k):
"""Finds the blocking probability of a queue.
Args:
lamb (float): The rate into the queue.
mu (float): The rate out of the queue.
k (int): Maximum number of customers able to be in the queue.
"""
rho = lamb/mu
return rho**k*((1-rho)/(1-rho**(k... | 4c1ea7f5f7984fb24c85a5c1c6c77cdbc2e1e76a | 3,658,737 |
def get_dependent_columns(covar):
"""
Get the list of dependent columns
:param covar: The covariance matrix
:return: Dependent columns
"""
ind_columns = (np.where(~covar.any(axis=1))[0]).tolist()
dep_columns_z = []
for i in range(0, covar.shape[0]):
if i not in ind_columns:
... | d0145649ce685a4d609809a57d374b1e362c303e | 3,658,738 |
def results_to_answers(guess_hints, answers):
"""Provide remaining valid answers matching a list of guesses and
corresponding hints
"""
gh_stack = guess_hints.copy()
new_ans = answers.copy()
while len(gh_stack) > 0:
gh = gh_stack.pop()
guess = gh[0]
hint = gh[1]
... | 243cbaeb2d36c66e49cd570c1487bbca7636cd2c | 3,658,739 |
from typing import Optional
def get_archive_map(data: DataFrame, row_col: Optional[str] = "ROW") -> Series:
"""
Get a series mapping object names to archive names
:param data: Dataset with archive names as ARCHIVE column and object names
in index
:type data: DataFrame
:param row_... | 2d66c55c64dab89e7523778411a7bf70ac784bf6 | 3,658,740 |
from typing import Iterable
import math
def gain_ratio(x_mat: ndarray, y_row: ndarray, prop: int, prop_values: Iterable, gain_value: float = None) -> float:
"""
计算使用属性 prop 对样本集进行划分的信息增益率,值越大表示使用属性 prop 进行划分
所获得的纯度提升越大。此方法对可取值数目较少的属性有所偏好
:param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数
:param y_row: 输出向... | 08a26ba4c3dc7712ca515f128f7e3039f005b993 | 3,658,741 |
def _LengthError(e: ByteList):
"""Check if the length of the EDID is a multiple of 128.
Args:
e: The list form of the EDID to be checked.
Returns:
A list of error.Error objects, or None.
"""
if not len(e) % 128:
return None
else:
return [
error.Error(
... | 940b6f4b2648eefe79afe69f623b0f1e02583ce1 | 3,658,742 |
def __single_auc_score__(feature_i,
clf,
cv_indices,
X,
y,
sample_weight=None):
"""Method determining the 'area under curve' for a single test set.
This function is intended for internal ... | 51738218bde23aeb3633bcfa47dff918af29c4cd | 3,658,743 |
def IntCurveSurface_ThePolygonToolOfHInter_Bounding(*args):
"""
:param thePolygon:
:type thePolygon: IntCurveSurface_ThePolygonOfHInter &
:rtype: Bnd_Box
"""
return _IntCurveSurface.IntCurveSurface_ThePolygonToolOfHInter_Bounding(*args) | 294da704fcc9a59a8e7fc2042d050255aa45accb | 3,658,744 |
def identity_show(client, resource_group_name, account_name):
"""
Show the identity for Azure Cognitive Services account.
"""
sa = client.get(resource_group_name, account_name)
return sa.identity if sa.identity else {} | 19018c895f3fdf0b2b79788547bf80a400724336 | 3,658,745 |
import re
def normalize_country_code(country_code):
""" Normalize country codes a bit by making capitalization consistent and
removing trailing comments (and other words). """
if not country_code:
return country_code
country_code = re.match(r'^(\w+)', country_code).group(1)
return coun... | 37dce64b62ae4ec20cb2d9b10c66beeba73c5683 | 3,658,747 |
import math
def get_angle(p1, p2):
"""Get the angle between two points."""
return math.atan2(p2[1] - p1[1], p2[0] - p1[0]) | a29ea1ed74a6c071cf314d1c38c6e2f920bd1c3a | 3,658,748 |
def per_application():
"""
:return:
a seeder function that always returns 1, ensuring at most one delegate is ever spawned
for the entire application.
"""
return lambda msg: 1 | 7ecc568846ab484557e768ad372f4faf85238401 | 3,658,749 |
import requests
from bs4 import BeautifulSoup
def get_job_information(url):
""" Uses bs4 to grab the information from each job container based on the url.
Parameters
----------
url : str
Career builder url of any job
Returns
------
job_data : dict
Contains Job Name, Compa... | a5c0b53338dbacc7fe0e7c7eb91b66855968af2b | 3,658,750 |
def idiv(self, other):
"""Compute the element-wise division.
Parameters
----------
other : Union[dragon.Tensor, number]
The value to divide.
Returns
-------
dragon.Tensor
The self.
See Also
--------
`dragon.math.div(...)`_
"""
return _apply_binary_op([... | 05afbc883ec835e06cceaa9a13119fbac0df8f5c | 3,658,751 |
def getAudioMetadata(fileRef):
"""Extract metadata for audio file"""
args = [config.mediaInfoExe]
args.append("--Output=EBUCore")
args.append(fileRef)
# Command line as string (used for logging purposes only)
cmdStr = " ".join(args)
status, out, err = shared.launchSubProcess(args)
# C... | 4f954d45e6b029b22001a02e49ad453a2f572bb8 | 3,658,752 |
def simulation_test(**kwargs):
"""Decorate a unit test and mark it as a simulation test.
The arguments provided to this decorator will be passed to
:py:meth:`~reviewbot.tools.testing.testcases.BaseToolTestCase
.setup_simulation_test`.
Args:
**kwargs (dict):
Keyword arguments to... | 56aa51374e66bb765bfc3d4da51e3254d06c0b55 | 3,658,753 |
def update_action_state():
""" :type action: dart.model.action.Action """
# we receive a list of {action_id, action_status, workflow_instance_id/status}
# We will update the database for each such entry
try:
action_status_updates = request.get_json()
_logger.info("AWS_Batch: extracted j... | f89142b6877f615cce253d727c001737729394fa | 3,658,754 |
def page_not_found():
"""Directs to error page if user is not logged in.
:return: HTML file for error page.
"""
error = 'You must be logged in to view this page.'
return render_template('error.html', error=error) | ff3cc2c369154bec1303658bb3c691de448d8231 | 3,658,755 |
def mtf_toy_model_parallel():
"""Set of hyperparameters."""
hparams = mtf_toy_base()
hparams.add_hparam("layout", "hidden:0")
return hparams | 74c01e9f8c68f07d332119fd7cead21b92e4de84 | 3,658,756 |
from typing import Union
from pathlib import Path
def to_dataframe(sas7bdat_file: Union[str, Path]) -> pd.DataFrame:
"""Converts a sas7bdat and/or xpt file into a pandas dataframe.
args:
sas7bdat_file: The name, including the path, for the sas7bdat file.
return:
A pandas dataframe contai... | 70564f16c43a6c6fdaf65841ee1d0c48d8f550f2 | 3,658,757 |
def shift_scale_rmsf(rmsf_double, phi, cellsize, ccomp, faraday_peak):
"""Shift and scale the RMSF, to the parameters of the found clean component.
Args:
rmsf_double (numpy array): double sized array of complex point spread
function values in Faraday space.
phi (numpy array): array of Fara... | d658cfece87276075b7c53b987772906908b5b80 | 3,658,758 |
def region_filter(annos, annotation):
"""filter for Region annotations.
The 'time' parameter can match either 'time' or 'timeEnd' parameters.
"""
result = []
for anno in annos:
time = annotation.get("time")
timeEnd = annotation.get("timeEnd")
for key in ['text', 'tags']:
... | 3ca4c6ba39d44370b3022f5eb17a25e0e1c9f056 | 3,658,759 |
def estimator_mixt_default(sample):
"""Default estimator of mixture distribution
This estimator returns tuple with two non-overlaping parts of `sample`
which are estimated to come from continuous and discrete parts of mixture
distribution. Estimation is done by deciding sample element to be from
di... | 31394305d9da7afe553f0dab9753d919b6aa7c73 | 3,658,760 |
import inspect
def get_post_processors():
"""
Loads post processors by inspecting members of the 'post_processors' package.
"""
post_processor_classes = []
for _, member in inspect.getmembers(post_processors):
if inspect.isclass(member):
post_processor_classes.append(member)
... | 6b65c438657230661b189c8851ca5b662714c4df | 3,658,762 |
def vulcanize(name: str) -> str:
"""Add prefixes to names that are similar to the prefixes seen
in Vulcan characters in the Star Trek™ franchise.
:param name: The name to modify.
:return: A :class:str object.
:rtype: str
Usage:
>>> # Seed the RNG to make the example predic... | 00cd22427ab873852af519a6657bf9504b945fb3 | 3,658,763 |
def B(j, p, x, knots):
""" Compute B-splines using recursive definition. """
if p == 0:
if knots[j] <= x < knots[j+1]:
return 1.0
else:
return 0.0
else:
left = special_div((x-knots[j])*B(j,p-1,x,knots), knots[j+p]-knots[j])
right = special_div(... | 1c578e317a3e2ff00f31b8e0b31b4f184e9bd338 | 3,658,764 |
from re import T
def not_falsy(item: T, item_name: str) -> T:
"""
Check if a value is falsy and throw an exception if so.
:param item: the item to check for falsiness.
:param item_name: the name of the item to include in any exception.
:raises ValueError: if the item is falsy.
:returns: the it... | b758d3ffe8f4c30086248fc9df2a9e82e05553d3 | 3,658,765 |
def _apply_limit_abs_unit(x, lim, unit):
"""Return one limit with applied unit(abs(x)). See get_limits."""
if unit is None:
return lim
unit = unit.lower()
if unit == 'near':
return lim * np.nanmin(np.abs(x))
if unit == 'far':
return lim * np.nanmax(np.abs(x))
elif unit ==... | e3c77192b90b04b4c488ca8bac41f79024517a6b | 3,658,766 |
def load_fits(name):
""" Open a fits file image
Inputs:
name: name of the .fits file (str).
Output:
image:
"""
while True:
try:
file = fits.open(name)
image = file.copy()
return image, name
except FileNotFoundError:
prin... | 24a348239e89cc9e565238e9f124875090ffe92b | 3,658,767 |
def cleanup():
"""Clean up resoruces in use by implementation.
Clean up any resources that have been allocated by the RPC implementation.
This is typically open connections to a messaging service. This function
would get called before an application using this API exits to allow
connections to get... | 984d2c3b297c47c1ffaec43302cfb741cfe369e4 | 3,658,769 |
def social_bonus_count(user, count):
"""Returns True if the number of social bonus the user received equals to count."""
return user.actionmember_set.filter(social_bonus_awarded=True).count() >= count | b2469833f315410df266cd0a9b36933edb1f9ac6 | 3,658,770 |
def del_category_tag_lib(self,c_uuid,t_uuid):
"""04删除便签或分类"""
if c_uuid:
category = Category.by_uuid(c_uuid)
if category is None:
flash(self, '分类不存在', 'error')
return {'status':False}
if category.articles:
flash(self,'分类下面有文章,请先删除文章','error')
... | db915fe29943d9bb63122d73d59a052715798818 | 3,658,771 |
import math
def get_distance_metres(aLocation1, aLocation2):
"""
Returns the ground distance in metres between two `LocationGlobal` or `LocationGlobalRelative` objects.
This method is an approximation, and will not be accurate over large distances and close to the
earth's poles. It comes from the Ard... | 57a56fac2d0a3a83083b769b5f896cb82d55dc56 | 3,658,772 |
import copy
def get_export_summary(results):
"""Prints to screen the exporting results of example programs.
Args:
results - results of the compilation stage. which is the output of and export_repos()
Returns: Numbers of failed results
"""
pass_table = PrettyTable()
pass_table.field_... | 0f68e8da955a73c401536f83e18faa223d603d15 | 3,658,774 |
import numpy
def _misfitfunc(data, predicted):
"""
Calculate the total data misfit function between the observed and predicted
data.
"""
result = 0.
for d, p, in zip(data, predicted):
residuals = d.observed - p
result += sqrt(numpy.dot(d.weights*residuals, residuals))/d.norm
... | c21fb4c8d68a2abe20ca155e5776124c69ce2eff | 3,658,775 |
def stream_doi(app, doi):
"""Returns tuple of URL string and a urlopen() return value."""
apikey = app.cfg.get_or_die('api-keys', 'crossref')
url = ('http://crossref.org/openurl/?id=%s&noredirect=true&pid=%s&'
'format=unixref' % (wu.urlquote(doi), wu.urlquote(apikey)))
return url, wu.urlopen... | 7c3569c4492b52c68ed13bcaac9dae0b6805bdb6 | 3,658,776 |
from typing import Optional
import getpass
from datetime import datetime
import json
def do_evaluation(
*,
input_path,
training_path: Optional[str] = None,
testing_path: Optional[str] = None,
method,
prediction_task,
dimensions: int = 300,
number_walks: int = 8,
walk_length: int = ... | ab5939065d9cf70c6e5ddba8530f91cb2577a31c | 3,658,777 |
import re
def test_structure_fatal_deformities(good_structure, deformity):
"""Make specific checks upon performing single invalidating deformations
of the data of a good structure.
"""
if deformity is None:
return StructureResource(**good_structure)
deformity, message = deformity
go... | 28acc95fb29564ddbf844de70704e31212e59b9f | 3,658,778 |
def edit_user():
""" 返回待编辑用户信息 """
data = request.json
user_id = data.get('id')
_edit = User.query.filter_by(id=user_id).first()
_data = {'account': _edit.account, 'name': _edit.name, 'role_id': _edit.role_id}
return jsonify({'data': _data, 'status': 1}) | 7423eb2342dd135a219bbb6f34ba7f82740b49d0 | 3,658,779 |
def transactions(request):
"""See all transactions that have been contained in blocks."""
vote_list = Vote.objects.all().order_by('timestamp')
paginator = Paginator(vote_list, 100, orphans=20, allow_empty_first_page=True)
page = request.GET.get('page')
votes = paginator.get_page(page)
hashes =... | 7ed0d4a8b997a41112eccfc67a19784283e65fd8 | 3,658,780 |
import pandas
def elections_vote_places_geo(source="xd", folder=".", fLOG=noLOG):
"""
Retrieves data vote places (bureaux de vote in French)
with geocodes.
@param source should be None unless you want to use the backup plan ("xd")
@param folder where to download
@param fLOG ... | b81abbeeed1968e01477cb71897a373a113ffafb | 3,658,781 |
from typing import Optional
def erfc(
x: oneflow._oneflow_internal.BlobDesc, name: Optional[str] = None
) -> oneflow._oneflow_internal.BlobDesc:
"""This operator computes the :math:`1-erf(x)`, for more details of `erf` function
please refer to `math.erf`.
Args:
x (oneflow._oneflow_internal.Bl... | 0fd6f01b0d6dbbdf7449a5a7dc2ac9ee3f0bce0e | 3,658,782 |
from typing import Union
from typing import Iterable
from typing import Optional
from typing import List
from typing import Dict
from typing import Any
def ner_manual_tokenizers_bert(
dataset: str,
source: Union[str, Iterable[dict]],
loader: Optional[str] = None,
label: Optional[List[str]] = None,
... | 982ddc4ab2e574870a5790dc37854ff5ffec648a | 3,658,783 |
def test_nested_simple_condition() -> None:
"""
Iterates and maps expressions over a complex Condition:
(A=B OR A=B) AND (A=B OR A=B)
"""
c1 = Column(None, "t1", "c1")
c2 = Column(None, "t1", "c2")
co1 = binary_condition(None, ConditionFunctions.EQ, c1, c2)
c3 = Column(None, "t1", "c1"... | f047f916f3ace9142e8940a39fd47d36d43dc108 | 3,658,784 |
import functools
def _deep_setattr(obj, key, val):
"""
Set an attribute `key` on the object. If any of the prefix attributes do
not exist, they are set to :class:`~pyro.nn.PyroModule`.
"""
def _getattr(obj, attr):
obj_next = getattr(obj, attr, None)
if obj_next is not None:
... | a28b01484de71dc486c73fe9ad01238675b15a04 | 3,658,785 |
def inverse_max_dcg(labels,
gain_fn=lambda labels: tf.pow(2.0, labels) - 1.,
rank_discount_fn=lambda rank: 1. / tf.math.log1p(rank),
topn=None):
"""Computes the inverse of max DCG.
Args:
labels: A `Tensor` with shape [batch_size, list_size]. Each valu... | 60e5b05af91fbd8e51a58894f9f19a5a8f92d1b5 | 3,658,786 |
def get(url):
"""
用 GET 请求 url 并返回响应,对301进行了处理
:param url:
:return:status_code, headers, body
"""
protocol, host, port, path = parsed_url(url)
s = socket_by_protocol(protocol)
s.connect((host, port))
request = 'GET {} HTTP/1.1\r\nhost: {}\r\nConnection: close\r\n\r\n'.format(path, ... | 3ef816149e8b4953e119c807726112feeacc6eed | 3,658,787 |
def NotEqual(data1, data2, target=utils.CCE):
"""
check whether data1 notequals to data2.
Args:
data1 (tvm.tensor.Tensor): Tensor.
data2 (tvm.tensor.Tensor): Tensor.
Returns:
tvm.tensor.Tensor. If data1 notequal to data2 return True, else return False.
Supported Platfo... | 88be9ea40900644a61dd3f37c0a05f9fa8c3eb76 | 3,658,789 |
def read_labels(labels_path):
"""Reads list of labels from a file"""
with open(labels_path, 'rb') as f:
return [w.strip() for w in f.readlines()] | 3ebc61c76dd1ae83b73aa8b77584661c08a51321 | 3,658,790 |
def calc_distance_two_points(long_from, lat_from, long_to, lat_to):
"""Calculate distance between two points
Parameters
----------
long_from : float
Longitute coordinate from point
lat_from : float
Latitute coordinate from point
long_to : float
Longitute coordinate to po... | 0c35c22458db165684242389470248632f2e1edb | 3,658,792 |
from typing import Counter
def modified_precision(reference_max_counts, hypothesis, n):
"""
Calculate modified ngram precision.
The normal precision method may lead to some wrong translations with
high-precision, e.g., the translation, in which a word of reference
repeats several times, has very ... | cbaf2ca391a6b0ac8bfcf9e2f85aba83f4b585d0 | 3,658,793 |
def bin_spectrum(bin_width, wavelength, doppler_shift, flux, flux_uncertainty,
final_uncertainty='combine'):
"""
Args:
wavelength:
doppler_shift:
flux:
flux_uncertainty:
Returns:
"""
bw = bin_width
wv = wavelength
ds = doppler_shift
f =... | 3c71977ae845161156ed95b42f68d7de65b80f66 | 3,658,794 |
def scrub(old_fs: Vfs, new_fs: Vfs) -> Vfs:
"""Try to eliminate files which were previously installed but are no longer used."""
old_fs = old_fs.copy()
new_fs = new_fs.copy()
# Look for files in the old log which are no longer present in the new log
for txn in old_fs._log:
if txn[0] == "li... | c1cdfad6c658e481b05658d3041458ab6fd3419c | 3,658,795 |
def get_filename(row):
"""
Assembles the name of the feature file.
Parameters
----------
row : pandas.Series
A row fom the sequence dataframe. Must have the following index values:
"sample_name", "inj_number", "batch_name", "acquisition_date_and_time".
Returns
-------
f... | 68624971527442da110734043bdbaa1c68dc4875 | 3,658,796 |
def create_plotly_trace(data_x, data_y, namexy, chosen_mode='lines', use_gl = True, swap_xy = False):
"""
Создание одного trace по данным
:param data_x: данные для оси x
:param data_y: данные для оси y
:param namexy: название для trace
:param chosen_mode: настройка отображения 'lines', 'marker... | dd90d370c27968053bfaf98f509868d959416d39 | 3,658,797 |
import yaml
def read_metadata() -> dict:
"""Reads and returns raw metadata."""
with open(metadata_path().resolve(), "r") as fd:
return yaml.safe_load(fd) | 0eafc0a722ac5cae69407a7e76d5bf62b7541b69 | 3,658,798 |
def new_token():
"""
Generate an access token for the user.
This endpoint requires basic auth with nickname and password.
"""
return jsonify({'token': generate_token(g.current_user['id'])}) | 07497cebfd29a133ab986c86b72b603975378ed8 | 3,658,800 |
def get_room_info(room_real_id: int, verify: utils.Verify = None, cookies = None):
"""
获取直播间信息(标题,简介等)
:param room_real_id: 真实房间ID
:param verify:
:return:
"""
if verify is None:
verify = utils.Verify()
api = API["live"]["info"]["room_info"]
if cookies is None:
resp =... | a6aa07886034a5f8c539026f8afacaa149860252 | 3,658,801 |
def parse_raw(setup, id=None, first_line_is_header=(-1,0,1)):
"""Used in conjunction with lazy_import and parse_setup in order to make alterations
before parsing.
Parameters
----------
setup : dict
Result of h2o.parse_setup
id : str, optional
An id for the frame.
first_line_is_header ... | 56d490eeaa28258ee668ed5efcc0f8a869acaa2b | 3,658,802 |
from datetime import datetime
def import_year(year: int = None) -> bool:
"""Downloads, extracts and imports the Losungen of a given year.
The year defaults to the next year."""
session: Session = SessionMaker()
repo = TagesLosungRepository(session)
year = datetime.date.today().year + 1 if year is ... | a0e5933178f5d18332f0b231f7a6ec43c0651714 | 3,658,803 |
import re
def isURL(url: str) -> bool:
""" Check whether a given string is a URL. """
return url is not None and re.match(urlregex, url) is not None | 6d32fee1fa374c07214d2a75cc39b868338ffa1c | 3,658,804 |
def rmse(Y_true, Y_hat):
"""
returns root mean squared error
Args:
Y_true : true outputs [N,(1)]
Y_hat : predicted outputs [N, (1)]
"""
if Y_true.ndim == 2:
Y_true = Y_true[:, 0]
if Y_hat.ndim == 2:
Y_hat = Y_hat[:, 0]
return np.sqrt(np.mean((Y_tru... | 676d14a5058632fbf1cd40e4d60d5cfb4c46e137 | 3,658,805 |
def getAllDescWords(itemList):
"""Returns a list of "description words" for each item named in itemList."""
itemList = list(set(itemList)) # make itemList unique
descWords = []
for item in itemList:
descWords.extend(NYCitems[item][DESCWORDS])
return list(set(descWords)) | fb7ea77fac5aae3abc2e6dbcc1c3af7ac404b5c2 | 3,658,806 |
def create_constrained_mechanical_system_from_component(structural_component, constant_mass=False,
constant_damping=False, constraint_formulation='boolean',
**formulation_options):
"""
Create a mechan... | e661ba16a691266e60b14d4594db16e09d81c2e2 | 3,658,808 |
def parse_certificate_issuer_id(id):
"""
:param id: The resource collection type.
:type id: str
:rtype: KeyVaultId
"""
return parse_object_id('certificates/issuers', id) | 919ad42ede4081c67c38f9d44945045d3f84bf87 | 3,658,809 |
def normalize_whitespace(
text, no_line_breaks=False, strip_lines=True, keep_two_line_breaks=False
):
"""
Given ``text`` str, replace one or more spacings with a single space, and one
or more line breaks with a single newline. Also strip leading/trailing whitespace.
"""
if strip_lines:
t... | 46d60967f48cb2b14ee44eaa4979592b87e8d811 | 3,658,810 |
import numpy
def nancumprod(x1, **kwargs):
"""
Return the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) as one.
For full documentation refer to :obj:`numpy.nancumprod`.
Limitations
-----------
Parameter ``x`` is supported as :obj:`dpnp.ndarray`.
... | e388081ca78decb8b05a6138173cb487a1c72c58 | 3,658,811 |
def error(data, mn, mx, confidence):
"""
Compute the error components.
:param data: the collected data.
:param mn: the critical value (minimum).
:param mx: the critical value (maximum).
:param confidence: the confidence level.
:return: (Dict) the dictionary of errors.
"""
return erru... | 31ba96b58a5017a3bd3a5166b460878a886f2bb3 | 3,658,813 |
def retry_connection(f):
"""Decorator. Recconect on failure.
"""
def retry(*args, **kwargs):
seconds_to_retry = 5
success = False
while (not success):
try:
result = f(*args, **kwargs)
success = True
return result
... | d9ccbe725f50a6061f77ac76d02e11c52dd91cb1 | 3,658,814 |
def shift_mean(x_mod, x_org):
"""
Shift the mean value of `x_mod` such that it equals the mean of `x_org`.
Parameters
----------
x_org : ndarray
The array which hold the "true" mean value.
x_mod : ndarray
The modified copy of `x_org` which must have its mean value shifted.
... | 0f04e37a9434548cff77a1c92d7540595ee5a1cf | 3,658,815 |
def conversation_detail(request, pk):
"""
Retrieve, update or delete a conversation.
"""
try:
conversation = Conversation.objects.get(pk=pk)
except Conversation.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = Conv_... | 5c4a0b20f38ca7b75415ecb88f25e9992e2a3e57 | 3,658,816 |
def purchase_products(product_id):
"""Purchase a product"""
app.logger.info("Request to purchase product with id %s", product_id)
check_content_type("application/json")
product = Product.find(product_id)
if not product:
abort(
status.HTTP_404_NOT_FOUND, "product with id '{}' was ... | c6681110ffaa25cab1ea2fd649c845c513b7b178 | 3,658,817 |
def process_alerts(data):
"""
Returns a Pandas DataFrame from the API call.
:return: A pandas DataFrame.
"""
data_dicts = data.get("data", [])
lines = []
for data_dict in data_dicts:
data_dict["alertDescription"] = helper.extract_json_field(
data_dict.get("alertProps", {... | 64a06486ebfde2610f11110b55a73a359fe8d0c0 | 3,658,818 |
def validate(df):
"""Validate the timeseries dataframe
"""
err_msgs = []
warn_msgs = []
# check column names
for col in EXP_COLS:
if col not in df:
err_msgs.append(f"**{col}** column missing")
msgs = {
"errors": err_msgs,
"warnings": warn_msgs
}
... | 74480413646d1f7480c7915cdd1d28116ace83c6 | 3,658,819 |
def _gcs_uri_rewriter(raw_uri):
"""Rewrite GCS file paths as required by the rewrite_uris method.
The GCS rewriter performs no operations on the raw_path and simply returns
it as the normalized URI. The docker path has the gs:// prefix replaced
with gs/ so that it can be mounted inside a docker image.
Args:... | 6e476860cb175dd2936cc0c080d3be1d09e04b77 | 3,658,820 |
def remove_apostrophe(text):
"""Remove apostrophes from text"""
return text.replace("'", " ") | c7d918e56646a247564a639462c4f4d26bb27fc4 | 3,658,821 |
def generate_initials(text):
"""
Extract initials from a string
Args:
text(str): The string to extract initials from
Returns:
str: The initials extracted from the string
"""
if not text:
return None
text = text.strip()
if text:
split_text = text.split(" ... | 709e53392c790585588da25290a80ab2d19309f8 | 3,658,822 |
def nmf_manifold_vec_update(X, U, V, k_to_W, k_to_D, k_to_L, k_to_feat_inds, n_steps=10, gamma=1.0, delta=1.0, i=0, verbose=False, norm_X=None):
"""
Perform <n_steps> update steps with a fixed Laplacian matrix for each latent factor
Parameters
----------
X : np.array
data to factor
U : np.array
pr... | f1998d8ccd000892f441341240216ada5fd46a70 | 3,658,823 |
def check_xyz_species_for_drawing(xyz, species):
"""A helper function to avoid repetative code"""
if species is not None and xyz is None:
xyz = xyz if xyz is not None else species.final_xyz
if species is not None and not isinstance(species, ARCSpecies):
raise InputError('Species must be an A... | 26caa32c55eee43dab53f85e442775095da92580 | 3,658,824 |
def GetUDPStreamSample(command_out, sending_vm, receiving_vm, request_bandwidth,
network_type, iteration):
"""Get a sample from the nuttcp string results.
Args:
command_out: the nuttcp output.
sending_vm: vm sending the UDP packets.
receiving_vm: vm receiving the UDP packets.
... | d9f0e75602768ee574d280215ebc78ebd67a520b | 3,658,825 |
def setSwaggerParamDesc(swagger,searchParams):
"""
Set the Swagger GET Parameter Description to what is stored in the search Parameters using helper function
"""
for id in range(len(swagger['tags'])):
# Paths are prefaced with forward slash
idName = '/'+swagger['tags'][id]['name']
... | e83c4c713718d382e5ce6f2429d029d4eb9ae588 | 3,658,826 |
def parse_args(args=[], doc=False):
"""
Handle parsing of arguments and flags. Generates docs using help from `ArgParser`
Args:
args (list): argv passed to the binary
doc (bool): If the function should generate and return manpage
Returns:
Processed args and a copy of the `ArgPa... | ca77aad1d31287f1394678db90c0857dbdae6a43 | 3,658,827 |
import array
def interact(u, v):
"""Compute element-wise mean(s) from two arrays."""
return tuple(mean(array([u, v]), axis=0)) | 9dd567568d5301dd62fcf19b7b4ac0130fc5b527 | 3,658,828 |
def part_allocation_count(build, part, *args, **kwargs):
""" Return the total number of <part> allocated to <build> """
return build.getAllocatedQuantity(part) | 84c94ca4e1b1006e293851189d17f63fc992b420 | 3,658,829 |
def stat_threshold(Z,mce='fdr_bh',a_level=0.05,side='two',copy=True):
"""
Threshold z maps
Parameters
----------
mce: multiple comparison error correction method, should be
among of the options below. [defualt: 'fdr_bh'].
The options are from statsmodels packages:
... | 3c582c0a59f8bd5544f8620870732562200f4f0a | 3,658,830 |
def esmf_grid(lon, lat, periodic=False, mask=None):
"""
Create an ESMF.Grid object, for constructing ESMF.Field and ESMF.Regrid.
Parameters
----------
lon, lat : 2D numpy array
Longitute/Latitude of cell centers.
Recommend Fortran-ordering to match ESMPy internal.
Shape... | 8087cfbf0c4923338984913dcd1a421e3a46dd29 | 3,658,831 |
def convert_to_numeral(decimal_integer: int, roman_format="brackets"):
"""Convert decimal to Roman numeral.
roman_format is a str containing either 'brackets' or 'latex'
The default option, 'brackets', converts 3,000,000,000 to [[MMM]] and
3,000,000 to [MMM].
'latex' outputs a LaTeX formula for th... | ebfd2b323879bcca9e20be0d9598104bf0f31e33 | 3,658,833 |
def transpose(x):
"""Tensor transpose """
return np.transpose(x) | 286c7e36629ff8e38ad5d0233bd1f8fd823514f2 | 3,658,834 |
from typing import Optional
from typing import List
from typing import Tuple
def greedy_reduction_flat(m: Mat2) -> Optional[List[Tuple[int, int]]]:
"""Returns a list of tuples (r1,r2) that specify which row should be added to which other row
in order to reduce one row of m to only contain a single 1.
In c... | 85c8098dd6e727abe64c3d1410c63161309b5135 | 3,658,835 |
def estimate_psd(vec, num_segs=DEFAULT_NUM_SEGS, overlap=DEFAULT_OVERLAP, dt=DEFAULT_DT, tukey_alpha=DEFAULT_TUKEY_ALPHA, one_sided=True):
"""
estimates the PSD using a DFT
divides vec into "num_segs" with a fractional overlap of "overlap" between neighbors
returns the average PSD from t... | 1c2d8c51bfd75d617f75dbc4aa3304c05c36e899 | 3,658,836 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.