content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
def get_type_specs_from_feature_specs(
feature_specs: Dict[str, common_types.FeatureSpecType]
) -> Dict[str, tf.TypeSpec]:
"""Returns `tf.TensorSpec`/`tf.SparseTensorSpec`s for the given feature spec.
Returns a dictionary of type_spec with the same type and shape as defined by
`feat... | 7ea1f204365380ffa48b98c5e5e7d31875a211c0 | 28,300 |
def read_fortran_namelist(fileobj):
"""Takes a fortran-namelist formatted file and returns appropriate
dictionaries, followed by lines of text that do not fit this
pattern.
"""
data = {}
extralines = []
indict = False
fileobj.seek(0)
for line in fileobj.readlines():
if indic... | 3c3b96ca707c7f0492c2913c6b9496cb57fc969b | 28,301 |
from typing import Tuple
import re
def check_token(surface: str) -> Tuple[str, str]:
"""Adopted and modified from coltekin/childes-tr/misc/parse-chat.py
For a given surface form of the token, return (surface, clean), where
clean is the token form without CHAT codes.
"""
if surface is None:
return None, None
... | c737c8acdce04597506e399a7d2fe0252634edc1 | 28,302 |
def remove_media_url(media_path):
"""
Strip leading MEDIA_URL from a media file url.
:param media_path:
:return:
"""
if media_path.startswith(MEDIA_URL):
return media_path[len(MEDIA_URL):]
else:
return media_path | 084773d30cc9c534a9347712058c581797a2b05b | 28,303 |
def _map_route_on_graph(ordered_cluster: sp.Cluster, graph: sp.Graph) -> list[sp.Segment]:
"""Построить маршрут в графе
Args:
ordered_cluster: Кластер с заданным порядком обхода точек
graph: Граф для прокладывания маршрута
Returns:
Построенный маршрут
"""
route = [] # Пут... | 1ca10abc6f9d88c08dbbbd63b48e62f7077c8a39 | 28,304 |
from typing import Tuple
from typing import Dict
def list_violation_data(client: Client, args) -> Tuple[str, Dict, Dict]:
"""List violation data.
Args:
client: Client object with request.
args: Usually demisto.args()
Returns:
Outputs.
"""
from_ = args.get('from')
to_ ... | c7548b7a86bb63855ee5c9fc7ec602ffa39a608b | 28,305 |
def train_add_test(func=lambda a, b: a+b, results_dir=None, reg_weight=5e-2, learning_rate=1e-2, n_epochs=10001):
"""Addition of two MNIST digits with a symbolic regression network.
Withold sums > 15 for test data"""
tf.reset_default_graph()
# Symbolic regression network to combine the conv net outputs... | 9705cfb8cc8a321c16eb6f93dda1878e73e9328f | 28,306 |
def walk_graph(csr_matrix, labels, walk_length=40, num_walks=1, n_jobs=1):
"""Perform random walks on adjacency matrix.
Args:
csr_matrix: adjacency matrix.
labels: list of node labels where index align with CSR matrix
walk_length: maximum length of random walk (default=40)
num_w... | 4a317aecbc88998469420575346c38da30f8bc90 | 28,307 |
def mutate_split(population, config):
"""
Splitting a non-zero dose (> 0.25Gy) into 2 doses.
population - next population, array [population_size, element_size].
"""
interval_in_indices = int(2 * config['time_interval_hours'])
mutation_config = config['mutations']['mutate_split']
min_dose =... | db737191d5f7c1852410d6f1ad779e8ca58c658a | 28,308 |
def _copy_df(df):
""" Copy a DataFrame """
return df.copy() if df is not None else None | 263bf1cf9cbdae371ea3e4685b4638e8a5714d7f | 28,309 |
def findPossi(bo):
""" Find all possibilities for all fields and add them to a list."""
possis = []
for row,rowVal in enumerate(bo):
for col,colVal in enumerate(rowVal):
localpossi=newPossiFinder(bo, col, row)
if bo[row][col]==0:
# Here ujson.loads(ujson.dump... | c504ca243f631af135ae64f97b9f46b2cdb7d789 | 28,310 |
def modernforms_exception_handler(func):
"""Decorate Modern Forms calls to handle Modern Forms exceptions.
A decorator that wraps the passed in function, catches Modern Forms errors,
and handles the availability of the device in the data coordinator.
"""
async def handler(self, *args, **kwargs):
... | c486173ef34f4c89fb3138cad989472f01d7bb7c | 28,311 |
def reads_per_insertion(tnpergene_list,readpergene_list,lines):
"""It computes the reads per insertion following the formula:
reads/(insertions-1) if the number of insertions is higher than 5,
if not then the reads per insertion will be 0.
Parameters
----------
tnpergene_list : list
A... | c5a3f06298d2e782d60b20d561d9d5f65a369dcd | 28,312 |
def getCurrDegreeSize(currDegree, spatialDim):
"""
Computes the number of polynomials of the current spatial dimension
"""
return np.math.factorial(currDegree + spatialDim - 1) / (
np.math.factorial(currDegree) * np.math.factorial(spatialDim - 1)) | 754440fde04f7fe30e336cf4d7c5efb75dd1aaac | 28,313 |
def split_last_dimension(x, n):
"""Reshape x so that the last dimension becomes two dimensions.
The first of these two dimensions is n.
Args:
x: a Tensor with shape [..., m]
n: an integer.
Returns:
a Tensor with shape [..., n, m/n]
"""
x_shape = shape_list(x)
m = x_... | c1f26106e0d11a5722191a52c86f90b9559d32dc | 28,314 |
import os
def get_base_dir_for_individual_image(dataset,
show_both_knees_in_each_image,
downsample_factor_on_reload,
normalization_method,
seed_to_further_shuffle_train_test_val_sets,
crop_to_just_the_knee):
"""
Get the path for an image.
"""
assert seed_to_further_shuffle_tr... | 568dd1ab16dc10e2fc2fa8fb083dad96793517ce | 28,315 |
def get_column_dtype(column, pd_or_sqla, index=False):
"""
Take a column (sqlalchemy table.Column or df.Series), return its dtype in Pandas or SQLA
If it doesn't match anything else, return String
Args:
column: pd.Series or SQLA.table.column
pd_or_sqla: either 'pd' or 'sqla': which kin... | c466405c66b24d48cc37920df2876e876d1d6885 | 28,316 |
def _stdlibs(tut):
"""Given a target, return the list of its standard rust libraries."""
libs = [
lib.static_library
for li in tut[CcInfo].linking_context.linker_inputs.to_list()
for lib in li.libraries
]
stdlibs = [lib for lib in libs if (tut.label.name not in lib.basename)]
... | 8098406876684911df5c52413780305bea2d12a7 | 28,317 |
def _chebyshev(wcs_dict):
"""Returns a chebyshev model of the wavelength solution.
Constructs a Chebyshev1D mathematical model
Parameters
----------
wcs_dict : dict
Dictionary containing all the wcs information decoded from the header and
necessary for constructing the Chebyshev1D... | 3d30fde977351a4e43a0940696c8fc988400ccda | 28,318 |
def autosolve(equation):
"""
Automatically solve an easy maths problem.
:type equation: string
:param equation: The equation to calculate.
>>> autosolve("300 + 600")
900
"""
try:
# Try to set a variable to an integer
num1 = int(equation.split(" ")[0])
except Value... | a4db1dedffdccc44d7747c4743f4f2eaf8dbd81a | 28,319 |
from bs4 import BeautifulSoup
import http
def request_champion(champion_name: str) -> BeautifulSoup:
"""
Get http request to website with all statistics about a
champion with html format.
"""
request = http.request(
'GET',
f'https://www.leaguespy.gg/league-of-legends/champion/{cham... | f0b5a0b1eb6cceec6c7e1c8c8cd1078a5f2505c3 | 28,320 |
def _act_drop(grid_world, agent, env_obj, drop_loc):
""" Private MATRX method.
Drops the carried object.
Parameters
----------
grid_world : GridWorld
The :class:`matrx.grid_world.GridWorld` instance in which the
object is dropped.
agent : AgentBody
... | 93511395fda0060d479284a4b97ccd181346292f | 28,321 |
def get_emoticon_radar_chart(scores_list, colors, names):
""" AAA
"""
data_radars = []
emotions = ['anger', 'anticipation', 'disgust', 'fear', 'joy', 'sadness', 'surprise', 'trust']
for score, color, name in zip(scores_list, colors, names):
data = go.Scatterpolar(r=score, theta=emotions, fil... | 9f147a9bdd5713a915b96a309bcd1086c9e17ba6 | 28,322 |
def get_polling_method(meth_name=None):
""" Grab a polling-method by string-key
Eventually these could be auto-registered somehow;
for now we just keep a look-up dict of them. """
methods = dict(
poll_game_unknowns=poll_game_unknowns,
poll_dan=poll_dan,
)
default_method = poll_... | 2faf19b3b6cf6decd230c5678591478eaf7839d6 | 28,323 |
def get_contour_list(image, preprocessed, MIN_FILTER=3000):
""" Given an image and its preprocessed version, returns the cropped image and its contours.
The return value is in the format: [(CroppedImage, Contour)]
Parameters
----------
image : opencv image
The original unprocessed image
... | 0970c2e1549ff5a50b9f04c1139ab9983e7ee8c3 | 28,324 |
import inspect
import re
def doc_signature(f):
"""Attempt to parse the signature of a function at the beginning of
its documentation. Useful for many numpy functions.
"""
doc = inspect.getdoc(f)
if not doc:
# print(f"DD doc_signature: no doc for {qualname(f)}")
return None
m =... | 5617cd674a57dd75d236e4eadb316e81640dd756 | 28,325 |
import pkg_resources
import scipy
def generate_wav(pattern, tempo=120, loops=1, saveName='audiofile.wav', fs=44100,
dynamics=False, customSound=None):
"""
Generate a .wav file from a pattern.
Specify a tempo (in BPM), loops, name of the file, sampling rate,
and decide if you want "dynamics". Dynamics adds o... | aa11722a40aca967d168f38ea1ae239eccfa3361 | 28,326 |
def svn_fs_upgrade(*args):
"""svn_fs_upgrade(char path, apr_pool_t pool) -> svn_error_t"""
return _fs.svn_fs_upgrade(*args) | 4f466df2d6f41cbe277370e3ec158e7737d271f0 | 28,327 |
def api_url(service: str = "IPublishedFileService",
function: str = "QueryFiles",
version: str = "v1") -> str:
"""
Builds a steam web API url.
:param service: The steam service to attach to.
:param function: The function to call.
:param version: The API version.
:return: ... | 2538ab8c8035c491611585089ddd3a1625e423cc | 28,328 |
import re
def reg_all_keywords(data):
"""
从meta file中提取所有关键词,格式为:
***[:###]***
提取出###
:param data:
:return:
"""
patt = re.compile(r"\[:([^\[\]]+)\]")
ret = patt.findall(data)
return ret if ret else None | d81f8dd5f04d9e65f61247a8c9857969cf7e514d | 28,329 |
def new_figure_manager(num, *args, **kwargs):
"""
Create a new figure manager instance
"""
_focus = windowing.FocusManager()
FigureClass = kwargs.pop('FigureClass', Figure)
figure = FigureClass(*args, **kwargs)
window = Tk.Tk()
canvas = FigureCanvasTkAgg(figure, master=window)
figMan... | c5c589c214a70f07ace913b5b8fb13cd52c30240 | 28,330 |
def get_platform():
"""Gets the platform (example: azure)."""
return get_config_value("platform") | 693540442f23b21b9d983c9e7728d5397415544b | 28,331 |
import sys
import difflib
def transform_command(src, show_diff=True):
"""Returns the results of firing the precommand handles."""
i = 0
limit = sys.getrecursionlimit()
lst = ""
raw = src
while src != lst:
lst = src
srcs = events.on_transform_command.fire(cmd=src)
for s ... | fa51d455b9b7d724e8648e8f33a770ad6fb583b4 | 28,332 |
def ascii_from_object(space, w_obj):
"""Implements builtins.ascii()"""
# repr is guaranteed to be unicode
w_repr = space.repr(w_obj)
w_encoded = encode_object(space, w_repr, 'ascii', 'backslashreplace')
return decode_object(space, w_encoded, 'ascii', 'strict') | 14ff3217b42743c5e202db107914e5ee0df4a10d | 28,333 |
import os
def project_dir(project_name=None):
"""
获取当前项目根路径
:param project_name:
:return: 根路径
"""
PROJECT_NAME = 'stock-technical-analysis' if project_name is None else project_name
project_path = os.path.abspath(os.path.dirname(__file__))
root_path = project_path[:proj... | 16a304e6c6fa068380e8908569b1f03f2ab3fb68 | 28,334 |
def capture(p):
"""Return a peg that acts like p, except it adds to the values
tuple the text that p matched."""
return _Peg(('capture(%r)', p),
lambda s, far, (i, vals):
[(i2, vals2 + (s[i:i2],))
for i2, vals2 in p.run(s, far, (i, vals))]) | 710e1cf4015b057e6898affa70ef380be0648ea3 | 28,335 |
def html_chart(df, height=1200):
"""
make interactive chart.
param df: inpute dataframe
param height: optional plot height
returns: plotly chart
"""
fig = make_subplots(rows=(len(df.columns)),
cols=1,
subplot_titles=df.columns,
... | 821f6ae8c10a80c32a932cd77beb2b0a3969d0af | 28,336 |
def build_0565_color_lookup():
"""Build the lookup table for the ARGB_0565 color format"""
bdG = 6
bdB = 5
redColorOffset = bdG + bdB
greenColorOffset = bdB
val_lookup_5 = BITDEPTH_VALUE_LOOKUPS[5]
val_lookup_6 = BITDEPTH_VALUE_LOOKUPS[6]
conversion_table = [None] * 65536
for r_sho... | c3a33e0355fb795e93ee722012faab6b83195bb4 | 28,337 |
def build_que_input_from_segments(context, answer, question, tokenizer,
max_input_length=1000, with_eos=True,
with_labels=True):
""" Build a sequence of input from 3 segments:
context, answer, question """
bos, eos, ctx, ans, que, pad, ... | 400abaac1744bab2f665c8ffad50ba2b7030569b | 28,338 |
import logging
import sys
def default_logging_config(logger):
"""Set up the default handler and formatter on the given logger."""
default_handler = logging.StreamHandler(stream=sys.stdout)
default_handler.formatter = ColorFormatter()
logger.handlers = [default_handler]
logger.propagate = True
... | 2be70b389af4d38ecab594a74da37dd6b8b4d39d | 28,339 |
import traceback
def verify_preload(upload_id, language=None):
"""
Continue the verification process by counting the number of geounits
in the uploaded file and compare it to the number of geounits in the
basest geolevel. After this step completes, the copy_to_characteristics
method is called.
... | bd1f43e8bff3c64badc6076fb879ee6c48193fd2 | 28,340 |
def transition(field, source='*', target=None, conditions=[], custom={}):
"""
Method decorator for mark allowed transitions
Set target to None if current state needs to be validated and
has not changed after the function call
"""
def inner_transition(func):
fsm_meta = getattr(func, '_d... | cf4066c8a21c89a793e526cf4a4171ac17cf7c42 | 28,341 |
def get_inspexp_frames(slice, inspexp_data, images_path):
"""
Loads inspiration and expiration frames for the specified cine-MRI slice
Parameters
----------
slice: CineMRISlice
A cine-MRI slice for which to extract inspiration and expiration frames
inspexp_data : dict
A dictionary... | d0dda284af281ebca08ee494a1e5fdc8f97789e4 | 28,342 |
def cleaned_reviews_dataframe(reviews_df):
"""
Remove newline "\n" from titles and descriptions,
as well as the "Unnamed: 0" column generated when
loading DataFrame from CSV. This is the only cleaning
required prior to NLP preprocessing.
INPUT: Pandas DataFrame with 'title' and 'desc' colum... | 8f805f556667f5d734d4d272a2194784d37ce99c | 28,343 |
def not_list(l):
"""Return the element wise negation of a list of booleans"""
assert all([isinstance(it, bool) for it in l])
return [not it for it in l] | 6d30f5dd587cdc69dc3db94abae92a7a8a7c610d | 28,344 |
def first_order_forward(n, zero = True):
"""
"""
m1 = -np.eye(n) + np.eye(n, k = 1)
return np.vstack([np.ones(n), m1]) | d79149614e15c8cce9f13a402f6321b43498862b | 28,345 |
def boil(config, recipe_config):
""" Boil wort. """
up = config['unit_parser']
if 'Hops' in recipe_config:
hops = recipe_config['Hops']
for hop in hops:
if 'addition type' in hop and hop['addition type'] == 'fwh':
if 'mass' in hop and 'name' in hop and 'type' in... | 035de7c388e2c82962987c63c13679e6bd16222f | 28,346 |
def _ecdf(
data=None,
p=None,
x_axis_label=None,
y_axis_label="ECDF",
title=None,
plot_height=300,
plot_width=450,
staircase=False,
complementary=False,
x_axis_type="linear",
y_axis_type="linear",
**kwargs,
):
"""
Create a plot of an ECDF.
Parameters
----... | e3ae7e76eaa285506692ef48031cdb309fa732f1 | 28,347 |
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
def _get_cipher(key: bytes) -> Cipher:
"""获取 DES3 Cipher 对象"""
algorithm = algorithms.TripleDES(key)
cipher = Cipher(algorithm, modes.CBC(key[:8]), backend=default_backend... | 13c046884ccd51ff19ed9eb80a1747f6888863a0 | 28,348 |
def get_real_dist2rim(x_dist, radius_cut, radius_sphere):
"""
Get the real distance to rim
:param x_dist:
:param radius_cut:
:param radius_sphere:
:return:
"""
x_transf = x_dist * ((radius_sphere) - np.sqrt((radius_sphere) ** 2 - (radius_cut) ** 2)) / radius_cut
return x_transf | 89f1a6ef3e020636537a8f229e082f7765410129 | 28,349 |
import os
import codecs
import json
import traceback
def read_json(filename):
"""
JSONファイル読み込む
"""
try:
basedir = os.path.dirname(os.path.abspath(__file__))
indir = os.path.join(basedir, "data")
readfilename = os.path.join(indir, filename)
with codecs.open(readfilename... | 471f4a56abbae11eef262e6676294b5ec50c9198 | 28,350 |
def get_workers_stats(worker_class=None):
"""Get the RQ workers stats.
Args:
worker_class (type): RQ Worker class
Returns:
list: List of worker stats as a dict {name, queues, state}
Raises:
redis.exceptions.RedisError: On Redis connection errors
"""
worker_class = worker_... | 33e86511051b15de07eceaa1ab0d8d609eecbafc | 28,351 |
def _get_trafo(cmatrix: cairo.Matrix) -> qc3const.TrafoType:
"""Converts cairo matrix to trafo list
:param cmatrix: (cairo.Matrix) cairo transformation matrix
:return: (qc3const.TrafoType) transformation matrix
"""
return [i for i in cmatrix] | ea9c3c3b8466a7025fce5f48ceb02baa5ae9d319 | 28,352 |
import bokeh
from bokeh.plotting import output_file, ColumnDataSource, show, figure
from bokeh.models import HoverTool, CategoricalColorMapper, LinearColorMapper, Legend, LegendItem, ColorBar
from bokeh.palettes import Category20
def mousover_plot(datadict, attr_x, attr_y, attr_color=None, attr_size=None, save_file=N... | 0cee54239d13e7c3ebd36972e7c0f259ff7de69a | 28,353 |
import numpy
def globalInequalityChanges(Y, fieldNames, outFile, permutations=9999):
"""Global inequality change test
This function tests whether global inequality has significantly changed
for the Theil statistic over the period t to t+k. For more information on
this function see [Rey_Sastre2010] (... | 6a9d0579c52083419d5f4cbedbe4b568d6b7e0a0 | 28,354 |
import re
def generate_gisaid_fasta_df(fname, rtype="nuc", ambiguous_tol=0.01, len_tol=0.9):
"""
Generate pandas dataframe for sequences downloaded from GISAID
"""
fdat_df = []
standardise_gene_name = {"PB2":1, "PB1":2, "PA":3, "HA":4, "NP":5, "NA":6, "MP":7, "NS":8}
subtype_to_influenza_gene... | bf7c09f1f2cfa935d93bbe46c25d55539f2c8bf8 | 28,355 |
def radial_trajectory(base_resolution,
views=1,
phases=None,
ordering='linear',
angle_range='full',
tiny_number=7,
readout_os=2.0):
"""Calculate a radial trajectory.
This function sup... | 3554fc0b833be552af31153c80c07863ab8f683d | 28,356 |
def highlight_threshold(image, img_data, threshold, color=(255, 0, 0)):
"""
Given an array of values for an image, highlights pixels whose value is greater than the given threshold.
:param image: The image to highlight
:param img_data: The values to use
:param threshold: The threshold above which pi... | bc4b0c9f44f7d45b947c9913f6b6f43b73ea542b | 28,357 |
import numpy
def error_norm(q_numerical, q_exact, dx, p=2):
"""
Compute the discrete error in q in the p norm
Parameters
----------
q_numerical : numpy vector
The numerical solution, an array size (N,) or (N,1)
q_exact : numpy vector
The exact solution, whose size matches q_nu... | e4d33583ee2c5308a2eda9755c44961acba2603d | 28,358 |
def _validate_voter(request, end_field):
"""Returns: voter, election, denied_reason, denied_detail (all optional)."""
# TODO: Deprecate use of token here; can auto-generate log-in tokens instead.
token = request.GET.get("token")
election = get_current_election()
voter = None
if not election:
... | c05170a6899a32b9f359b1ae9a2a61f077753d1b | 28,359 |
def flip(xyz_img):
"""
Take an xyz_img and flip its world from LPS / RAS to
RAS / LPS.
>>> data = np.random.standard_normal((30,40,50,5))
>>> metadata = {'name':'John Doe'}
>>> lps_im = XYZImage(data, np.diag([3,4,5,1]), 'ijkt', metadata)
>>> lps_im.xyz_transform
XYZTransform(
fu... | e3f345c8c61043e8a46e8c9b603ed5de93125d63 | 28,360 |
def pivoting_remove(z, rule):
"""Choose which active constraint will be replaced
"""
if rule is None:
k = np.argmin(z)
elif rule.lower() == 'bland':
k = np.min(np.nonzero(z < 0)[0])
else:
raise('Undefined pivoting rule')
return k | 54186ddc15db3abca6853b928c6d51f145cbe248 | 28,361 |
import tqdm
def train_network(model, optimizer, train_loader, lss_fc) -> None:
"""Train Network for one Epoch."""
train_losses = []
for batch in tqdm(train_loader, total=len(train_loader)):
optimizer.zero_grad()
input_tensor, original = batch
input_tensor = input_tensor.to('cuda')... | 1b90706348ceefe7840b16d29bfb0cc37229ec46 | 28,362 |
def get_class(cls):
"""Return TestModuleVisitor report from a class instance."""
ast = get_ast(cls.__module__)
nv = TestmoduleVisitor()
nv.visit(ast)
return nv._classes[cls.__name__] | 4d3bb56f9582edb1576db67a3094f6b3efa3e106 | 28,363 |
def show_system_timezone(
enode,
_shell='vtysh',
_shell_args={
'matches': None,
'newline': True,
'timeout': None,
'connection': None
}
):
"""
Display system timezone information
This function runs the following vtysh command:
::
# show system ti... | 67f08762a31c54fdaeb7c93c48c8c5d97ecf2f3e | 28,364 |
import numpy
def summarize_list(values):
"""
Takes a list of integers such as [1,2,3,4,6,7,8] and summarises it as a string "1-4,6-8"
:param values:
:return: string
"""
sorted_values = numpy.array(sorted(values))
summaries = [
(f'{chunk[0]}-{chunk[-1]}' if len(chunk) > 1 els... | ea6e3501fb3340e0a78a71096129df5b3400fac9 | 28,365 |
import torch
def enforce_size(img, depth, instances, new_w, new_h):
""" Ensures that the image is the given size without distorting aspect ratio. """
with torch.no_grad():
_, h, w = img.size()
if h == new_h and w == new_w:
return img, depth, instances
# Resize the... | 5252b9c62af4ce909fb85856a78b7e4a697aaf74 | 28,366 |
import stat
def update_V_softmax(V,B,T,O,R,gamma,eps=None,PBVI_temps=None,
max_iter=100,verbose=False,n_samps=100,seed=False):
"""
inputs:
V (list):
V[0]: n_B x n_S array of alpha-vector values for each belief
V[1]: n_B array, denoting which action generate... | 62910d068a59902d6a9f5f0c2b873cad551f9c17 | 28,367 |
def scaled_location_plot(yname, yopt, scaled_res):
"""
Plot the scaled location, given the dependant values and scaled residuals.
:param str yname: Name of the Y axis
:param ndarray yopt: Estimated values
:param ndarray scaled_res: Scaled residuals
:returns: the handles for the ... | 24e126f3bb60e5f46713d3a0c7da383684081afd | 28,368 |
def importNoiseTerms(filename):
""" Imports noise data from an FWH file; the returned data is a list of length
nProbes filled with (nTime,3) arrays """
f = open(filename,'r')
deltaT = []
while True:
line = f.readline(); # read line by line
if line == '': # check for ... | b2066f37f7a030d1e330f9bcc0b13b7527caa1e1 | 28,369 |
def line_edit_style_factory(txt_color='white', tgt_layer_color='white',
bg_color='#232323'):
"""Generates a string of a qss style sheet for a line edit. Colors can be
supplied as strings of color name or hex value. If a color arg receives
a tuple we assume it is either an rgb or ... | 10670afc32ec1c19d09dd72fc0e23bb1583ba3af | 28,370 |
import struct
import random
def create_key(key_len):
""" Generates key using random device if present
- key_len -- length of key
"""
try:
#generates truly random numbers
frand = open("/dev/random", "r")
data = frand.read(key_len/2)
frand.close()
return data.e... | 84a9952a896855f04ddf6fedf8a81c1be6bdaa08 | 28,371 |
import os
import logging
def connectToPostgres():
"""
If rulemonitor database does not exist yet:
$ initdb /home/rulemonitor/postgres/data
$ pg_ctl -D /home/rulemonitor/postgres/data -l /home/rulemonitor/postgres/log
$ createdb rulemonitor
"""
pghost = os.getenv("POSTGRES_HO... | c8103d0c2ebff0e85532976b84539e4b04ca65f9 | 28,372 |
import re
def ipv6_from_string(string: str) -> netaddr.IPSet:
"""
Takes a string and extracts all valid IPv6 Addresses as a SET of Strings
Uses the validate_ip helper function to achieve.
"""
ipv6_regex = re.compile(
'(?<![a-zA-Z\d\.])((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-... | 2aa529b8561498384dea2ae6c18f44164710848a | 28,373 |
from typing import Tuple
from typing import List
def get_feature_location(
feature_text: str) -> Tuple[int, int, str, List, bool, bool]:
"""
Args:
feature_text: endswith '\n'
For example:
' CDS complement(join(<360626..360849,360919..360948,
... | 665649a7ea7c618a8830b0bf11c5d26a6e6d21fd | 28,374 |
import stat
import os
def isdir(path):
"""Like os.path.isdir, but raises an exception on error."""
return bool(stat.S_ISDIR(os.stat(path).st_mode)) | e68179caf5da3453f29ff8796702f494879dcca9 | 28,375 |
import json
import logging
def _update_port_rate_limits_v1(port_name, broadcast_limit=None, broadcast_units=None,
multicast_limit=None, multicast_units=None, unknown_unicast_limit=None,
unknown_unicast_units=None, **kwargs):
"""
Perform GET and P... | 28f21634af949b2e023db64ac6a4b850e2bf96cc | 28,376 |
def random_geom_sum(pmf, p, low_mem=False):
"""Calculates the distribution of Z = X_1 + X_2 + ... + X_N.
Parameters
----------
pmf : array
Probability distribution of X such that pmf[x] = Pr(X = x).
p : float
Probability such that N ~ geom(p), i.e. Pr(N = n) = p(1-p)^{n-1}.
low_... | 3b7f75a248975dd78e3cf986bff02a6160c1a026 | 28,377 |
def noto_tools(default=""):
"""Local path to nototools git repo. If this is called, we require config
to be set up."""
result = _values.get("noto_tools", default)
if result:
return result
raise Exception(_ERR_MSG) | 42738c374bcd6d89baf4eabbe7c0f0a75fb1fd1d | 28,378 |
def fdc_windtur_west(timestamp, sonicU, sonicV, sonicW, heading,
rateX, rateY, rateZ, accX, accY, accZ, lat):
"""
Description:
Calculates the L1 windspeed data product WINDTUR-VLW_L1 from the FDCHP
instrument, which collects 20 minutes of data every hour. The L1 data
... | e0136ff7ddaf676b99f28700e3613523bb57b12e | 28,379 |
def reports():
"""View reports"""
return render_template("reports.html") | b69119a97998595757d52e5641246bbeea007d18 | 28,380 |
def otr_statusbar_cb(data, item, window):
"""Update the statusbar."""
if window:
buf = weechat.window_get_pointer(window, 'buffer')
else:
# If the bar item is in a root bar that is not in a window, window
# will be empty.
buf = weechat.current_buffer()
result = ''
i... | 9fb58921b901e542ad6f8bed7207337db56de872 | 28,381 |
def rotate_ellipse_NS(time_deg, datastruc, const):
"""Rotate ellipse major/minor axis to north/south orientation."""
# Construct major and minor
major, minor, pha, inc = get_constituent(const, datastruc)
# construct current at this time
try:
major_current = major*np.cos(np.deg2rad(time_deg -... | 48c4d4270e8a521969608369974c59cff6700a03 | 28,382 |
import requests
def img_lookup(pid):
"""Query for object type and return correct JPG location"""
r = requests.get("https://fsu.digital.flvc.org/islandora/object/{0}/datastream/JPG/view".format(pid))
if r.status_code == 200:
return r.url
elif r.status_code == 404:
r2 = requests.get("htt... | ac9ccfc64e4bf38b0f22e90649368cae1ad89b18 | 28,383 |
from datetime import datetime
def _get_midnight_date(date):
"""Return midnight date for the specified date.
Effectively, this function returns the start of the day for the
specified date.
Arguments:
date -- An arbitrary date (type: datetime.datetime)
Return: Midnight date (type: datetime.da... | 165a884fd12e79f167c9818126e1e31a3b2dc8b3 | 28,384 |
def get_workflow_entrypoint(definition_class, workflow_name, workflow_version):
"""Get the entry point information from *workflow_class*.
This function provides a convenient way to extract the parameters
that need to be returned the *get_workflow* argument to
:py:class:`~.GenericWorkflowWorker`
:p... | 87a7cbc1ad810e08033f19d1d3c7551ff8b4eb46 | 28,385 |
def expect_types(*_pos, **named):
"""
Preprocessing decorator that verifies inputs have expected types.
Usage
-----
>>> @expect_types(x=int, y=str)
... def foo(x, y):
... return x, y
...
>>> foo(2, '3')
(2, '3')
>>> foo(2.0, '3')
Traceback (most recent call last):
... | 92b7682bda54f02c095d10534b71fb02fea1a763 | 28,386 |
def squash_by(child_parent_ids, *attributes):
"""Squash a child-parent relationship
Arguments
---------
child_parent_ids - array of ids (unique values that identify the parent)
*attributes - other arrays that need to follow the sorting of ids
Returns
-------
child_parents_idx - an arra... | 1c68bb38ee10044803021f4d74b37ea4b161eef5 | 28,387 |
import random
import math
def _generate_quantsets(num_vars, num_qsets, ratio):
"""
_generate_quantsets(num_vars : int,
num_qsets : int,
ratio : float)
return (quantsets : list)
Generates a list of random quantifier sets according to given argument... | e01e053e64384f0304fd21200bd31485f0e6eb06 | 28,388 |
import argparse
def get_parser():
"""
Parses the command line arguments.
:returns: a parser with command line arguments
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description="Modbus Slave Endpoint.")
port_choices = SerialPort.list_serial_ports() + ['tcp:502', '... | 42b18670fe981cf2b6fa9cb2983573b4eee73af6 | 28,389 |
def encoder(src_embedding, src_sequence_length):
"""Encoder: Bidirectional GRU"""
encoder_fwd_cell = layers.GRUCell(hidden_size=hidden_dim)
encoder_fwd_output, fwd_state = layers.rnn(
cell=encoder_fwd_cell,
inputs=src_embedding,
sequence_length=src_sequence_length,
time_major... | f23fb197838952017d3706db221ab55c9807bbb0 | 28,390 |
def _class_search_post_url_from(absolute_url, form):
"""Determines absolute URL to submit HTTP POST query request to"""
method = form.get(HTTP_METHOD)
if method != POST:
raise ValueError("Expected POST form submission method; Got "+repr(method))
action = form.get(ACTION)
dest_url = urljoin(a... | 9547643b49cec1a4ea272c31b6a5399c076fa487 | 28,391 |
def pcmh_2_2d__3_5_6_7_8():
"""Huddles, Meetings & Trainings"""
huddle_sheet_url = URL('init', 'word', 'huddle_sheet.doc', vars=dict(**request.get_vars), hmac_key=MY_KEY,
salt=session.MY_SALT, hash_vars=["app_id"])
# referral tracking chart
huddle_sheet = MultiQNA(
5... | 73946627100342c07083e656d92d2364d166cc16 | 28,392 |
def CallCountsToMockFunctions(mock_function):
"""A decorator that passes a call count to the function it decorates.
Examples:
@CallCountsToMockFunctions
def foo(call_count):
return call_count
...
...
[foo(), foo(), foo()]
[0, 1, 2]
"""
counter = [0]
def Result(*args, **kwargs)... | cc621cabdf87ff554bb02c25282e99fadcaaa833 | 28,393 |
from typing import Callable
from typing import Tuple
import scipy
def multi_start_maximise(objective_function: Callable,
initial_points: ndarray, **kwargs) -> Tuple[ndarray, float]:
"""Run multi-start maximisation of the given objective function.
Warnings
--------
This is a h... | 6eabacc0d84389c45ddbd75fd84a27cf312e65be | 28,394 |
async def ping():
"""
.ping: respond with pong
"""
return "pong" | 988165efb5087fd838a2930dbe4ed540b2d70037 | 28,395 |
from statsmodels.tsa.stattools import adfuller
def stationarity_check(TS,plot=True,col=None):
"""From: https://learn.co/tracks/data-science-career-v2/module-4-a-complete-data-science-project-using-multiple-regression/working-with-time-series-data/time-series-decomposition
"""
# Import adfuller
i... | 4b2120b4da74a08e13f61220bd212ae6016f3a73 | 28,396 |
import re
def generate_modelname(tpl,
nlayers: int = -1,
nhid: int = -1,
nagts=-1,
bptt: int = -1,
pre: bool = False,
arch: str = None):
"""
Generates model name from param... | 23c7b36c8e08376f15e8a53d569b33d2a5de770f | 28,397 |
def file_exists(session, ds_browser, ds_path, file_name):
"""Check if the file exists on the datastore."""
client_factory = session._get_vim().client.factory
search_spec = vm_util.search_datastore_spec(client_factory, file_name)
search_task = session._call_method(session._get_vim(),
... | 00b856d529f16ea05123f2b4447d94698d986902 | 28,398 |
def convert_binary_to_unicode(binary_input):
"""
converts binary string of length 18 input to unicode
:param binary_input: String
:return: String
"""
unicode_output = ''
for starting_position in range(0, len(binary_input), 18):
unicode_output += chr(int(binary_input[starting_positio... | ae00c8b31779420662dca09e1ca6c23590b45e38 | 28,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.