content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import scipy
def memory_kernel_logspace(dt, coeffs, dim_x, noDirac=False):
"""
Return the value of the estimated memory kernel
Parameters
----------
dt: Timestep
coeffs : Coefficients for diffusion and friction
dim_x: Dimension of visible variables
noDirac: Remove the dirac at time ze... | 21e6aed08bebd91f359efa216ab1331cf9ace310 | 3,654,276 |
def _is_constant(x, atol=1e-7, positive=None):
"""
True if x is a constant array, within atol
"""
x = np.asarray(x)
return (np.max(np.abs(x - x[0])) < atol and
(np.all((x > 0) == positive) if positive is not None else True)) | 0b272dd843adbd4eaa4ebbe31efe6420de05a6dd | 3,654,277 |
def estimate_M(X, estimator, B, ratio):
"""Estimating M with Block or incomplete U-statistics estimator
:param B: Block size
:param ratio: size of incomplete U-statistics estimator
"""
p = X.shape[1]
x_bw = util.meddistance(X, subsample = 1000)**2
kx = kernel.KGauss(x_bw)
if estimator ==... | 656b83eac9e522b1feb20a4b5b56649b9553ecb0 | 3,654,278 |
def query_yes_no(question, default="yes"):
"""Queries user for confimration"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = "... | 58e9bba831155ca9f4d4879a5e960949757b0562 | 3,654,279 |
import base64
import binascii
def decode(password, encoded, notice):
"""
:type password: str
:type encoded: str
"""
dec = []
try:
encoded_bytes = base64.urlsafe_b64decode(encoded.encode()).decode()
except binascii.Error:
notice("Invalid input '{}'".format(encoded))
... | 5cf82bfbbe7eee458914113f648dadbe7b15dee8 | 3,654,280 |
from functools import reduce
def replace(data, replacements):
""" Allows to performs several string substitutions.
This function performs several string substitutions on the initial ``data`` string using a list
of 2-tuples (old, new) defining substitutions and returns the resulting string.
"""
r... | 37b2ad5b9b6d50d81a8c1bcded9890de3c840722 | 3,654,282 |
def fake_kafka() -> FakeKafka:
"""Fixture for fake kafka."""
return FakeKafka() | 35fdcf2030dda1cab2be1820549f67dc246cf88f | 3,654,283 |
from typing import Union
import operator
def rr20(prec: pd.Series) -> Union[float, int]:
"""Function for count of heavy precipitation (days where rr greater equal 20mm)
Args:
prec (list): value array of precipitation
Returns:
np.nan or number: the count of icing days
"""
assert ... | 4686eccac5be53b4a888d8bf0649c72e65d81bdb | 3,654,284 |
def get_neg_label(cls_label: np.ndarray, num_neg: int) -> np.ndarray:
"""Generate random negative samples.
:param cls_label: Class labels including only positive samples.
:param num_neg: Number of negative samples.
:return: Label with original positive samples (marked by 1), negative
samples (m... | 3cd0ad5c1973eff969330f014c405f39092b733b | 3,654,285 |
def G12(x, a):
"""
Eqs 20, 24, 25 of Khangulyan et al (2014)
"""
alpha, a, beta, b = a
pi26 = np.pi ** 2 / 6.0
G = (pi26 + x) * np.exp(-x)
tmp = 1 + b * x ** beta
g = 1.0 / (a * x ** alpha / tmp + 1.0)
return G * g | 6b84d5f5978a9faf8c9d77a2b9351f73f5717f48 | 3,654,286 |
def binomial(n, k):
""" binomial coefficient """
if k < 0 or k > n:
return 0
if k == 0 or k == n:
return 1
num = 1
den = 1
for i in range(1, min(k, n - k) + 1): # take advantage of symmetry
num *= (n + 1 - i)
den *= i
c = num // den
return c | 78910202202f749f8e154b074a55f6a5ddf91f64 | 3,654,287 |
def pagination(page):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator = page.paginator
page_num = page.number
#pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if False: #not pagination_required:
page_range = []
e... | 60d90adfbeceab9d159652b641e60da8fa995954 | 3,654,288 |
def bubbleSort(arr):
"""
>>> bubbleSort(arr)
[11, 12, 23, 25, 34, 54, 90]
"""
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr | 28bc9d505ef44a4b403c0f91a971cccf74644c5a | 3,654,289 |
def generate_kronik_feats(fn):
"""Generates features from a Kronik output file"""
header = get_tsv_header(fn)
return generate_split_tsv_lines(fn, header) | 8b98f346ef5d833e0bfb876a7985c8bb3ced905c | 3,654,290 |
def delete_product(uuid: str, db: Session = Depends(auth)):
"""Delete a registered product."""
if product := repo.get_product_by_uuid(db=db, uuid=uuid):
if product.taken:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Cannot delete prod... | 97aa45eec0ae98a58984f8ca97d584b5a715cba6 | 3,654,292 |
import functools
def CreateMnemonicsC(mnemonicsIds):
""" Create the opcodes arrays for C header files. """
opsEnum = "typedef enum {\n\tI_UNDEFINED = 0, "
pos = 0
l2 = sorted(mnemonicsIds.keys())
for i in l2:
s = "I_%s = %d" % (i.replace(" ", "_").replace(",", ""), mnemonicsIds[i])
if i != l2[-1]:
s += ",... | a20a01fbefc1175c24144753264edc938258cdca | 3,654,293 |
import math
def create_windows(c_main, origin, J=None, I=None, depth=None, width=None):
"""
Create windows based on contour and windowing parameters. The first
window (at arc length = 0) is placed at the spline origin.
Note: to define the windows, this function uses pseudo-radial and
pseudo-angul... | c5e3989b8f8f0f558cdc057b6f3bb9901c4363cf | 3,654,294 |
from bs4 import BeautifulSoup
def extractsms(htmlsms) :
"""
extractsms -- extract SMS messages from BeautifulSoup tree of Google Voice SMS HTML.
Output is a list of dictionaries, one per message.
"""
msgitems = [] # accum message items here
# Extract all conversations by searching ... | e31a66ae5ee56faf4eab131044c395fcd8de3a2a | 3,654,295 |
def load_ch_wubi_dict(dict_path=e2p.E2P_CH_WUBI_PATH):
"""Load Chinese to Wubi Dictionary.
Parameters
---------
dict_path : str
the absolute path to chinese2wubi dictionary.
In default, it's E2P_CH_WUBI_PATH.
Returns
-------
dict : Dictionary
a mapping between Chine... | e9297968b5dc4d1811659084e03ef0b2156c8a00 | 3,654,296 |
def middle_flow(middle_inputs: Tensor) -> Tensor:
"""
Middle flow
Implements the second of the three broad parts of the model
:param middle_inputs: middle_inputs: Tensor output generate by the Entry Flow,
having shape [*, new_rows, new_cols, 728]
:return: Out... | 80fedffbb6da2f3e0b99a931d66d593bf627bdbe | 3,654,297 |
def feature_extraction(sample_index, labels, baf, lrr, rawcopy_pred, data_shape, margin=10000, pad_val=-2):
"""
Extract features at sample index
:param sample_index: sample index
:param labels: break point labels
:param baf: b-allele frequency values
:param lrr: ... | 2b70229d3e4021d4a0cce9bf7dce2222956e299d | 3,654,298 |
def get_filename(file_fullpath):
"""
Returns the filename without the full path
:param file_fullpath:
:return: Returns the filename
"""
filename = file_fullpath.split("/")[-1].split(".")[0]
return filename | 903cb26c89d1d18c9ebafe1a468c7fa66c51f119 | 3,654,299 |
def create_and_assign_household(humans_with_same_house, housetype, conf, city, allocated_humans):
"""
Creates a residence and allocates humans in `humans_with_same_house` to the same.
Args:
humans_with_same_house (list): a list of `Human` objects which are to be allocated to the same residence of t... | 594830aec1c820de94f7277499239f19e51ba0de | 3,654,300 |
import torch
def make_positions(tensor, padding_idx):
"""Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1. Padding symbols are ignored.
"""
# The series of casts and type-conversions here are carefully
# balanced to both work with ONNX export and XL... | f86f5485ddd3400161d9e233ad66cc492fd6d277 | 3,654,302 |
import click
def init():
"""Top level command handler."""
@click.command()
@click.option('--policy-servers', type=cli.LIST,
required=True,
help='Warpgate policy servers')
@click.option('--service-principal', type=str,
default='host',
... | fcadaa48fead63b10431bf509f4f4398216be564 | 3,654,303 |
def load(file):
"""unpickle an object from a file"""
pik = Unpickler(file)
pik._main = _main_module
obj = pik.load()
if type(obj).__module__ == getattr(_main_module, '__name__', '__main__'):
# point obj class to main
try: obj.__class__ = getattr(pik._main, type(obj).__name__)
... | 22050da1c2ff891180ce9581a1cf2c6f1cf9e0b9 | 3,654,304 |
def setup(app):
"""Set up the Sphinx extension."""
app.add_config_value(
name="doctr_versions_menu_conf", default={}, rebuild="html",
)
app.connect('builder-inited', ext.add_versions_menu_js_file)
app.connect('build-finished', ext.cleanup)
return {
"version": __version__,
... | 01173da317d1058811b01842be8492265ac0a62b | 3,654,306 |
import click
def get_help_recursive(group, ctx, commands):
"""
Returns help for arbitrarily nested subcommands of the given click.Group.
"""
try:
command_name = commands.pop(0)
group = group.get_command(ctx, command_name)
if not group:
raise click.ClickException('In... | 412f0cb9e9aa1f19caf4a4a5db95c8040a0d2f36 | 3,654,308 |
def clump_tracker(fprefix, param=None, directory=None, nsmooth=32, verbose=True):
"""
Finds and tracks clumps over a simulation with multiple time steps and
calculates various physical properties of the clumps.
Runs all the steps necessary to find/track clumps, these are:
get_fnames
pF... | bc72ae48e152ada388aa2421290d41d9865fa439 | 3,654,309 |
def OptimizeGraph(config_proto,
metagraph,
verbose=True,
graph_id=b'graph_to_optimize',
cluster=None,
strip_default_attributes=False):
"""Optimize the provided metagraph.
For best results, the signature_def field in `metagrap... | 0d1fc74ffe6c16da953b9ac711534b125afb82d6 | 3,654,310 |
def parse_imei(msg):
"""Parse an IMEI (in BCD format) into ASCII format."""
imei = ''
for octet in msg[1:]:
imei += imei_parse_nibble(ord(octet) & 0x0f)
imei += imei_parse_nibble(ord(octet) >> 4)
return imei | 664d9472b51dd806b28b2b2ecee1047307e4e15a | 3,654,312 |
def get_blender_frame_time(skeleton, frame_id, rate, time_scale, actor_id):
"""Goes from multi-actor integer frame_id to modded blender float time."""
# stays within video frame limits
frame_id2 = skeleton.mod_frame_id(frame_id=frame_id) # type: int
time_ = skeleton.get_time(frame_id)
if actor_id >... | ca8ab45dbbb1b28b05894b9dd92529245441c60b | 3,654,313 |
from ..plots.wx_symbols import wx_code_to_numeric
from datetime import datetime
import contextlib
def parse_metar(metar_text, year, month, station_metadata=station_info):
"""Parse a METAR report in text form into a list of named tuples.
Parameters
----------
metar_text : str
The METAR report
... | 3660aeda77343c1bb21729b6b0d36ce597c5ca0d | 3,654,314 |
def update_facemap_material(self, context):
""" Assign the updated material to all faces belonging to active facemap
"""
set_material_for_active_facemap(self.material, context)
return None | 61e5f05cd059ca7646609f4d65f0bb86aaaebc8a | 3,654,315 |
def calculate_accuracy(y_true, y_pred):
"""Calculates the accuracy of the model.
Arguments:
y_true {numpy.array} -- the true labels corresponding to each input
y_pred {numpy.array} -- the model's predictions
Returns:
accuracy {str} -- the accuracy of the model (%)
... | 1ea14f8e4f50d13e2ae557aeec466c5372b99171 | 3,654,316 |
def resolve_diff_args(args):
"""Resolve ambiguity of path vs base/remote for git:
Cases:
- No args: Use defaults
- One arg: Either base or path, check with is_gitref.
- Two args or more: Check if first two are base/remote by is_gitref
"""
base = args.base
remote = args.remote
pat... | 6260d69bffd8a4a4d35471c5710c9a86324f9549 | 3,654,317 |
def get_coco_metrics_from_gt_and_det(groundtruth_dict, detection_boxes_list, category=''):
"""
Get COCO metrics given dictionary of groundtruth dictionary and the list of
detections.
"""
coco_wrapped_groundtruth = coco_tools.COCOWrapper(groundtruth_dict)
coco_wrapped_detections = coco_wrapped_gr... | fbf6ca237f43c74ebe37772006c856f3a1850683 | 3,654,318 |
def createDataset(dataPath,dStr,sigScale=1):
"""
dStr from ["20K", "1M", "10M"]
"""
print("Loading D1B dataset...")
ft1_d = loadD1B(dataPath,dStr,w=40)
if dStr=="20K":
ft1_d = ft1_d[:10000,:]
print("Running PCA on D1B")
pcaD1B = PCA(n_components=ft1_d.shape[1],random_state... | 02cf1b4a5708abf6d7e3fee323c5fb096fdbbffb | 3,654,319 |
def generate_interblock_leader():
"""Generates the leader between normal blocks"""
return b'\x55' * 0x2 | 99878b67a31a4169bc73ad9b9b249a981a22177f | 3,654,320 |
import itertools
import warnings
def discover_handlers(entrypoint_group_name="databroker.handlers", skip_failures=True):
"""
Discover handlers via entrypoints.
Parameters
----------
entrypoint_group_name: str
Default is 'databroker.handlers', the "official" databroker entrypoint
f... | d6b4b5c2071833503689abf474d5ebbc928c30c8 | 3,654,321 |
def create_highway_layer(highway_type,
num_layer,
unit_dim,
window_size,
activation,
dropout,
num_gpus,
default_gpu_id,
... | 3bb1aafe9935f81683dfb036c91ec52da808932f | 3,654,322 |
def compute_metrics(y_true, y_predicted, y_prob = None):
"""compute metrics for the prredicted labels against ground truth
@args:
y_true: the ground truth label
y_predicted: the predicted label
y_predicted_prob: probability of the predicted label
@returns:
... | e31264fa05ad02bcc73de0746df12dcccb1889fd | 3,654,323 |
def session_store(decoy: Decoy) -> SessionStore:
"""Get a mock SessionStore interface."""
return decoy.mock(cls=SessionStore) | 92518d32c7195f8fe6a6f3e44640cb2a5accb28b | 3,654,324 |
from typing import Dict
from typing import Any
from typing import List
def extract_values(obj: Dict[str, Any], key: str, val: Any) -> List[Dict[str, Any]]:
"""
Pull all values of specified key from nested JSON.
Args:
obj (dict): Dictionary to be searched
key (str): tuple of key and value.... | 368203a85ded379d6c4042dc90e803611bf810d9 | 3,654,326 |
def createMeshPatches(ax, mesh, rasterized=False, verbose=True):
"""Utility function to create 2d mesh patches within a given ax."""
if not mesh:
pg.error("drawMeshBoundaries(ax, mesh): invalid mesh:", mesh)
return
if mesh.nodeCount() < 2:
pg.error("drawMeshBoundaries(ax, mesh): to ... | 977de081b20e0ab0709887213b53f5318b1ff5f0 | 3,654,327 |
def get_url_name(url_):
"""从url_中获取名字"""
raw_res = url_.split('/', -1)[-1]
raw_res = raw_res.split('.', 1)[0]
res = raw_res[-15:]
return res | a8f3b8dbc4a53e839b3047604e71ffaf36c00767 | 3,654,328 |
def check_uuid_in_db(uuid_to_validate, uuid_type):
"""
A helper function to validate whether a UUID exists within our db.
"""
uuid_in_db = None
if uuid_type.name == "SESSION":
uuid_in_db = Sessions.query.filter_by(session_uuid=uuid_to_validate).first()
elif uuid_type.name == "QUIZ":
... | b151e7b7b393daf9647f308dea6fddd5eec3cb92 | 3,654,329 |
def delete(uuid):
""" Deletes stored entities and time them.
Args:
uuid: A str, unique identifier, a part of the keynames of entities.
Returns:
A tuple of two lists. A list of float times to delete
all entities, and a list of errors. A zero value signifies
a failure.
"""
timings = []
error... | c0f9b42829dd8bd0963ea3a9b904d1aec0c50368 | 3,654,330 |
def remove_prefix(string, prefix):
"""
This function removes the given prefix from a string, if the string does
indeed begin with the prefix; otherwise, it returns the string
unmodified.
"""
if string.startswith(prefix):
return string[len(prefix):]
else:
return string | 73cffca0e9938ea48f3781c7821fcbcf56e0cf25 | 3,654,331 |
import torch
def action_probs_to_action(probs):
""" Takes output of controller and converts to action in format [0,0,0,0] """
forward = probs[:, 0:2]; camera=probs[:, 2:5]; jump=probs[:,5:7];
action = [torch.distributions.Categorical(p).sample().detach().item() for p in [forward,camera,jump]]
action.... | 00395569cd3fb7696bd0aa050f6fbcd6641d3741 | 3,654,332 |
from typing import Tuple
from typing import List
from typing import Set
def search_for_subject(subject: Synset, num_urls: int, subscription_key: str, custom_config: str,
host: str, path: str) -> Tuple[List[Tuple[str, str, str]], str, str]:
"""Perform the search phase for one particular subj... | fde60dc857f5623e8aae9a7a52621d4386034fb5 | 3,654,334 |
def get_kwargs(class_name: str) -> Kwargs:
"""Returns the specific kwargs for each field `class_name`"""
default_kwargs = get_default_kwargs()
class_kwargs = get_setting("COMMON_KWARGS", {})
use_kwargs = class_kwargs.get(class_name, default_kwargs)
return use_kwargs | 8b1ee7448792e2740053edf51528c99f3e2b5698 | 3,654,335 |
def minute_info(x):
"""
separates the minutes from time stamp. Returns minute of time.
"""
n2 = x.minute
return n2/60 | c166bb8f759a5eed1b45b2dd8f228206357deb28 | 3,654,336 |
from bs4 import BeautifulSoup
def remove_html_tags(text):
"""Removes HTML Tags from texts and replaces special spaces with regular spaces"""
text = BeautifulSoup(text, 'html.parser').get_text()
text = text.replace(u'\xa0', ' ')
return text | 7f31a18d81ebc80b202ac697eb7b19fe206aed95 | 3,654,337 |
def patchy(target, source=None):
""" If source is not supplied, auto updates cannot be applied """
if isinstance(target, str):
target = resolve(target)
if isinstance(source, str):
source = resolve(source)
if isinstance(target, ModuleType):
return PatchModule(target, source)
e... | eece41abbc040fd306ae9b2813ae6f3e089cee82 | 3,654,338 |
def _handle_special_addresses(lion):
"""
When there are special address codes/names, ensure that there is a duplicate
row with the special name and code as the primary.
Note: Only for special address type 'P' - addressable place names
"""
special = lion[
(lion['special_address_type'].i... | c8079ef0cba6e96940ed13b74c87a1bd49416376 | 3,654,339 |
def get_local():
"""Construct a local population."""
pop = CosmicPopulation.simple(SIZE, generate=True)
survey = Survey('perfect')
surv_pop = SurveyPopulation(pop, survey)
return surv_pop.frbs.s_peak | 2ab081ffbd79c991c8a3d6ec7097a09407e5fe8a | 3,654,340 |
def calculate_y_pos(x, centre):
"""Calculates the y-coordinate on a parabolic curve, given x."""
centre = 80
y = 1 / centre * (x - centre) ** 2 + sun_radius
return int(y) | e57501c9e83bc26491266c9237f3e3b722ccacef | 3,654,342 |
def extract_flowlines(gdb_path, target_crs, extra_flowline_cols=[]):
"""
Extracts flowlines data from NHDPlusHR data product.
Extract flowlines from NHDPlusHR data product, joins to VAA table,
and filters out coastlines.
Extracts joins between flowlines, and filters out coastlines.
Parameters
... | 8e0f0fec59441a3370b958452a2e4674f1e0ee34 | 3,654,343 |
def split_str_to_list(input_str, split_char=","):
"""Split a string into a list of elements.
Args:
input_str (str): The string to split
split_char (str, optional): The character to split the string by. Defaults
to ",".
Returns:
(list): The string split into a list
"... | 2b13868aed1869310a1398886f6777ddceb6c777 | 3,654,345 |
def generate_password(length):
"""
This will create a random password for the user
Args:
length - the user's preferred length for the password
Return:
It will return a random password of user's preferred length
"""
return Password.generate_pass(length) | 76fd4e06364b4cbfeffb389cb959f5d22f0acc71 | 3,654,346 |
def export_csv(obj, file_name, point_type='evalpts', **kwargs):
""" Exports control points or evaluated points as a CSV file.
:param obj: a curve or a surface object
:type obj: abstract.Curve, abstract.Surface
:param file_name: output file name
:type file_name: str
:param point_type: ``ctrlpts`... | a42f13a5af94344f0ef9c6b9b8aca62067dfd77f | 3,654,347 |
import re
def formatRFC822Headers(headers):
""" Convert the key-value pairs in 'headers' to valid RFC822-style
headers, including adding leading whitespace to elements which
contain newlines in order to preserve continuation-line semantics.
"""
munged = []
linesplit = re.compile(r'[\n... | 4c7dd97c9079daf144acf83241ebe9f025020611 | 3,654,348 |
def first_fixation_duration(trial: Trial, region_number: int) -> RegionMeasure:
"""
The duration of the first fixation in a region during first pass reading
(i.e., before the reader fixates areas beyond the region).
If this region is skipped during first pass, this measure is None.
::
fp_f... | cdb1435f382d277bb3a116e2d268a566b17692a4 | 3,654,349 |
def find_in_path(input_data, path):
"""Finds values at the path in input_data.
:param input_data: dict or list
:param path: the path of the values example: b.*.name
:result: list of found data
"""
result = find(input_data, path.split('.'))
return [value for _, value in result if value] | 6529486013966df264fc3f84a17a8f858a37190c | 3,654,350 |
def post_test_check(duthost, up_bgp_neighbors):
"""Post-checks the status of critical processes and state of BGP sessions.
Args:
duthost: Host DUT.
skip_containers: A list contains the container names which should be skipped.
Return:
This function will return True if all critical p... | 6ce585abbfbdb2b8a1f858ce54f4cd837c84bbda | 3,654,351 |
def fill_with_mode(filename, column):
"""
Fill the missing values(NaN) in a column with the mode of that column
Args:
filename: Name of the CSV file.
column: Name of the column to fill
Returns:
df: Pandas DataFrame object.
(Representing entire data and where 'column' does... | 6b9dc4b0530c21b0a43776b05ce0d8620f75dd30 | 3,654,352 |
def get_model_spec(
model_zoo,
model_def,
model_params,
dataset_fn,
loss,
optimizer,
eval_metrics_fn,
prediction_outputs_processor,
):
"""Get the model spec items in a tuple.
The model spec tuple contains the following items in order:
* The model object instantiated with pa... | 427cf6f2705f32a493fdd8c16cc57d337b528a2f | 3,654,354 |
def clean_meta(unclean_list):
"""
cleans raw_vcf_header_list for downstream processing
:return:
"""
clean_list = []
for i in unclean_list:
if "=<" in i:
i = i.rstrip(">")
i = i.replace("##", "")
ii = i.split("=<", 1)
else:
i = i.rep... | 03dcbcad57b129fd6ff379f3fb3181c91f8f4106 | 3,654,355 |
import itertools
def generate_result_table(models, data_info): # per idx (gene/transcript)
"""
Generate a table containing learned model parameters and statistic tests.
Parameters
----------
models
Learned models for individual genomic positions of a gene.
group_labels
Labels... | 455cbe41c2114e3a81ac186b2adf07753041d753 | 3,654,356 |
def get_href_kind(href, domain):
"""Return kind of href (internal or external)"""
if is_internal_href(href, domain):
kind = 'internal'
else:
kind = 'external'
return kind | e63b3e28d0f6f776338da827f61b0c5709dfe990 | 3,654,357 |
def check_mark(value):
"""Helper method to create an html formatted entry for the flags in tables."""
return format_html('✓') if value == 1 else '' | 07430e1b5be180b01dd8dd045db01ac4ee9ca6ee | 3,654,359 |
def military_to_english_time(time, fmt="{0}:{1:02d}{2}"):
""" assumes 08:33:55 and 22:33:42 type times
will return 8:33am and 10:33pm
(not we floor the minutes)
"""
ret_val = time
try:
h, m = split_time(time)
ampm = "am"
if h >= 12:
ampm = "pm"
... | 880f42354c407a7fae5ba2685b38a10260bc9f58 | 3,654,361 |
def parse_ssh_config(text):
"""
Parse an ssh-config output into a Python dict.
Because Windows doesn't have grep, lol.
"""
try:
lines = text.split('\n')
lists = [l.split(' ') for l in lines]
lists = [filter(None, l) for l in lists]
tuples = [(l[0], ''.join(l[1:]).st... | 7441c39e5ca9127871316d98a6fe195ed1da6522 | 3,654,362 |
import re
def snake_case(string: str) -> str:
"""Convert upper camelcase to snake case."""
return re.sub(r"(?<!^)(?=[A-Z])", "_", string).lower() | fe8592bcfa1f2233a07308741de5f912fd7055b3 | 3,654,363 |
import tempfile
import atexit
def create_tempdir(suffix='', prefix='tmp', directory=None, delete=True):
"""Create a tempdir and return the path.
This function registers the new temporary directory
for deletion with the atexit module.
"""
tempd = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=... | f0c9b6b3a9198d1e552e5fce838113239021a4fd | 3,654,365 |
import binascii
async def get_transactor_key(request):
"""Get transactor key out of request."""
id_dict = deserialize_api_key(
request.app.config.SECRET_KEY, extract_request_token(request)
)
next_id = id_dict.get("id")
auth_data = await get_auth_by_next_id(next_id)
encrypted_private_k... | a1766e70ad076eaeb7d19509aeffbb729869df51 | 3,654,366 |
def _get_plot_aeff_exact_to_ground_energy(parsed_ncsd_out_files):
"""Returns a list of plots in the form
(xdata, ydata, const_list, const_dict),
where A=Aeff is xdata, and ground energy is ydata
"""
a_aeff_to_ground_state_energy = get_a_aeff_to_ground_state_energy_map(
parsed_ncsd_ou... | e4224d43808e9ef0f43bc32041ef567138853bdb | 3,654,367 |
def get_twitter_auth():
"""Setup Twitter connection
return: API object"""
parameters = set_parameters.take_auth_data()
twitter_access_token = parameters['twitter_access_token']
twitter_secret_token = parameters['twitter_secret_token']
twitter_api_key = parameters['twitter_api_key']
twitter... | 1bb6ef2660adf25935f844c29e7e1dae3e674937 | 3,654,368 |
import re
import logging
def pre_process_string_data(item: dict):
"""
remove extra whitespaces, linebreaks, quotes from strings
:param item: dictionary with data for analysis
:return: cleaned item
"""
try:
result_item = {key: item[key] for key in KEYS + ['_id']}
for prop in res... | 32c4218c0e02580ea90a75f117d8b822239ee6d1 | 3,654,369 |
def remove_cmds_from_title(title):
"""
Função que remove os comandos colocados nos títulos
apenas por uma questão de objetividade no título
"""
arr = title.split()
output = " ".join(list(filter(lambda x: x[0] != "!", arr)))
return output | bfaa96aa578455f977549b737a8492afa80e1e7c | 3,654,370 |
def load_config(file_path):
"""Loads the config file into a config-namedtuple
Parameters:
input (pathlib.Path):
takes a Path object for the config file. It does not correct any
relative path issues.
Returns:
(namedtuple -- config):
Contains t... | 82664fa4e27fd60ae56c435b3deb45cb7535bc17 | 3,654,371 |
def parse_version_number(raw_version_number):
# type: (str) -> Tuple[int, int, int]
"""
Parse a valid "INT.INT.INT" string, or raise an
Exception. Exceptions are handled by caller and
mean invalid version number.
"""
converted_version_number = [int(part) for part in raw_version_number.split(... | a899d29790ce03d28e7acb11c87f38890501d462 | 3,654,372 |
def get_error_directory_does_not_exists(dir_kind):
"""dir kind = [dir, file ,url]"""
return f"Error: Directory with {dir_kind} does not exist:" | 171fb09ab341daf2810612f2cc7c077b5326f347 | 3,654,373 |
def var_text(vname, iotype, variable):
"""
Extract info from variable for vname of iotype
and return info as HTML string.
"""
if iotype == 'read':
txt = '<p><i>Input Variable Name:</i> <b>{}</b>'.format(vname)
if 'required' in variable:
txt += '<br><b><i>Required Input Va... | 04fdb1727c8eb783f7fb2c0324852e80673e8b77 | 3,654,374 |
def line_search_reset(binary_img, left_lane, right_line):
"""
#---------------------
# After applying calibration, thresholding, and a perspective transform to a road image,
# I have a binary image where the lane lines stand out clearly.
# However, I still need to decide explicitly which pixels ar... | d810c111bcf5731f7c4486c77863c3505d8400a8 | 3,654,375 |
def get_primary_language(current_site=None):
"""Fetch the first language of the current site settings."""
current_site = current_site or Site.objects.get_current()
return get_languages()[current_site.id][0]['code'] | c4d71c30424bb753de353e325a012efb9265a01b | 3,654,376 |
def get_Theta_ref_cnd_H(Theta_sur_f_hex_H):
"""(23)
Args:
Theta_sur_f_hex_H: 暖房時の室内機熱交換器の表面温度(℃)
Returns:
暖房時の冷媒の凝縮温度(℃)
"""
Theta_ref_cnd_H = Theta_sur_f_hex_H
if Theta_ref_cnd_H > 65:
Theta_ref_cnd_H = 65
return Theta_ref_cnd_H | deccaa524aebda2a7457da53b44c517287a190a4 | 3,654,377 |
def hpat_pandas_series_shape(self):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.shape
Examples
--------
.. literalinclude:: ../../../examples/series/series_shape.py
:language: python
:lines: 27-
... | 6c27e6276caecaea18650398678d04623ddcc653 | 3,654,379 |
async def port_utilization_range(
port_id: str, direction: str, limit: int, start: str, granularity: int, end=None,
):
"""Get port utilization by date range."""
async with Influx("telegraf", granularity=granularity) as db:
q = (
db.SELECT(f"derivative(max(bytes{direction.title()}), 1s) *... | 2d2ac7ad32ee279f88d662bd8f099ccee0407b66 | 3,654,380 |
def composer_includes(context):
"""
Include the composer JS and CSS files in a page if the user has permission.
"""
if context.get('can_compose_permission', False):
url = settings.STATIC_URL
url += '' if url[-1] == '/' else '/'
js = '<script type="text/javascript" src="%sjs/compo... | 7c0a89a5ce1e1fe5838e8022fe568347420ffb0f | 3,654,381 |
def craft(crafter, recipe_name, *inputs, raise_exception=False, **kwargs):
"""
Access function. Craft a given recipe from a source recipe module. A
recipe module is a Python module containing recipe classes. Note that this
requires `settings.CRAFT_RECIPE_MODULES` to be added to a list of one or
more... | 860b839123394f2ba210b4cfdcb40a57595701a3 | 3,654,382 |
from typing import Iterable
from typing import Union
from typing import List
from typing import Any
from typing import Dict
import collections
def load_data(
data,
*,
keys: Iterable[Union[str, int]] = (0,),
unique_keys: bool = False,
multiple_values: bool = False,
unique_values: bool = False,
... | ad3a5f74a0bbbfbf3de62f691be5b27b63fa9949 | 3,654,383 |
def get_avg_wind_speed(data):
"""this function gets the average wind speeds for each point in the fetched data"""
wind_speed_history = []
for point in data:
this_point_wind_speed = []
for year_reading in point:
hourly = []
for hour in year_reading['weather'][0]['hourl... | fdeeb64f495343893ffc98997de2bad5748591c2 | 3,654,384 |
from typing import List
def get_uris_of_class(repository: str, endpoint: str, sparql_file: str, class_name: str, endpoint_type: str,
limit: int = 1000) -> List[URIRef]:
"""
Returns the list of uris of type class_name
:param repository: The repository containing the RDF data
:para... | 7b5cf86d286afd00d40e202e98661be3668364c3 | 3,654,385 |
def nspath_eval(xpath: str) -> str:
"""
Return an etree friendly xpath based expanding namespace
into namespace URIs
:param xpath: xpath string with namespace prefixes
:returns: etree friendly xpath
"""
out = []
for chunks in xpath.split('/'):
namespace, element = chunks.split... | 6e5e558da8d00d57ee1857bce2b8c99d05386c73 | 3,654,386 |
def basic_streamalert_config():
"""Generate basic StreamAlert configuration dictionary."""
return {
'global': {
'account': {
'aws_account_id': '123456789123',
'kms_key_alias': 'stream_alert_secrets',
'prefix': 'unit-testing',
'r... | 8e766fa73c9043888c6531659bccc57fcb1a88ea | 3,654,387 |
def _read_elastic_moduli(outfilename):
"""
Read elastic modulus matrix from a completed GULP job
:param outfilename: Path of the stdout from the GULP job
:type outfilename: str
:returns: 6x6 Elastic modulus matrix in GPa
"""
outfile = open(outfilename,'r')
moduli_array = []
while Tr... | d09672135bed16aa651bbe5befe526e21763fc1b | 3,654,388 |
def predict_koopman(lam, w, v, x0, ncp, g, h, u=None):
"""Predict the future dynamics of the system given an initial value `x0`. Result is returned
as a matrix where rows correspond to states and columns to time.
Args:
lam (tf.Tensor): Koopman eigenvalues.
w (tf.Tensor): Left eigenvectors.
... | 8509a96a5566f69ac238827538591ff9fcf34269 | 3,654,389 |
def handle_registration():
""" Show the registration form or handles the registration
of a user, if the email or username is taken, take them back to the
registration form
- Upon successful login, take to the homepage
"""
form = RegisterForm()
email = form.email.data
userna... | 27ce2a38202ea5873c53bc53fd5d2843515177cf | 3,654,390 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.