content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def puzzles():
"""
Pick one of the TOP95 puzzle strings
"""
return [l for l in TOP95.split("\n") if l] | def2fefe114fe2867f2d465dbe4b55ae74287e09 | 3,639,700 |
from datetime import datetime
def test_declarative_sfc_obs_full(ccrs):
"""Test making a full surface observation plot."""
data = pd.read_csv(get_test_data('SFC_obs.csv', as_file_obj=False),
infer_datetime_format=True, parse_dates=['valid'])
obs = PlotObs()
obs.data = data
o... | 780b4462ba01ddcd20a1e87ef8637ca174293af8 | 3,639,701 |
def standardize_ants_data(ants_data, subject_ID_col):
""" Takes df from ANTs output and stadardizes column names for both left and right hemi
"""
ants_useful_cols = ['Structure Name']
ants_to_std_naming_dict = {}
ants_to_std_naming_dict['Structure Name'] = subject_ID_col #'SubjID'
for roi in ant... | 0f5216fd75244b0b9b60fdcdf05d63bfd02a2ed9 | 3,639,702 |
def make_gridpoints(bbox, resolution=1, return_coords=False):
"""It constructs a grid of points regularly spaced.
Parameters
----------
bbox : str, GeoDataFrame or dict.
Corresponds to the boundary box in which the grid will be formed.
If a str is provided, it should be in '(S,W,N,E)' f... | 8ccc5b257666cb8bd3a87662c6b021b4ed49ccb9 | 3,639,703 |
def removeElement_2(nums, val):
"""
Using one loop and two pointers
Don't preserve order
"""
# Remove the elment from the list
i = 0
j = len(nums) - 1
count = 0
while i < j:
if nums[i] == val:
while j > i and nums[j] == val:
j -= 1
pr... | e1a836514a09fc925a49b144880960b057dfff80 | 3,639,704 |
def decrypt_ballot_shares(
request: DecryptBallotSharesRequest = Body(...),
scheduler: Scheduler = Depends(get_scheduler),
) -> DecryptBallotSharesResponse:
"""
Decrypt this guardian's share of one or more ballots
"""
ballots = [
SubmittedBallot.from_json_object(ballot) for ballot in req... | c10b9961c2f86e9d9cf26d75e276cd65b3dcfdc4 | 3,639,705 |
def returnHumidity(dd):
""" Returns humidity data if it exists in the dictionary"""
rh = []
if 'RH' in dd:
rh = dd['RH']
elif 'RH1' in dd:
rh = dd['RH1']
else:
# Convert the dew point temperature to relative humidity
Pmb = dd['airpres']/10 # hPa to mb
rh = air... | b51d5d23247780683d9d644f59e442b1c77210e8 | 3,639,706 |
def fixture_penn_chime_raw_df_no_beta(penn_chime_setup) -> DataFrame:
"""Runs penn_chime SIR model for no social policies
"""
p, simsir = penn_chime_setup
n_days = simsir.raw_df.day.max() - simsir.raw_df.day.min()
policies = [(simsir.beta, n_days)]
raw = sim_sir(
simsir.susceptible,
... | 8e1d654b4e171e8ab55023bfb55135d5067d7052 | 3,639,707 |
import json
import hashlib
def _verify_manifest_signature(manifest, text, digest):
"""
Verify the manifest digest and signature
"""
format_length = None
format_tail = None
if 'signatures' in manifest:
for sig in manifest['signatures']:
protected_json = _jose_decode_base64(... | d3c5cebcb6f63723d7356be8def0824bb3cd2726 | 3,639,708 |
from typing import List
from typing import Optional
from typing import Dict
import logging
def create_hierarchy(
src_assets: List[Asset],
dst_assets: List[Asset],
project_src: str,
runtime: int,
client: CogniteClient,
subtree_ids: Optional[List[int]] = None,
subtree_external_ids: Optional[... | 54ec8460f6eaedee44c0cdeb423da2a757d018a7 | 3,639,709 |
def ETL_work():
""" ETL page"""
return render_template("ETL_work.html") | 08806ed7154f4820db961b54a5c852bd0c275532 | 3,639,710 |
def advanced_perm_check_function(*rules_sets, restrictions=None):
"""
Check channels and permissions, use -s -sudo or -a -admin to run it.
Args:
*rules_sets: list of rules, 1d or 2d,
restrictions: Restrictions must be always met
Returns:
message object returned by calling given f... | acf6f5494fcc632fec3bb665778a6bed3e58f19d | 3,639,711 |
def worker_id():
"""Return a predefined worker ID.
Returns:
int: The static work id
"""
return 123 | 8c8e9c570a2355a15fd9a4d1d03d0159a33ffba0 | 3,639,712 |
def get_urls(spec):
"""Small convenience method to construct the URLs of the Jupyter server."""
host_url = f"http{'s' if spec['routing']['tls']['enabled'] else ''}://{spec['routing']['host']}"
full_url = urljoin(
host_url,
spec["routing"]["path"].rstrip("/"),
)
return host_url, full_... | 059913ed12b021fce5964d54bf8b9b22132f914f | 3,639,713 |
def resubs(resubpairs,target):
"""takes several regex find replace pairs [(find1, replace1), (find2,replace2), ... ]
and applies them to a target on the order given"""
return resubpair[0].sub(resubpair[1],target)
for resubpair in resubpairs:
target = resub(resubpair,target)
return target | 49b371211de991c323fdec313801aba0ded8ff93 | 3,639,714 |
import functools
import time
def time_profile(func):
"""Time Profiled for optimisation
Notes:
* Do not use this in production
"""
@functools.wraps(func)
def profile(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} : {tim... | a4dde1d66f5987b4be1e9179da1570c252540363 | 3,639,715 |
from typing import Type
import uuid
from datetime import datetime
async def create_guid(data: GuidIn) -> Type[GuidOut]:
"""
Create a record w/o specifying a guid.
Also cleans up expired records & caches the new record.
"""
guid = uuid.uuid4().hex
validated = data.dict()
try:
awai... | 0ff0f95acc6268e5ccd081156cc9355c8db520db | 3,639,716 |
def exp_for(iterable, filename, display = False):
"""
Run an experiment for words in given iterable and save its
results to PATH_RESULTS/filename. If display is set to True, also
print output to screen.
The output is formated as follows:
[word]RESULT_SEP[size]RESULT_SEP[n+x]RESULT_SEP[diff wit... | 11933d4b4c77dcae354b307cb27ab27af3e49311 | 3,639,717 |
import argparse
def arg_parse():
"""
Parse arguments to the detect module
"""
parser = argparse.ArgumentParser(description='YOLO v3 Detection Module')
parser.add_argument("--bs", dest="bs", help="Batch size", default=1)
parser.add_argument("--confidence", dest="confidence", help="Object Confid... | 24ec26a23278b59d09f12df3950faa9996828958 | 3,639,718 |
import re
def remove_useless_lines(text):
"""Removes lines that don't contain a word nor a number.
Args:
text (string): markdown text that is going to be processed.
Returns:
string: text once it is processed.
"""
# Useless lines
useless_line_regex = re.compile(r'^[^\w\n]*$', re.MULTILINE | re.UNICODE)
pr... | fd33cdb243b6887d11846736f922bb4e1332d549 | 3,639,719 |
def get_candidate(word):
"""get candidate word set
@word -- the given word
@return -- a set of candidate words
"""
candidates = set()
candidates |= meanslike(word)
candidates |= senselike(word)
# remove '_' and '-' between words --> candidates is a LIST now
candidates = [w.replac... | 8e2b7359f681cd96bb1ddad68cbfe77c1ae2e79b | 3,639,720 |
def _build_proxy_response(response: RawResponse, error_handler: callable) -> dict:
"""Once the application completes the request, maps the results into the format required by
AWS.
"""
try:
if response.caught_exception is not None:
raise response.caught_exception
message = ''.... | c07e52da6c6e952c35bda18b9d5600d756280f9b | 3,639,721 |
from typing import Dict
from typing import Any
def parse_and_execute(config: dict) -> Dict[str, Any]:
"""Validate, parse and transform the config. Execute backends based
on the transformed config to perform I/O operations.
If `prompt` and/or `default` contains a macro, it will be expanded.
:param co... | dd350df8b282aa5fa459b89aedc000c326d4923d | 3,639,722 |
def reduce_any(input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
Wrapper around the tf.reduce_any to handle argument keep_dims
"""
return reduce_function(tf.reduce_any, input_tensor, axis=axis,
keepdims=keepdims, name=name,
... | bdf25f573caef2d9c0926c92d8ce4b4a3b682775 | 3,639,723 |
def get_customer_profile_ids():
"""get customer profile IDs"""
merchantAuth = apicontractsv1.merchantAuthenticationType()
merchantAuth.name = constants.apiLoginId
merchantAuth.transactionKey = constants.transactionKey
CustomerProfileIdsRequest = apicontractsv1.getCustomerProfileIdsRequest()
Cus... | ba6cb076870961b4ab226b2aeb3ab07b1b5eb848 | 3,639,724 |
from typing import List
def compare_alignments_(prediction: List[dict], ground_truth: List[dict], types: List[str]) -> (float, float, float):
"""
Parameters
----------
prediction: List of dictionaries containing the predicted alignments
ground_truth: List of dictionaries containing the ground trut... | 57648544c152bff0acc52271d453b58a0d8e8cad | 3,639,725 |
import inspect
def shim_unpack(
unpack_fn, # type: TShimmedFunc
download_dir, # type str
tempdir_manager_provider, # type: TShimmedFunc
ireq=None, # type: Optional[Any]
link=None, # type: Optional[Any]
location=None, # type Optional[str],
hashes=None, # type: Optional[Any]
progr... | 561d473584da5f96cbffadb543cee129c9c6e0ef | 3,639,726 |
def xavier_uniform(x):
"""Wrapper for torch.nn.init.xavier_uniform method.
Parameters
----------
x : torch.tensor
Input tensor to be initialized. See torch.nn.init.py for more information
Returns
-------
torch.tensor
Initialized tensor
"""
return init.xavier_unifor... | f407fa3e35d1bd708e6cfe4b003a788bed4eb443 | 3,639,727 |
import pyzo.util.interpreters as interps ### EKR
import os
def _get_interpreters_win(): # pyzo_in_leo.py
"""
Monkey-patch pyzo/util/interpreters._get_interpreters_win.
This patched code fixes an apparent pyzo bug.
Unlike shutil.which, this function returns all plausible python executables.
... | 35b64945c0531b34f5733b9587a9000e70a9e4e3 | 3,639,728 |
def create_test_data(site, start=None, end="now", interval=5, units='minutes' , val=50, db='test_db', data={}):
"""
data = {'R1':[0,0,0,..],'R2':[0,0,123,12,...]...} will not generate date but use fixed data set
if val is not set random data will be generated if data is not existing
"""
... | 56e5f65650a2fb1eb2a829d9443cd0a588402c3a | 3,639,729 |
def Nmin(e, dz, s, a, a_err):
"""Estimates the minimum number of independent structures
to detect a difference in dN/dz w/r to a field value given
by dNdz|field = a +- a_err, at a statistical significance s,
using a redshift path of dz per structure"""
e = np.array(e).astype(float)
dz = np.array... | c603f90e35802b6b7401c14abda3bb350d0e6941 | 3,639,730 |
import string
def remove_punctuation(list_of_string, item_to_keep=""):
"""
Remove punctuation from a list of strings.
Parameters
----------
- list_of_string : a dataframe column or variable containing the text stored as a list of string sentences
- item_to_keep : a string of punctuation ... | cb9190bc160f8e725479b531afab383c6857ceac | 3,639,731 |
import requests
import pickle
def save_sp500_tickers(force_download=False):
"""Get the S&P 500 tickers from Wikipedia
Parameters
----------
force_download : bool
if True, force redownload of data
Returns
-------
tickers : pandas.DataFrame
The S&P50... | 94ddf34acbda542fe039f988887b904bb2ac9da4 | 3,639,732 |
def get_search_keywords(testcase):
"""Get search keywords for a testcase."""
crash_state_lines = testcase.crash_state.splitlines()
# Use top 2 frames for searching.
return crash_state_lines[:2] | 15c1611aeff33f9d8bba843f076b31abfb4023ba | 3,639,733 |
def make_protein_index(proteins):
"""Indexes proteins
"""
prot_index = {}
skip = set(['sp', 'tr', 'gi', 'ref', ''])
for i, p in enumerate(proteins):
accs = p.accession.split('|')
for acc in accs:
if acc in skip:
continue
prot_index[acc] = i
... | be54ca3a123fe13efbb8c694187dd34d944fd654 | 3,639,734 |
def jvp_solve_Hz(g, Hz, info_dict, eps_vec, source, iterative=False, method=DEFAULT_SOLVER):
""" Gives jvp for solve_Hz with respect to eps_vec """
# construct the system matrix again and the RHS of the gradient expersion
A = make_A_Hz(info_dict, eps_vec)
ux = spdot(info_dict['Dxb'], Hz)
uy = sp... | 0d861f9c6a899c70da7d095cb6ac436586e75bdd | 3,639,735 |
from typing import Union
def encode(X: Union[tf.Tensor, np.ndarray], encoder: keras.Model, **kwargs) -> tf.Tensor:
"""
Encodes the input tensor.
Parameters
----------
X
Input to be encoded.
encoder
Pretrained encoder network.
Returns
-------
Input encoding.
... | a97abdc611643e4cd1ed944ff27ef7402e824acb | 3,639,736 |
def _step2(input):
"""
_step2 - function to apply step2 rules
Inputs:
- input : str
- m : int
Measurement m of c.v.c. sequences
Outputs:
- input : str
"""
# ational -> ate
if input.endswith('ational') and _compute_m(input[:-7]) > 0:
return input[:-1 * len('ational')] + 'ate'
# tional -> tion
elif in... | 5181d55de4ef7c33778dfbe80707e4e621018d5c | 3,639,737 |
from typing import cast
def compute_annualized_volatility(srs: pd.Series) -> float:
"""
Annualize sample volatility.
:param srs: series with datetimeindex with `freq`
:return: annualized volatility (stdev)
"""
srs = hdataf.apply_nan_mode(srs, mode="fill_with_zero")
ppy = hdataf.infer_samp... | 517d56e53885fdcb5eee3ed0fa3acae766d9c7e2 | 3,639,738 |
from datetime import datetime
def json_sanitized(value, stringify=stringified, dt=str, none=False):
"""
Args:
value: Value to sanitize
stringify (callable | None): Function to use to stringify non-builtin types
dt (callable | None): Function to use to stringify dates
none (str ... | 6f50e3bb5a07417b05cb95813d2cc5a89ad12a2b | 3,639,739 |
def rescan_organization_task(task, org, allpr, dry_run, earliest, latest):
"""A bound Celery task to call rescan_organization."""
meta = {"org": org}
task.update_state(state="STARTED", meta=meta)
callback = PaginateCallback(task, meta)
return rescan_organization(org, allpr, dry_run, earliest, latest... | 2241bf6630bdd63c231f011708ac392c3d1a8234 | 3,639,740 |
def python(cc):
"""Format the character for a Python string."""
codepoint = ord(cc)
if 0x20 <= codepoint <= 0x7f:
return cc
if codepoint > 0xFFFF:
return "\\U%08x" % codepoint
return "\\u%04x" % codepoint | b0c2042c653043c0831a35ffc13d73850e29af2f | 3,639,741 |
import logging
def stop_execution(execution_id):
"""
Stop the current workflow execution.
swagger_from_file: docs/stop.yml
"""
name = execution_id # str | the custom object's name
body = kubernetes.client.V1DeleteOptions() # V1DeleteOptions |
grace_period_seconds = 56 # int | The durati... | d7d4264a81f106de31c49d5825de114a20f79966 | 3,639,742 |
def reshape_signal_batch(signal):
"""Convert the signal into a standard batch shape for use with cochleagram.py
functions. The first dimension is the batch dimension.
Args:
signal (array): The sound signal (waveform) in the time domain. Should be
either a flattened array with shape (n_samples,), a row ... | 344ce1a9a695e99fa470a5d849afb40bc381c9df | 3,639,743 |
import scipy
import itertools
def tryallmedoids(dmat, c, weights=None, potential_medoid_inds=None, fuzzy=True, fuzzyParams=('FCM', 2)):
"""Brute force optimization of k-medoids or fuzzy c-medoids clustering.
To apply to points in euclidean space pass dmat using:
dmat = sklearn.neighbors.DistanceMetric.ge... | 34ba39d57bdce6b52b3c5e8eef085ef928d02038 | 3,639,744 |
from typing import Union
def human_timedelta(s: Union[int, float]) -> str:
"""Convert a timedelta from seconds into a string using a more sensible unit.
Args:
s: Amount of seconds
Returns:
A string representing `s` seconds in an easily understandable way
"""
if s >= MONTH_SECONDS... | 84725ecf4e4d59d423505978b8255f96a6483cd0 | 3,639,745 |
from functools import reduce
def rate_cell(cell, board, snake, bloom_level=4):
""" rates a cell based on proximity to other snakes, food, the edge of the board, etc """
cells = []
# Get all the cells of "bloom_level" number of circles surrounding the given cell.
for x in range(-bloom_level, bloom_lev... | ab78b4b822789b32e2a768dcb9d55f5398b34a13 | 3,639,746 |
def edges_are_same(a, b):
"""
Function to check if two tuple elements (src, tgt, val) correspond
to the same directed edge (src, tgt).
Args:
tuple_elements : a = (src, val, val) and b = (src, val, val)
Returns:
True or False
"""
if a[0:2] == b[0:2]:
return True
... | 04c4d414402a57cafa0028d0ecd140bedd2539d7 | 3,639,747 |
def conv_mrf(A, B):
"""
:param A: conv kernel 1 x 120 x 180 x 1 (prior)
:param B: input heatmaps: hps.batch_size x 60 x 90 x 1 (likelihood)
:return: C is hps.batch_size x 60 x 90 x 1
"""
B = tf.transpose(B, [1, 2, 3, 0])
B = tf.reverse(B, axis=[0, 1]) # [h, w, 1, b], we flip kernel to get c... | 5bca01b656b135f20325441ebcbcfac883627565 | 3,639,748 |
from typing import Dict
from typing import Tuple
def get_alert_by_id_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]:
"""Get alert by id and return outputs in Demisto's format
Args:
client: Client object with request
args: Usually demisto.args()
Returns:
Outputs
... | 74208c66627e2441ff62ad6b4207844241ab7cd6 | 3,639,749 |
def close_issues() -> list[res.Response]:
"""Batch close issues on GitHub."""
settings = _get_connection_settings(CONFIG_MANAGER.config)
try:
github_service = ghs.GithubService(settings)
except ghs.GithubServiceError as gse:
return [res.ResponseFailure(res.ResponseTypes.RESOURCE_ERROR, g... | ac59a72b893ebc91090d3ba38a1cbf6cb8844be1 | 3,639,750 |
def _invert_lambda(node: tn.Node) -> tn.Node:
"""Invert a diagonal lambda matrix. """
tensor = node.get_tensor()
assert _is_diagonal_matrix(tensor)
diagonal = tensor.diagonal()
return tn.Node(np.diag(1/diagonal)) | b5c06728b1e88bedec7d19591f0aa4823e90f412 | 3,639,751 |
def map_field_name_to_label(form):
"""Takes a form and creates label to field name map.
:param django.forms.Form form: Instance of ``django.forms.Form``.
:return dict:
"""
return dict([(field_name, field.label)
for (field_name, field)
in form.base_fields.items()]) | dfc2779f498fb479553602a72d9520d398746302 | 3,639,752 |
from typing import Callable
from typing import List
def solve_compound_rec(
recurrence_func: Callable,
parameter_list: List[float],
std_of_compound_dist: float,
max_mRNA_copy_number: int,
recursion_length: int,
index_compound_parameter: int = 3,
compounding_distribution: str = "normal",
... | 22e9106872ed185cf635fe958707da4244eee60c | 3,639,753 |
def create_brand():
"""
Creates a new brand with the given info
:return: Status of the request
"""
check = check_brand_parameters(request)
if check is not None:
return check
name = request.json[NAME]
brand = Brand.query.filter(Brand.name == name).first()
if brand is not Non... | 5c745aa1050b574cc659cf17bc06d1bdeb424b13 | 3,639,754 |
import os
def update(args):
"""Traverse third-party repos / submodules and emit version-strings"""
failures = []
ver = "///< This file is autogenerated by 'scripts/xnvme_3p.py'\n"
ver += "const char *xnvme_3p_ver[] = {\n"
for project, err in traverse_projects(args):
print("project: %s, s... | bb66e6d49f8c255d68bac75c7ead8bb53b6753c7 | 3,639,755 |
def feature_contained(boundary: geo, **kwargs):
"""Analyse containment for all features within a single-layer vector file according to a Geometry
and return multiple GeoJSON files."""
geom, prop = kwargs["geom"], kwargs["prop"]
if isinstance(geom, geo.Polygon):
prop["valid"] = boundary.contains(... | 5fbad0dbb915dfa5e422bfeb356a63d4290df07d | 3,639,756 |
import time
def compute(n=26):
""" Computes 2 to the power of n and returns elapsed time"""
start = time.time()
res = 0
for i in range(2**n):
res += 1
end = time.time()
dt = end - start
print(f'Result {res} in {dt} seconds!')
return dt | d816c587302830f0acd20a59905c8634fcf20b49 | 3,639,757 |
from re import S
import mpmath
def _real_to_rational(expr, tolerance=None, rational_conversion='base10'):
"""
Replace all reals in expr with rationals.
Examples
========
>>> from sympy import Rational
>>> from sympy.simplify.simplify import _real_to_rational
>>> from sympy.abc import x
... | ce685079459e3bc6e19decc2f22c3bc8198411c0 | 3,639,758 |
import multiprocessing
import itertools
import functools
def run(block, epsilon, ratio, prng, alpha=2, beta=1.2, gamma=1.0, theta=None, verbose=False):
"""Run HDPView
1st phase, divide blocks.
2nd phase, perturbation.
Prepare parameters and execute HDPView
Args:
block (CountTa... | 51a7f9f8a739de76b3c8b188a2d0495f42be1cbe | 3,639,759 |
def wait_for_view(class_name):
"""
Waits for a View matching the specified class. Default timeout is 20 seconds.
:param class_name:the {@link View} class to wait for
:return:{@code true} if the {@link View} is displayed and {@code false} if it is not displayed before the timeout
"""
return get_... | 8829f1af924540d92923c1ce44742f8d4d223ca8 | 3,639,760 |
def _create_table():
"""helper for crc calculation"""
table = []
for i in range(256):
k = i
for _ in range(8):
if k & 1:
k = (k >> 1) ^ 0xEDB88320
else:
k >>= 1
table.append(k)
return table | 830317e62dcfb7bca63f1186b46a2882e0bb399f | 3,639,761 |
def average_syllables(verses):
"""
Takes a list of verses
Returns the mean number of syllables among input verses
"""
verse_count = len(verses)
syll_counts = list(map(count_syllables, verses))
syll_count = sum(syll_counts)
return syll_count / verse_count | 4cb4d53431b5ccaa2c4ca08083242089feb61be5 | 3,639,762 |
def _create_subplots_if_needed(ntotal,
ncols=None,
default_ncols=1,
fieldorder='C',
avoid_single_column=False,
sharex=False,
sharey=Fa... | d164cd0d73632fcbcb38face930e2aa5c7300728 | 3,639,763 |
def template_file_counter(session, templates, fetch_count=False):
"""Create template file counter."""
file_counts = {}
default_count = None
if fetch_count:
file_counts = TemplatesDAO.query_file_counts(session=session, templates=templates)
default_count = 0
def counter(template: Temp... | 9a931e11385cba0c7f2968740cc8059da341cd50 | 3,639,764 |
def _init_matrices_nw(aln1, aln2, gap_open_penalty, gap_extend_penalty):
"""initialize score matrix and traceback matrix for global alignment
Parameters
----------
aln1 : list
list of activities, which is the first sequence to be aligned
aln2 : list
list of activities, which is the ... | 46c4426a5570ed9dceb0409b5bd4ac2ccb8efb10 | 3,639,765 |
import re
def parse_path_params(end_point_path):
"""Parse path parameters."""
numeric_item_types = ['Lnn', 'Zone', 'Port', 'Lin']
params = []
for partial_path in end_point_path.split('/'):
if (not partial_path or partial_path[0] != '<' or
partial_path[-1] != '>'):
c... | 895c3b3663c33a6883ba34d7bbfb20de1491910d | 3,639,766 |
def read_pid_stat(pid="self"):
"""
Returns system process stat information.
:param pid: The process ID.
:returns: The system stat information.
:rtype: dict
"""
with open("/proc/%s/stat" % (pid,), "rb") as f:
stat = f.readline().split()
return {
"utime": int(stat[13]),
... | 5ec6b21b09372e71e6dcf8c60f418bcbc4beee64 | 3,639,767 |
def simple_split_with_list(x, y, train_fraction=0.8, seed=None):
"""Splits data stored in a list.
The data x and y are list of arrays with shape [batch, ...].
These are split in two sets randomly using train_fraction over the number of
element of the list. Then these sets are returned with
the arra... | c99ae6507b934b42577949ee3a9226e68e870da9 | 3,639,768 |
from typing import Tuple
def save_correlation_heatmap_results(
correlations: pd.DataFrame, intensity_label: str = "Intensity", show_suptitle: bool = True,
close_plots: str = "all", exp_has_techrep: bool = False, **kwargs
) -> Tuple[plt.Figure, plt.Axes]:
"""
Saves the plot with prefix: {{name}... | 78f2bffcd9fc200ad152aa95177ba3a3bb6f3c3c | 3,639,769 |
def get_star(star_path, verbose=False, recreate=False):
"""Return a varconlib.star.Star object based on its name.
Parameters
----------
star_path : str
A string representing the name of the directory where the HDF5 file
containing a `star.Star`'s data can be found.
Optional
---... | f6ccd804e5998e42a0fb4d1d4368e2d65244d855 | 3,639,770 |
import glob
import os
def get_terminal_map():
"""Get a map of device-id -> path as a dict.
Used by Process.terminal()
"""
ret = {}
ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
for name in ls:
assert name not in ret, name
try:
ret[os.stat(name).st_rdev] = na... | 50a4f56e3e2db87a620ab97f485b776c6ac35b6c | 3,639,771 |
import os
def targets(inventory="/etc/ansible/hosts", **kwargs):
"""
Return the targets from the ansible inventory_file
Default: /etc/salt/roster
"""
if not os.path.isfile(inventory):
raise CommandExecutionError("Inventory file not found: {}".format(inventory))
extra_cmd = []
if "... | 630d525ef671dcc62c1cd7ae600bb95e3f8c97d5 | 3,639,772 |
from datetime import datetime
def get_relative_days(days):
"""Calculates a relative date/time in the past without any time offsets.
This is useful when a service wants to have a default value of, for example 7 days back. If an ISO duration format
is used, such as P7D then the current time will be factore... | 58e429708e7d1c3cbda88c09bfb978f32cb1892a | 3,639,773 |
def find_pending_trade(df):
""" Find the trade value according to its sign like negative number means Sell type
or positive number means Buy """
p_df = pd.DataFrame()
p_df['Type'] = df['Buy_Qty'] - df['Sell_Qty']
return p_df['Type'].map(lambda val: trade_type_conversion(val)) | 1e764929cb047b6d8314732902dcc273176c924b | 3,639,774 |
def rtri(x, a, b):
"""Convolution of rect(ax) with tri(bx)."""
assert a > 0
assert b > 0
return b*(step2(x + 1/(2*a) + 1/b) - 2*step2(x + 1/(2*a)) + step2(x + 1/(2*a) - 1/b) - step2(x - 1/(2*a) + 1/b) + 2*step2(x - 1/(2*a)) - step2(x - 1/(2*a) - 1/b)) | 74745bf680507a2d3627c31c14ccc24db4b2d2d1 | 3,639,775 |
def make_xgboost_predict_extractor(
eval_shared_model: tfma.EvalSharedModel,
eval_config: tfma.EvalConfig,
) -> extractor.Extractor:
"""Creates an extractor for performing predictions using a xgboost model.
The extractor's PTransform loads and runs the serving pickle against
every extract yielding a copy... | 01c44814023e2c960ec695ee8a7282f2a9d0b21f | 3,639,776 |
def training_dataset() -> Dataset:
"""Creating the dataframe."""
data = {
"record1": [
{"@first_name": "Hans", "@last_name": "Peter"},
{"@first_name": "Heinrich", "@last_name": "Meier"},
{"@first_name": "Hans", "@last_name": "Peter"},
],
"record2": [
... | 1d3ecc780044036aa8f8425abf8dba556649af98 | 3,639,777 |
def getWCSForcamera(cameraname, crpix1, crpix2):
""" Return SIP non-linear coordiante correction object intialized for a camera from a lookup table.
If the camera is not in the lookup table, an identify transformation is returned.
TODO: variable order, so far limit ouselves to second order
TODO: Time... | f2905e16eada7b3f4806b9a5db7fba065283de6c | 3,639,778 |
def get_full_frac_val(r_recalc,fs,diff_frac=0,bypass_correction=0):
"""
Compute total offset in number of samples, and also fractional sample correction.
Parameters
----------
r_recalc : float
delay.
fs : float
sampling frequency.
diff_frac : 0
[unused] 0 b... | 23bf8326472844b16c87ac28e1065156bf20ce8b | 3,639,779 |
import inspect
def get_code():
"""
returns the code for the min cost path function
"""
return inspect.getsource(calculate_path) | bad3e06b11b0897b9225ffc9ab6dc81972f4442b | 3,639,780 |
import functools
def box_net(images,
level,
num_anchors,
num_filters,
is_training,
act_type,
repeats=4,
separable_conv=True,
survival_prob=None,
strategy=None,
data_format='channels_last'):
"""Box... | 8caab72f716c0f754efb82467556a5b016d2f72e | 3,639,781 |
from typing import Set
def get_distance_to_center(
element: object, centers: "Set[object]", distance_function: "function"
) -> float:
"""
Returns the distance from the given point to its center
:param element: a point to get the distance for
:param centers: an iteratable of the center points
... | bd4a400e5a98711d00c5c236ce02945bd2014719 | 3,639,782 |
def auto_delete_file_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem when corresponding
`Worksheet` object is updated with a new file.
"""
if not instance.pk:
return False
db_obj = Worksheet.objects.get(pk=instance.pk)
exists = True
try:
old_f... | 2ab584fffbe2224109c4d4ea0446c22650df493f | 3,639,783 |
def clean_immigration_data(validPorts: dict, immigration_usa_df: psd.DataFrame, spark: pss.DataFrame) -> psd.DataFrame:
"""[This cleans immigration data in USA. It casts date of immigrant entry, city of destination, and port entry.]
Args:
validPorts (dict): [dictionery that includes valid entry ports i... | 8746f0f4e35745d653549c32c5a804422d22c588 | 3,639,784 |
from pathlib import Path
def prepare(args: dict, overwriting: bool) -> Path:
"""Load config and key file,create output directories and setup log files.
Args:
args (dict): argparser dictionary
Returns:
Path: output directory path
"""
output_dir = make_dir(args, "results_tmp", "ag... | dca02f4180e91423fa61e8da36e9ac095dbe3ca4 | 3,639,785 |
def dd_wave_function_array(x, u_array, Lx):
"""Returns numpy array of all second derivatives
of waves in Fourier sum"""
coeff = 2 * np.pi / Lx
f_array = wave_function_array(x, u_array, Lx)
return - coeff ** 2 * u_array ** 2 * f_array | d815afe12916643c46fcc7b8f108ce5aad840e3b | 3,639,786 |
from typing import Iterable
import os
def plot_energy_fluxes(solver, fsrs, group_bounds=None, norm=True,
loglog=True, get_figure=False):
"""Plot the scalar flux vs. energy for one or more FSRs.
The Solver must have converged the FSR sources before calling this routine.
The routine ... | e640a70b9f002f41755bc6dfbec45121f237f27f | 3,639,787 |
def handle_health_check():
"""Return response 200 for successful health check"""
return Response(status=200) | 3ff055a7dc5e1318dd0e283ace87399c54e361b2 | 3,639,788 |
def pow(x, n):
""" pow(x, n)
Power function.
"""
return x**n | 09d62a68607bf0dab8b380a0c3ee58c6ed4497d6 | 3,639,789 |
def download_cad_model():
"""Download cad dataset."""
return _download_and_read('42400-IDGH.stl') | 1f7aad5ed9c8f62ffef16cb3f44207b83aced204 | 3,639,790 |
def dot_product(u, v):
"""Computes dot product of two vectors u and v, each represented as a tuple
or list of coordinates. Assume the two vectors are the same length."""
output = 0
for i in range(len(u)):
output += (u[i]*v[i])
return output | 6362776bef32870d3b380aecbb2037483e049092 | 3,639,791 |
from datetime import datetime
def precise_diff(
d1, d2
): # type: (typing.Union[datetime.datetime, datetime.date], typing.Union[datetime.datetime, datetime.date]) -> PreciseDiff
"""
Calculate a precise difference between two datetimes.
:param d1: The first datetime
:type d1: datetime.datetime or... | 21c2a2a275ce23e8282c0563218d4aacc1f0accd | 3,639,792 |
import utool as ut # NOQA
import importlib
import utool as ut
import utool as ut
from xdoctest import docscrape_google
from xdoctest import core as xdoc_core
from xdoctest import static_analysis as static
import types
import sys
import inspect
def get_module_doctest_tup(
testable_list=None,
check_flags=True,... | ac7f2fd69180ce7ca24651ae585a7bf55c624399 | 3,639,793 |
def subset_lists(L, min_size=0, max_size=None):
"""Strategy to generate a subset of a `list`.
This should be built in to hypothesis (see hypothesis issue #1115), but was rejected.
Parameters
----------
L : list
List of elements we want to get a subset of.
min_size : int
Minimum... | 1ad343ed6459c12b6c454c71505e8cfa04e9e36e | 3,639,794 |
def DCNPack(x, extra_feat, out_channels, kernel_size=(3, 3), strides=(1, 1), padding='same', dilations=(1, 1),
use_bias=True, num_groups=1, num_deform_groups=1, trainable=True, dcn_version='v2', name='DCN'):
"""Deformable convolution encapsulation that acts as normal convolution layers."""
with tf.v... | 091669ff8608c2783916d042bac2b2756ca25973 | 3,639,795 |
def endtiming(fn):
"""
Decorator used to end timing.
Keeps track of the count for the first and second calls.
"""
NITER = 10000
def new(*args, **kw):
ret = fn(*args, **kw)
obj = args[0]
if obj.firststoptime == 0:
obj.firststoptime = time.time()
elif ob... | 493fd06b0c28ef1c8c4f3c38c555cf5e52013d80 | 3,639,796 |
def CreateRailFrames(thisNurbsCurve, parameters, multiple=False):
"""
Computes relatively parallel rail sweep frames at specified parameters.
Args:
parameters (IEnumerable<double>): A collection of curve parameters.
Returns:
Plane[]: An array of planes if successful, or an empty array ... | bf62e197d6b7cb83453b43ce441eb062000ca069 | 3,639,797 |
def news(stock):
"""analyzes analyst recommendations using keywords and assigns values to them
:param stock: stock that will be analyzed
:return recommendations value"""
stock = yf.Ticker(str(stock))
reco = str(stock.recommendations) # Stands for recomend
reco = reco.split()
reco.revers... | 2385f5c212c8802e6572b6efe69c1c791a68c261 | 3,639,798 |
def get_pulse_coefficient(pulse_profile_dictionary, tt):
"""
This function generates an envelope that smoothly goes from 0 to 1, and back down to 0.
It follows the nomenclature introduced to me by working with oscilloscopes.
The pulse profile dictionary will contain a rise time, flat time, and fall tim... | 1db21359bbbcec44214752ecb5c08a6ee0592593 | 3,639,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.