content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def linspace(
start,
stop,
num=50,
endpoint=True,
retstep=False,
dtype=None,
split=None,
device=None,
comm=None,
):
"""
Returns num evenly spaced samples, calculated over the interval [start, stop]. The endpoint of the interval can
optionally be excluded.
Parameters
... | 19,500 |
def _h1_cmp_chi2_ ( h1 ,
h2 ,
density = False ) :
"""Compare histograms by chi2
>>> h1 = ... ## the first histo
>>> h2 = ... ## the second histo (or function or anything else)
>>> chi2ndf , probability = h1.cmp_chi2 ( h2 )
"""
... | 19,501 |
def _questionnaire_metric(name, col):
"""Returns a metrics SQL aggregation tuple for the given key/column."""
return _SqlAggregation(
name,
"""
SELECT {col}, COUNT(*)
FROM participant_summary
WHERE {summary_filter_sql}
GROUP BY 1;
""".format(
col=col, su... | 19,502 |
def xyzToAtomsPositions(xyzFileOrStr):
"""
Returns atom positions (order) given a molecule in an xyz format.
Inchi-based algorithm.
Use this function to set the atoms positions in a reference
molecule. The idea is to assign the positions once and to never
change them again.
Arguments:
... | 19,503 |
def read_LFW(fname):
""" read LFW dataset annotation information with names and labels... """
# dir = os.getcwd()
# os.chdir(dirname)
if not os.path.exists(fname):
raise ValueError('LFW File :' + fname + 'does not exist')
lines = open(fname).readlines();
print lines
for l in lines:
... | 19,504 |
async def modify_video_favorite_list(
media_id: int,
title: str,
introduction: str = '',
private: bool = False,
credential: Credential = None):
"""
修改视频收藏夹信息。
Args:
media_id (int) : 收藏夹 ID.
title (str) : 收藏夹名。
... | 19,505 |
def get_salesforce_log_files():
"""Helper function to get a list available log files"""
return {
"totalSize": 2,
"done": True,
"records": [
{
"attributes": {
"type": "EventLogFile",
"url": "/services/data/v32.0/sobjects/... | 19,506 |
def remove_true_false_edges(dict_snapshots, dict_weights, index):
"""
Remove chosen true edges from the graph so the embedding could be calculated without them.
:param dict_snapshots: Dict where keys are times and values are a list of edges for each time stamp.
:param dict_weights: Dict where keys are t... | 19,507 |
def _make_mutable(obj):
"""
Context manager that makes the tree mutable.
"""
with _MUTABLE_CONTEXT.update(prev_mutable={}):
try:
apply(_make_mutable_fn, obj, inplace=True)
yield
finally:
apply(_revert_mutable_fn, obj, inplace=True) | 19,508 |
def addFavoriteDir(name:str, directory:str, type:str=None, icon:str=None, tooltip:str=None, key:str=None):
"""
addFavoriteDir(name, directory, type, icon, tooltip, key) -> None.
Add a path to the file choosers favorite directory list. The path name can contain environment variables which will be expanded w... | 19,509 |
def save(data):
"""Save cleanup annotations."""
data_and_frames = data.split("_")
data = data_and_frames[0]
frames = data_and_frames[1]
if len(data) == 1:
removed = []
else:
removed = [int(f) for f in data[1:].split(':')]
frames = [int(f) for f in frames[:].split(':')]
... | 19,510 |
def search(search_term):
"""Searches the FRED database using a user provided
search term."""
continue_search = True
page_num = 1
while continue_search:
complete_search_term = ' '.join(search_term)
metadata = api.search_fred(complete_search_term, page=page_num)
data = metad... | 19,511 |
def download_data(date_string):
"""Download weekly prices in XLS and save them to file"""
main_url = 'http://fcainfoweb.nic.in/PMSver2/Reports/Report_Menu_web.aspx'
params = 'MainContent_ToolkitScriptManager1_HiddenField=%3B%3BAjaxControlToolkit%2C+Version%3D4.1.51116.0%2C+Culture%3Dneutral%2C+PublicKeyTok... | 19,512 |
def list_runs_in_swestore(path, pattern=RUN_RE, no_ext=False):
"""
Will list runs that exist in swestore
:param str path: swestore path to list runs
:param str pattern: regex pattern for runs
"""
try:
status = check_call(['icd', path])
proc = Popen(['ils'], stdout=PI... | 19,513 |
def linear_regression(
XL: ArrayLike, YP: ArrayLike, Q: ArrayLike
) -> LinearRegressionResult:
"""Efficient linear regression estimation for multiple covariate sets
Parameters
----------
XL
[array-like, shape: (M, N)]
"Loop" covariates for which N separate regressions will be run
... | 19,514 |
def wait_for_visible_link(driver):
""" Wait for any link of interest to be visible. """
wait_time = 0
while wait_time < MAX_WAIT_SECONDS:
for link in LINKS:
if is_link_visible(driver, link):
return
time.sleep(1)
wait_time += 1
raise TimeoutException | 19,515 |
def scrape(domains, links):
"""
Scrape the given list of links and pickle the output to a file containing a
dict of <category, dict of link, document> pairs and a dict of {link,
set(links)}.
args:
domains - list of base urls
links - list of page paths
"""
pool = Pool(10)
... | 19,516 |
def orthogonal_decomposition(C, tr_error, l_exp):
"""
Orthogonal decomposition of the covariance matrix to determine the meaningful directions
:param C: covariance matrix
:param tr_error: allowed truncation error
:param l_exp: expansion order
:return: transformation matrix Wy, number of terms ... | 19,517 |
def get_data():
"""Reads the current state of the world"""
server = http.client.HTTPConnection(URL)
server.request('GET','/data')
response = server.getresponse()
if (response.status == 200):
data = response.read()
response.close()
return json.loads(data.decode())
else:
... | 19,518 |
def chi_angles(filepath, model_id=0):
"""Calculate chi angles for a given file in the PDB format.
:param filepath: Path to the PDB file.
:param model_id: Model to be used for chi calculation.
:return: A list composed by a list of chi1, a list of chi2, etc.
"""
torsions_list = _sidechain_torsio... | 19,519 |
def callback(ch, method, properties, body):
"""Callback that has the message that was received"""
vol_prefix = os.getenv('VOL_PREFIX', '')
workers = load_workers()
d = setup_docker()
pipeline = json.loads(body.decode('utf-8'))
worker_found = False
status = {}
extra_workers = {}
for w... | 19,520 |
def surface_sphere(radius):
"""
"""
phi, theta = np.mgrid[0.0:np.pi:100j, 0.0:2.0*np.pi:100j]
x_blank_sphere = radius*np.sin(phi)*np.cos(theta)
y_blank_sphere = radius*np.sin(phi)*np.sin(theta)
z_blank_sphere = radius*np.cos(phi)
sphere_surface = np.array(([x_blank_sphere,
... | 19,521 |
def p_domain(p):
"""domain : domain_def requirements_def types_def predicates_def action_def
| domain_def requirements_def types_def predicates_def function_def action_def"""
if len(p) == 6:
p[0] = Domain(p[1], p[2], p[3], p[4], p[5])
else:
p[0] = Domain(p[1], p[2], p[3], p[4... | 19,522 |
def test_create_layout():
"""Checks if axes for regular and detailed plots were created
properly.
Summary
-------
We pass different stages and plot levels to pipeline.create_layout,
and check the resulting axes.
Expected
--------
- pipeline.create_layout(1, 0) should not return axe... | 19,523 |
def schema_upgrades():
"""schema upgrade migrations go here."""
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('build', 'git_tag', new_column_name='vcs_ref')
op.add_column('build', sa.Column('ver', sa.String(), nullable=False, server_default='0.0.0.0'))
op.alter_column... | 19,524 |
def format_bucket_objects_listing(bucket_objects):
"""Returns a formated list of buckets.
Args:
buckets (list): A list of buckets objects.
Returns:
The formated list as string
"""
import re
import math
out = ""
i = 1
for o in bucket_objects:
... | 19,525 |
def load_white_list() -> None:
"""Loads the whitelist."""
with OpenJson(PLAYERS_DATA_PATH + "whitelist.json") as whitelist_file:
data = whitelist_file.load()
for account_id in data:
CacheData.whitelist.append(account_id) | 19,526 |
def test_decode_ssdp_packet_v6():
"""Test SSDP response decoding."""
msg = (
b"HTTP/1.1 200 OK\r\n"
b"Cache-Control: max-age=1900\r\n"
b"Location: http://[fe80::2]:80/RootDevice.xml\r\n"
b"Server: UPnP/1.0 UPnP/1.0 UPnP-Device-Host/1.0\r\n"
b"ST:urn:schemas-upnp-org:servi... | 19,527 |
def charts(chart_type, cmid, start_date, end_date=None):
"""
Get the given type of charts for the artist.
https://api.chartmetric.com/api/artist/:id/:type/charts
**Parameters**
- `chart_type`: string type of charts to pull, choose from
'spotify_viral_daily', 'spotify_viral_weekly',
... | 19,528 |
def session_setup(request):
"""
Auto session resource fixture
"""
pass | 19,529 |
def test_condition_one_condition_pair():
"""
GIVEN PolicyStatementCondition object.
WHEN Created PolicyStatementCondition object with 'condition_operator','condition_statements attributes.
THEN Object created with desired attributes.
"""
cond_statement = PolicyStatementCondition(
conditi... | 19,530 |
def config():
"""Do various things related to config.""" | 19,531 |
def fake_traceback(exc_value, tb, filename, lineno):
"""Produce a new traceback object that looks like it came from the
template source instead of the compiled code. The filename, line
number, and location name will point to the template, and the local
variables will be the current template context.
... | 19,532 |
def search_candidates(api_key, active_status="true"):
"""
https://api.open.fec.gov/developers#/candidate/get_candidates_
"""
query = """https://api.open.fec.gov/v1/candidates/?sort=name&sort_hide_null=false&is_active_candidate={active_status}&sort_null_only=false&sort_nulls_last=false&page=1&per_page=20... | 19,533 |
def load_dat(file_name):
"""
carga el fichero dat (Matlab) especificado y lo
devuelve en un array de numpy
"""
data = loadmat(file_name)
y = data['y']
X = data['X']
ytest = data['ytest']
Xtest = data['Xtest']
yval = data['yval']
Xval = data['Xval']
return X,y,Xtest,ytest,... | 19,534 |
def get_specific_pos_value(img, pos):
"""
Parameters
----------
img : ndarray
image data.
pos : list
pos[0] is horizontal coordinate, pos[1] is verical coordinate.
"""
return img[pos[1], pos[0]] | 19,535 |
def postorder(dirUp,catchment,node,catch,dirDown):
"""
routine to run a postoder tree traversal
:param dirUp:
:param catchment:
:param node:
:param catch:
:param dirDown:
:return: dirDown and catchment
"""
if dirUp[node] != []:
postorder(dirUp,catchment,dirUp[node][0],ca... | 19,536 |
def transpose_tokens(
cards: List[MTGJSONCard]
) -> Tuple[List[MTGJSONCard], List[Dict[str, Any]]]:
"""
Sometimes, tokens slip through and need to be transplanted
back into their appropriate array. This method will allow
us to pluck the tokens out and return them home.
:param cards: Cards+Tokens... | 19,537 |
def test_jdbc_query_executor_failed_query_event(sdc_builder, sdc_executor, database):
"""Simple JDBC Query Executor test for failed-query event type.
Pipeline will try to insert records into a non-existing table and the query would fail.
Event records are verified for failed-query event type.
This is a... | 19,538 |
def from_local(local_dt, timezone=None):
"""Converts the given local datetime to a universal datetime."""
if not isinstance(local_dt, datetime.datetime):
raise TypeError('Expected a datetime object')
if timezone is None:
a = arrow.get(local_dt)
else:
a = arrow.get(local_dt, time... | 19,539 |
def mrefresh_to_relurl(content):
"""Get a relative url from the contents of a metarefresh tag"""
urlstart = re.compile('.*URL=')
_, url = content.split(';')
url = urlstart.sub('', url)
return url | 19,540 |
def mock_mikrotik_api():
"""Mock an api."""
with patch("librouteros.connect"):
yield | 19,541 |
def simclr_loss_func(
z1: torch.Tensor,
z2: torch.Tensor,
temperature: float = 0.1,
extra_pos_mask=None,
) -> torch.Tensor:
"""Computes SimCLR's loss given batch of projected features z1 from view 1 and
projected features z2 from view 2.
Args:
z1 (torch.Tensor): NxD Tensor containing... | 19,542 |
def find_node_types(G, edge_type):
"""
:param G: NetworkX graph.
:param edge_type: Edge type.
:return: Node types that correspond to the edge type.
"""
for e in G.edges:
if G[e[0]][e[1]][e[2]]['type'] == edge_type:
u, v = e[0], e[1]
break
utype = G.nodes[u]['... | 19,543 |
def distance_point_point(p1, p2):
"""Calculates the euclidian distance between two points or sets of points
>>> distance_point_point(np.array([1, 0]), np.array([0, 1]))
1.4142135623730951
>>> distance_point_point(np.array([[1, 1], [0, 0]]), np.array([0, 1]))
array([1., 1.])
>>> distance_point_po... | 19,544 |
def plotInfluential ( InferenceObject ):
"""Diagnostic plot for detecting influential observations
Determining influential observations follows a different logic for bootstrap
and for bayes inference. A block is labelled an influential observation if
the fit for a dataset without that point is signific... | 19,545 |
def switch(
confs=None, remain=False, all_checked=False, _default=None, **kwargs
):
"""
Execute first statement among conf where task result is True.
If remain, process all statements conf starting from the first checked
conf.
:param confs: task confs to check. Each one may contain a task a... | 19,546 |
def makeProcesses(nChildren):
"""
Create and start all the worker processes
"""
global taskQueue,resultsQueue,workers
if nChildren < 0:
print 'makeProcesses: ',nChildren, ' is too small'
return False
if nChildren > 3:
print 'makeProcesses: ',nChildren, ' is too large... | 19,547 |
def create_moleculenet_model(model_name):
"""Create a model.
Parameters
----------
model_name : str
Name for the model.
Returns
-------
Created model
"""
for func in [create_bace_model, create_bbbp_model, create_clintox_model, create_esol_model,
create_free... | 19,548 |
def detect_daml_lf_dir(paths: "Collection[str]") -> "Optional[str]":
"""
Find the biggest Daml-LF v1 version in the set of file names from a Protobuf archive, and return
the path that contains the associated files (with a trailing slash).
If there is ever a Daml-LF 2, then this logic will need to be re... | 19,549 |
def random_mini_batches(X, Y, mini_batch_size):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (m, n_H, n_W, c)
Y -- true "label" vector of shape (m, num_classes)
mini_batch_size -- size of mini-batches, integer
Returns:
mini_ba... | 19,550 |
def classifyContent(text):
"""
Uses the NLP provider's SDK to perform a content classification operation.
Arguments:
text {String} -- Text to be analyzed.
"""
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT,
language='en')
try:
... | 19,551 |
def print_matrix(matrice: np.ndarray):
"""Stampa a video della Mappa"""
str_ = ""
for i in range(len(matrice)):
for j in range(len(matrice)):
if matrice[i][j] == 0:
str_ += Back.BLACK + " "
elif matrice[i][j] == 1:
str_ += Back.WHITE + " "
... | 19,552 |
def print_instance_summary(instance, use_color='auto'):
""" Print summary info line for the supplied instance """
colorize_ = partial(colorize, use_color=use_color)
name = colorize_(instance.name, "yellow")
instance_type = instance.extra['gonzo_size']
if instance.state == NodeState.RUNNING:
... | 19,553 |
def cli(input_file=None, part=None):
"""
CLI entry point
"""
result = process(input_file, part)
print(result) | 19,554 |
def test_local_time_string_raises_v_020_010():
"""local_time_string() with bad t_format type raises SimplEthError"""
bad_format_type = 100
with pytest.raises(SimplEthError) as excp:
Convert().local_time_string(bad_format_type)
assert excp.value.code == 'V-020-010' | 19,555 |
def generate_blob_sas_token(blob, container, blob_service, permission=BlobPermissions.READ):
"""Generate a blob URL with SAS token."""
sas_token = blob_service.generate_blob_shared_access_signature(
container, blob.name,
permission=permission,
start=datetime.datetime.utcnow() - datetime.... | 19,556 |
def rewrite_complex_signature(function, signature: Sequence[tf.TensorSpec]):
"""Compatibility layer for testing complex numbers."""
if not all([spec.dtype.is_complex for spec in signature]):
raise NotImplementedError("Signatures with mixed complex and non-complex "
"tensor specs ar... | 19,557 |
def get_args(argv: list):
"""gets the args and dictionarize them"""
if len(argv) not in [5,7]:
Errors.args_error()
data = {}
# getting the type of the title
if "-" in argv[1]:
data["type"] = "series" if argv[1] == "-s" else "movie" if argv[1] == "-m" else None
else:
... | 19,558 |
def random(
reason: str,
current_dir: Path = Path("."),
) -> None:
"""Roll the dice and email the result."""
logger = getLogger(__name__)
config = MailsConfig.from_global_paths(GlobalPaths.from_defaults(current_dir))
names = list(config.to)
name = choice(names)
logger.info(f"I've drawn {... | 19,559 |
def fund_with_erc20(
to_fund_address, erc20_token_contract, ether_amount=0.1, account=None
):
"""Send a specified amount of an ERC20 token to an address.
Args:
to_fund_address (address): Address to send to the tokens to.
erc20_token_contract (Contract): Contract of the ERC20 token.
... | 19,560 |
def test_tensor_from_cache_empty(tensor_key):
"""Test get works returns None if tensor key is not in the db."""
db = TensorDB()
cached_nparray = db.get_tensor_from_cache(tensor_key)
assert cached_nparray is None | 19,561 |
async def test_form(opp):
"""Test we get the form."""
await setup.async_setup_component(opp, "persistent_notification", {})
result = await opp.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] ... | 19,562 |
def energy_adj_ground_to_sig_end(ds):
"""
Waveform energy from the ground peak. We calculated senergy_whrc as the energy of the waveform (in digital counts) from the ground peak
to the signal end multiplied by two. Ground peak defined as whichever of the two lowest peaks has greater amplitude. We then appl... | 19,563 |
def profile(args, model, model_info, device):
"""
Profile.
:param model:
:param model_info:
:return:
"""
import copy
from torch.profiler import profile, record_function, ProfilerActivity
model = copy.deepcopy(model)
model = model.to(device)
model.eval()
inputs = tuple(
... | 19,564 |
def get_previous_version(versions: dict, app: str) -> str:
"""Looks in the app's .version_history to retrieve the prior version"""
try:
with open(f"{app}/.version_history", "r") as fh:
lines = [line.strip() for line in fh]
except FileNotFoundError:
logging.warning(f"No .version_h... | 19,565 |
def validate_marktlokations_id(self, marktlokations_id_attribute, value):
"""
A validator for marktlokations IDs
"""
if not value:
raise ValueError("The marktlokations_id must not be empty.")
if not _malo_id_pattern.match(value):
raise ValueError(f"The {marktlokations_id_attribute.na... | 19,566 |
def healthcheck() -> bool:
"""FastAPI server healthcheck."""
return True | 19,567 |
def test_unsigned_short_enumeration004_1782_unsigned_short_enumeration004_1782_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=enumeration and value=0 1 234
and document value=0
"""
assert_bindings(
schema="msData/datatypes/Facets/unsignedShort/unsignedShort_e... | 19,568 |
def copy_media_files(from_dir, to_dir, exclude=None, dirty=False):
"""
Recursively copy all files except markdown and exclude[ed] files into another directory.
`exclude` accepts a list of Unix shell-style wildcards (`['*.py', '*.pyc']`).
Note that `exclude` only operates on file names, not directories.... | 19,569 |
def frames_to_masks(
nproc: int,
out_paths: List[str],
colors_list: List[List[np.ndarray]],
poly2ds_list: List[List[List[Poly2D]]],
with_instances: bool = True,
) -> None:
"""Execute the mask conversion in parallel."""
with Pool(nproc) as pool:
pool.starmap(
partial(frame... | 19,570 |
def test_branched_history_with_mergepoint(pytester):
"""Branched history can be navigated, when there's a mergepoint present."""
run_pytest(pytester, passed=5) | 19,571 |
def ToHexStr(num):
"""
将返回的错误码转换为十六进制显示
:param num: 错误码 字符串
:return: 十六进制字符串
"""
chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
hexStr = ""
if num < 0:
num = num + 2**32
while num >= 16:
digit = num % 16
hexStr = chaDic.get(digit, str(digit)) ... | 19,572 |
def getSBMLFromBiomodelsURN(urn):
""" Get SBML string from given BioModels URN.
Searches for a BioModels identifier in the given urn and retrieves the SBML from biomodels.
For example:
urn:miriam:biomodels.db:BIOMD0000000003.xml
Handles redirects of the download page.
:param urn:
:ret... | 19,573 |
def dataclass_validate(instance: Any) -> None:
"""Ensure values in a dataclass are correct types.
Note that this will always fail if a dataclass contains field types
not supported by this module.
"""
_dataclass_validate(instance, dataclasses.asdict(instance)) | 19,574 |
def draw(k, n):
"""
Select k things from a pool of n without replacement.
"""
# At k == n/4, an extra 0.15*k draws are needed to get k unique draws
if k > n/4:
result = rng.permutation(n)[:k]
else:
s = set()
result = np.empty(k, 'i')
for i in range(k):
... | 19,575 |
def print_version(args):
"""Print the version (short or long)"""
# Long version
if len(args) > 0 and args[0] == '--full':
apk_version = dtfglobals.get_generic_global(
dtfglobals.CONFIG_SECTION_CLIENT, 'apk_version')
bundle_version = dtfglobals.get_generic_global(
dt... | 19,576 |
async def test_get_start_entries_by_race_id(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
race: dict,
start_entry: dict,
) -> None:
"""Should return OK and a valid json body."""
START_ENTRY_ID = start_entry["id"]
mocker.patch(
"race_service.adapters.start_entries... | 19,577 |
def naturalTimeDifference(value):
"""
Finds the difference between the datetime value given and now()
and returns appropriate humanize form
"""
from datetime import datetime
if isinstance(value, datetime):
delta = datetime.now() - value
if delta.days > 6:
return v... | 19,578 |
def test_specific_location(client, user, db_setup, tag_data):
"""specific_location is an optional field. If it is included in the
posted data, it will be correctly associated with the recovery
object in the database.
"""
report = Report.objects.get(reported_by__first_name="Homer")
url = rever... | 19,579 |
def raises_Invalid(function):
"""A decorator that asserts that the decorated function raises
dictization_functions.Invalid.
Usage:
@raises_Invalid
def call_validator(*args, **kwargs):
return validators.user_name_validator(*args, **kwargs)
call_validator(key, data, error... | 19,580 |
def load_dataset(dataset_path: Path) -> [Instruction]:
"""Returns the program as a list of alu instructions."""
with open_utf8(dataset_path) as file:
program = []
for line in file:
if len(line.strip()) > 0:
instruction = line.strip().split(" ")
if len(... | 19,581 |
def test_document_delete1(flask_client, user8, dev_app):
"""document() DELETE should delete one item."""
doc = user8.documents.first()
access_token = api.create_token(user8, dev_app.client_id)
response = flask_client.delete(
"/api/documents/" + str(doc.id), headers={"authorization": "Bearer " + ... | 19,582 |
def process_info(args):
"""
Process a single json file
"""
fname, opts = args
with open(fname, 'r') as f:
ann = json.load(f)
f.close()
examples = []
skipped_instances = 0
for instance in ann:
components = instance['components']
if len(components[0][... | 19,583 |
def test_uncharge():
"""All charges should be neutralized."""
assert _uncharge_smiles("CNCC([O-])C[O-]") == "CNCC(O)CO" | 19,584 |
def logout():
"""
退出登录
:return:
"""
# pop是移除session中的数据(dict),pop会有一个返回值,如果移除的key不存在返回None
session.pop('user_id', None)
session.pop('mobile', None)
session.pop('nick_name', None)
# 要清除is_admin的session值,不然登录管理员后退出再登录普通用户又能访问管理员后台
session.pop('is_admin', None)
return jsonify(er... | 19,585 |
def test_dun_depth_method_on_single_bst(bst):
"""Test the _depth method on single bst."""
assert bst._depth(bst.root) == 1 | 19,586 |
def lift_to_dimension(A,dim):
"""
Creates a view of A of dimension dim (by adding dummy dimensions if necessary).
Assumes a numpy array as input
:param A: numpy array
:param dim: desired dimension of view
:return: returns view of A of appropriate dimension
"""
current_dim = len(A.shape... | 19,587 |
def search(keyword=None):
"""
Display search results in JSON format
Parameters
----------
keyword : str
Search keyword. Default None
"""
return get_json(False, keyword) | 19,588 |
def min_offerings(heights: List[int]) -> int:
"""
Get the max increasing sequence on the left and the right side of current index,
leading upto the current index.
current index's value would be the max of both + 1.
"""
length = len(heights)
if length < 2:
return length
left_inc... | 19,589 |
def pretty(value, width=80, nl_width=80, sep='\n', **kw):
# type: (str, int, int, str, **Any) -> str
"""Format value for printing to console."""
if isinstance(value, dict):
return '{{{0} {1}'.format(sep, pformat(value, 4, nl_width)[1:])
elif isinstance(value, tuple):
return '{}{}{}'.form... | 19,590 |
def get_csv_file_path(file_name: str) -> str:
"""
Get absolute path to csv metrics file
Parameters
----------
file_name
Name of metrics file
Returns
-------
file_path
Full path to csv file
"""
return os.path.join(os.getcwd(), file_name) | 19,591 |
def test_drop_mrel_column(pipeline, clean_db):
"""
Verify that we can't drop matrel columns
"""
pipeline.create_stream('mrel_drop_s', x='integer')
q = """
SELECT x, sum(x), avg(x), count(*) FROM mrel_drop_s GROUP BY x
"""
pipeline.create_cv('mrel_drop_cv', q)
for col in ('x', 'sum', 'avg', 'count'):
... | 19,592 |
def failed(config: dict, app_logger: logger.Logger) -> bool:
"""
Set migration status to FAILED.
:param config: pymigrate configuration.
:param app_logger: pymigrate configured logger.
:return: True on success, False otherwise.
"""
app_logger.log_with_ts('Running status_failed action for m... | 19,593 |
async def test_face_event_call_no_confidence(mock_config, hass, aioclient_mock):
"""Set up and scan a picture and test faces from event."""
face_events = await setup_image_processing_face(hass)
aioclient_mock.get(get_url(hass), content=b"image")
common.async_scan(hass, entity_id="image_processing.demo_... | 19,594 |
def niceNumber(v, maxdigit=6):
"""Nicely format a number, with a maximum of 6 digits."""
assert(maxdigit >= 0)
if maxdigit == 0:
return "%.0f" % v
fmt = '%%.%df' % maxdigit
s = fmt % v
if len(s) > maxdigit:
return s.rstrip("0").rstrip(".")
elif len(s) == 0:
return ... | 19,595 |
def query_incident(conditions: list, method=None, plan_status="A", mulitple_fields=False):
"""
Queries incidents in Resilient/CP4S
:param condition_list: list of conditions as [field_name, field_value, method] or a list of list conditions if multiple_fields==True
:param method: set all field conditions... | 19,596 |
def test_no_value():
"""When no value is given we should return Failure."""
test = [[], '-']
with pytest.raises(UnwrapFailedError):
apply_separator(*test).unwrap() | 19,597 |
def get_banner():
"""Return a banner message for the interactive console."""
global _CONN
result = ''
# Note how we are connected
result += 'Connected to %s' % _CONN.url
if _CONN.creds is not None:
result += ' as %s' % _CONN.creds[0]
# Give hint about exiting. Most people exit wi... | 19,598 |
def generate_fish(
n,
channel,
interaction,
lim_neighbors,
neighbor_weights=None,
fish_max_speeds=None,
clock_freqs=None,
verbose=False,
names=None
):
"""Generate some fish
Arguments:
n {int} -- Number of fish to generate
channel {Channel} -- Channel instance... | 19,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.