content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def manhattan_distance(current, target, moved):
"""
Manhattan distance from current position to target
Args:
current (tuple): x, y coordinates of the current position
target (tuple): x, y coordinates of the target
Returns:
(float): Manhattan distance from current position to target
"""
dist = abs(targ... | bbdb8517327f520609e2e98466d918baab517674 | 75,290 |
def noisy_max(answers: np.ndarray, epsilon: float, sensitivity: float):
""" Implementation of the noisy max mechanism with gap using Laplace noise
Given a set of queries, this mechanism will return the **index**, not the
value, of the query that is probably largest.
Args:
answers (float or numpy... | 7ea3a579d6e28a0bef731e6a0a5158a32c145793 | 75,291 |
def loss(logits, labels):
"""L2 error computing.
"""
sparse_labels = tf.reshape(labels, [FLAGS.batch_size, 1])
indices = tf.reshape(tf.range(FLAGS.batch_size), [FLAGS.batch_size, 1])
concated = tf.concat([indices, sparse_labels], 1)
dense_labels = tf.sparse_to_dense(concated, [FLAGS.batch_siz... | 4ce5175c62ca10a849305e25ffe3ad78c556a72a | 75,292 |
import json
def edit_config(data):
"""Edit configuration in data/commentary_conf.json"""
with open(CONFIG_PATH, 'r') as f:
conf = json.load(f)
if len(data) > 0:
for k,v in data.items():
conf[k] = v
with open(CONFIG_PATH, 'w') as f:
json.dump(conf,f, indent=... | 312a23cfa8b631ea7d28bb3328c141b160e2b4ba | 75,293 |
def sigma2_debye(t, theta, path=None, _larch=None):
"""calculate sigma2 for a Feff Path wih the correlated Debye model
sigma2 = sigma2_debye(t, theta, path=None)
Parameters:
-----------
t sample temperature (in K)
theta Debye temperature (in K)
path FeffPath to cacluate... | 4316b403994b090c200b325879da7219c96ab785 | 75,294 |
from typing import Optional
def predict_regioselective_sites(
mol: Mol, pdf_protomers: pd.DataFrame, energy_cut1=1.0, energy_cut2=3.0, mopac_options={}
) -> Optional[Mol]:
"""
Return molobj with annotated atoms
Assumes salt is removed
"""
# Neutralize molobj
mol = chembridge.neutralize_mo... | 6ff76b1efdf76a287acf756b307cdf91d6ab6d4c | 75,295 |
from typing import Optional
def highlight_quad(
quad: dom.Quad,
color: Optional[dom.RGBA] = None,
outlineColor: Optional[dom.RGBA] = None,
) -> dict:
"""Highlights given quad. Coordinates are absolute with respect to the main frame viewport.
Parameters
----------
quad: dom.Quad
... | cc236bdc1ee7b4a45e1063323cf5efc3993ce7c2 | 75,296 |
import random
def light_leak(tensor, shape, alpha=.25, time=0.0, speed=1.0):
"""
"""
x, y = point_cloud(6, distrib=PointDistribution.grid_members()[random.randint(0, len(PointDistribution.grid_members()) - 1)], drift=.05, shape=shape, time=time, speed=speed)
leak = voronoi(tensor, shape, diagram_typ... | ee66dae2c233fec39794d182c988958d776c6f41 | 75,297 |
def Fabber(*search_dirs, **kwargs):
"""
Get an API object for Fabber. Uses the shared lib API if available
and requested using `shlib=True`, otherwise use command line wrappers
:param extra_search_dirs: Extra search directories to use to look for Fabber libraries and executables
"""
corelib, co... | 702f14c6d76279794887792adaf18703a472445a | 75,299 |
def home():
"""
This function just responds to the browser ULR
localhost:5000/
:return: the rendered template 'home.html'
"""
return render_template('home.html') | 9a47911d52950181546faf44ce9977533eebaaa4 | 75,300 |
def update_par_helper(row, blocks, add_num):
"""The current function accepts line, line constraint, and integer.The
purpose of the function is to update the parameters it receives (those
parameters which the main function receives) according to the
pointer value. For each of the three possible values, i... | 732bba078066418312c454dd4fbb7132632f25d2 | 75,301 |
import logging
def breaksensorFactory(descp):
"""
Creates break sensors from a break sensor descp
"""
try:
if "RIODigitalIn" in descp["type"]:
return di(descp["channel"])
except Exception as e:
logging.error("Failed to create IR Break sensor for %s. Error %s", descp, e... | 5e7ec49e99f00979d0cfaca2aeecbce055b90700 | 75,303 |
def _get_seeds_to_create_not_interpolate_indicator(dense_keys, options):
"""Get seeds for each dense index to mask not interpolated states."""
seeds = {
dense_key: next(options["solution_seed_iteration"]) for dense_key in dense_keys
}
return seeds | e3ee4260309be644f11becba19f1ef3386d182d9 | 75,304 |
from typing import Dict
from typing import List
def align_timepoints(agg_data: Dict, agg_timepoints: List) -> Dict:
""" Align the timepoints
:param dict agg_data:
A mapping of key: [list of timepoint stats]
:param list agg_timepoints:
A list of timepoints corresponding to each stat
:r... | a903ac03e42ec9d09e90c3a19c379554702ad455 | 75,305 |
import tokenize
def build_model():
"""Build a multi-output classification model
Returns:
pipeline => multi-output classifier pipeline
"""
pipeline1 = Pipeline([
('features', FeatureUnion([
('text_pipeline', Pipeline([
('count_vectorizer', CountVectorizer(to... | 5e1531c3f30f18546af6d507ecae177214d2b809 | 75,307 |
def get_cluster():
"""Grappler optimization configuration for GPU."""
named_device = device_properties_pb2.NamedDevice()
named_device.name = '/GPU:0'
named_device.properties.type = 'GPU'
named_device.properties.environment['architecture'] = '4'
cluster = gcluster.Cluster(devices=[named_device])
return clu... | 561db29b7d7ee00298b63e193d2b163bdffbe389 | 75,308 |
def device_detail(request, deviceid):
"""
Retrive or delete a device instace.
"""
try:
device = Device.objects.get(dev_id=deviceid)
except:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = DeviceSerializer(device, context={'reque... | 48f7f89838fb28d824849d7ff0fc9e2dc96b0b90 | 75,310 |
def Transit(t, P, i, r_a, p, t0, u1, u2, e, omega):
"""
Calculates transit light curve, normalized
non-obvious pars:
r_a=R_*/a
p = R_p/R_*
"""
if (e > 0):
f = np.pi/2 - omega
E = 2.0 * np.arctan2(np.sqrt( (1.0-e)/(1.0+e)) * np.sin(f/2.0), np.cos(f/2.0) )
n = 2 * np.... | 170905af76c979311d20a6e193fa59d26123fec5 | 75,311 |
def put(path, key):
"""Takes a local file path and puts it into key in the bucket
Parameters
----------
path : str
Local filename
key : str
Filename in s3 bucket
Returns
-------
burrito : boolean
Whether the transfer was successful (True) or failed (False)
... | ace42eaa82658f8539710ec06b39bd6aab60830b | 75,312 |
def type2TermCombination(member,klass,context):
"""Maps a type to a TermCombo"""
try:
rt = TERM_COMBINATIONS['%sU%s%s' % \
(term2Letter(member),
term2Letter(klass),
normalizeGraph(context)[-1])]
return rt
except:
... | c28170da6dcc6db0757f5c965eaa21701e5f71c6 | 75,313 |
def make_bigrams(bigram_mod, texts):
"""Gera bigrama dos textos."""
return [bigram_mod[doc] for doc in texts] | 9ac129f72a5dd4fdf4fb64694073df2482a76a9e | 75,314 |
def prepare_exons_for_cesar(exon_seqs):
"""Cesar requires some special formatting for exons."""
# CESAR requires a special king of reference exons formatting
# Split codons should be written in lowercase, as follows:
# ATGTTTa ctGTAAAGTGCc ttAGTTGA
verbose("prepare_exons_for_cesar")
left_pointer... | e7742a84e94b7152dc84c2abca2ef1f10028b1f8 | 75,315 |
def student_t_shape_statistic_d_known(X, Args):
""" GLRT test for testing a change in the shape of a multivariate
Student-t distribution when the degree of freefom is known.
Inputs:
* X = a (p, N, T) numpy array with:
* p = dimension of vectors
* N = numbe... | 3c09a1d00ae30cbf96c62f8f3505de6ea279335d | 75,316 |
def mandel_numpy(n=400,maxi=512):
"""Compute an n x n Mandelbrot matrix with maxi maximum iterations."""
# get 2-d arrays for x and y, using numpy's convenience function
xs, ys = N.meshgrid(N.linspace(x0,x1,n), N.linspace(y0,y1,n))
z = N.zeros((n,n),'complex128') # a matrix of complex zeros
c... | a94dfde2f891fa73937579a7517ff329b920f1da | 75,317 |
def _case_convert_snake_to_camel(token: str) -> str:
"""Implements logic to convert a snake case token to a camel case one.
"""
while True:
try:
# find next underscore
underscore_loc = token.index('_')
except ValueError:
# converted all underscores
... | 3796f627cc836f884aeab765769cf652f8fd1ff9 | 75,318 |
def running_average(x):
"""
Return cummulative average of an array.
"""
y = np.zeros(len(x)) # new array to store result
current_sum = 0.0 # running sum of elements of x
for i in range(len(x)):
current_sum += x[i] # increment sum
y[i] = current_sum / (i + 1.0) # update running average
return y | e67f72149ef86e1672cb64f5f03112df8eabe1b2 | 75,319 |
def doeqdi(x, y, UP=False):
"""
Takes digitized x,y, data and returns the dec,inc, assuming an
equal area projection
Parameters
__________________
x : array of digitized x from point on equal area projection
y : array of igitized y from point on equal area projection
UP : if... | f99f0bc5e2f5961b1480d74f7ae9023f21e25842 | 75,320 |
import scipy
def inverse_boxcox(Y: np.ndarray, lmbda):
"""
Inverse Box-Cox transformation.
Parameters
---------------
Y : :class:`numpy.ndarray`
Array on which to perform the transformation.
lmbda : :class:`float`
Lambda value used to forward-transform values.
Returns
... | c570ab4af552259e5331ce3882dbe289a805c1d5 | 75,321 |
def make_reduce_compose(obj, hook_cls, hooks: list):
"""only keeps the overridden methods not the empty ones"""
def _get_loop_fn(fns):
def loop(*args, **kwargs):
for fn in fns:
fn(*args, **kwargs)
return loop
method_list = [func for func in dir(hook_cls)
... | 03cc81714ec1309e2db896d0e59f98ac528f5adb | 75,322 |
def gaussian_kernel(epsilon, obs_data, sim_data):
"""gaussian distance function"""
return np.sum(-0.5 * ((obs_data - sim_data) / epsilon) ** 2) | e893fb7cb100f2a514b39b6cd254a285bfa29358 | 75,323 |
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), form... | 7fc4e90e496ea6f04838a1ccefb810c2467fafaf | 75,324 |
def FieldWidget(field, widget): # pylint: disable=invalid-name
"""Set the field for the widget."""
widget.field = field
if not IFieldWidget.providedBy(widget):
alsoProvides(widget, IFieldWidget)
# Initial values are set. They can be overridden while updating the widget
# itself later on.
... | 56fe0309d0267cc36bac508fd10fea1518558695 | 75,325 |
def get_object_bank_from_request(request):
"""parse out the right params before passing to get_object_bank
Do NOT use the convenience methods here with session, etc."""
valid_params = ['/assessment/items/']
path = request.path
if any(p in path for p in valid_params):
test_request = SimpleReq... | d0aaa8997adf5a58a514f5a91dbb9f14e46702b5 | 75,326 |
from datetime import datetime
def update_timeseries(fr_dt, t_dt):
"""
This callback function updates the time series based on date picker component.
"""
fr_dt = fr_dt[:10]
t_dt = t_dt[:10]
from_dt = datetime.datetime.strptime(fr_dt, '%Y-%m-%d')
to_dt = datetime.datetime.strptime(t_dt, '%Y-... | 51810d86006506ac6b2812651389d7a6cb20068e | 75,327 |
import base64
def to_base64(data):
"""
Utility function to base64 encode.
:param data: The data to encode.
:return: The base64 encoded data.
"""
return base64.b64encode(data) | 014ca1e1534e9350034e148abcceac525b0f0349 | 75,328 |
def get_pundit_categories():
"""Return list of pundit categories"""
config = configuration()
return [category for category, value in config.items('punditpanels')] | 46107f2865a0b0b7dc76759478b92e4d65188ac0 | 75,329 |
def process_gdkkeysymsh():
""" Opens the gdkkeysyms.h file from GTK+/gdk/gdkkeysyms.h """
""" Fills up keysymdb with contents """
filename_gdkkeysymsh = download_file(URL_GDKKEYSYMSH)
try:
gdkkeysymsh = open(filename_gdkkeysymsh, 'r')
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, stre... | 1dea443ca61ef2810e8ef21cafddadd9e5af7319 | 75,330 |
import plistlib
def LoadPlist(filename):
"""Plists can be read with plistlib."""
try:
return plistlib.readPlist(filename)
except:
print('python3.4 is required to read binary plist %s, skipping' % filename)
return None | 99c82247e2246ce077ba5530bf2cdd2af1705fe5 | 75,331 |
def Gxx_shifted_2d(field, costheta, sintheta, space_order):
"""
2D rotated second order derivative in the direction x as an average of
two non-centered rotated second order derivative in the direction x
:param field: symbolic data whose derivative we are computing
:param costheta: cosine of the tilt... | b017f6924209b48c8f9fecbea918c1f30d3b6307 | 75,332 |
def encode_dict(dict_in, charset='utf8'):
""" Encodes dict values to UTF-8
Args:
dict_in (dict): Input dictionary with unicode values
Returns:
dict: Output dictionary with UTF-8 encoded values
"""
try:
dict_out = {}
for k, v in iteritems(dict_in):
if PY2... | 5ce2e515c27236ec1b9d06f572a40a5fc8f47ade | 75,333 |
def json_set_check(obj):
"""
json.dump(X,default=json_set_check)
https://stackoverflow.com/questions/22281059/set-object-is-not-json-serializable
"""
if isinstance(obj, set):
return list(obj)
raise TypeError | d8b632c54938aac4797794d5d40fcd93c3415e04 | 75,334 |
def pe_dist_v1(a_xy, b_pv):
"""
:param a_xy: n, 2 | (x_x, x_y)
:param b_pv: k, 4 | (x_x, x_y, v_x, v_y)
:return:
pe_dist: n, k | perpendicular distance of each a to each b
pa_dist: n, k | parallel distance (signed)
"""
# n, k, 2
pos_dif = a_xy[:, np.newaxis, :2] - b_pv[np.new... | e851b991f461a6228388d297bc125cf606fc460f | 75,335 |
import zipfile
def get_pfile_contents(pfile):
"""
Get a list of files within the pfile Archive
"""
if zipfile.is_zipfile(pfile):
zip = zipfile.ZipFile(pfile)
return zip.namelist()
else:
return None | 8f67b87a0e35fe42d0c20cb9ed0c3cdc93a89163 | 75,336 |
import tarfile
import gzip
def headerfile_content_from_raw_archive(infile, headerfile_name):
"""Extract headerfile for Snow Water Equivalent (SWE) based on
<input file> Path to the raw .tar SNODAS archive for a given day
<headerfile_name> Name of file to extract from raw archive
"""
w... | 78fc2b8d952b0711c1375a3959d62f51024f1b30 | 75,337 |
def convert_single_mathqa_example(example, option, is_training, tokenizer, max_seq_length,
cls_token, sep_token):
"""Converts a single MathQAExample into Multiple Retriever Features."""
""" option: tf idf or all"""
"""train: 1:3 pos neg. Test: all"""
pos_features = []
... | 594d33f2d6dfcccbc7fa100bb3080eb385c07a1f | 75,339 |
def rate(report, rate_type):
"""generate gamma or epsilon rate
report (list of str): diagnostic report
rate_type (str): gamma or epsilon
return: binary result in form of str"""
pre_rate = []
if rate_type == "gamma":
rt = 1
elif rate_type == "epsilon":
rt = -1
else:
... | 3e08ea470bcbdc7805f2f056086f2965aa4bc91f | 75,340 |
def create_index():
"""
Creates an index for the given window
:return:
"""
log("Create Index: Received req: {0}".format(request.form))
# res = create_viz_index({"sw": (-124, 27), "ne": (-59, 48)}, [int(i) for i in request.form['zoom']])
res = create_viz_index({"sw": (-124, 27), "ne": (-59, 4... | f4c778d8dfaa49d79e665eb4c2c189df3ae59d34 | 75,341 |
def as_class_name(*args, **kwargs):
"""Convert string into a CamelCase class name."""
return delimited_to_camelcase(*args, **kwargs) | 3f8a2739b40171f5a786dc2f7e9fd3fffd44e235 | 75,342 |
import re
def natural_sort(l):
""" https://stackoverflow.com/a/4836734 """
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)", key)]
return sorted(l, key=alphanum_key) | 838658c5374253ffaa6f5ad6380880fbb27aa3b3 | 75,343 |
def angle_param_linear(feature_vector, params):
"""Returns the "parameterized linear encoding" of the feature vectors
theta * feature_vector[0]
2 * phi * feature_vector[1]
"""
[theta, phi] = params
return (theta * feature_vector[0], phi * feature_vector[1])
# return (theta * feature_vector[... | 01db73c3b9bfe5b9c21d2bc39cb26ec501759022 | 75,344 |
from functools import reduce
import operator
def _getRouting(path, exitType, exitInfo):
"""Given a list of ServerInfo, and a final exitType and exitInfo,
return a 3-tuple of:
1) A list of routingtype/routinginfo tuples for the header
2) The size (in bytes) added to the header in order... | 366117b230739e5330bd4bcc5c4338c41cc84f74 | 75,346 |
from typing import Union
from typing import Sequence
from typing import Tuple
from typing import Optional
def clonotype_network(
adata: AnnData,
*,
color: Union[str, Sequence[str], None] = None,
basis: str = "clonotype_network",
panel_size: Tuple[float, float] = (10, 10),
color_by_n_cells: boo... | 667453b817e59a4c73e2dd50c03a9b755c2dd495 | 75,347 |
def getSystemMetadata(identifier, cache=False):
"""Gets the system metadata for an identifier.
In development, I'm keeping a cache of documents in the root of the
d1lod folder at ./cache. This will need to be removed in
production. This is toggled with the argument `cache`.
Arguments:
iden... | 7f2afcb6b2d38279691b61182e4e643556740c61 | 75,348 |
def get_widget_from_id(id):
"""returns widget object by id
example web-htmltextwidget-2-2
"""
res = id.split('-')
try:
model_cls = apps.get_model(res[0], res[1])
obj = model_cls.objects.get(parent=res[2], id=res[3])
except:
obj = None
return obj | af91e0abd037217b21eea3c86b3f8193316f8962 | 75,349 |
def to_float32(data):
"""
Cast data (typically from WAV) to float32.
Parameters
----------
data : numpy array
Real signal in time domain, typically obtained from WAV file.
Returns
-------
numpy array
`data` as float32.
"""
if np.issubdtype(data.dtype, np.intege... | 1d37bc93d946c68fe8010b483c0e3cc4b52de413 | 75,350 |
import re
def twitter_preprocess(
text: str,
no_rt: bool = True,
no_mention: bool = False,
no_hashtag: bool = False
) -> str:
"""
Preprocessing function to remove retweets, mentions and/or hashtags from
raw tweets.
Examples
--------
>>> twitter_preproce... | 1644b7da6b43ebd77a33bcb186f2634b6d3bc8db | 75,351 |
from typing import Optional
from typing import Tuple
from typing import Any
import tqdm
def find_label(
graph: MultiDiGraph, query: str, verbose: bool = True
) -> Optional[Tuple[Any, Any]]:
"""Returns the edge label
containing the specified string.
Parameters
----------
graph : MultiDiGraph
... | 234475a1f775c81810566878eb138fad9532b939 | 75,352 |
def create_company_view(request):
"""
Creates a company on ``POST`` request and returns a company creation form ``GET`` request.
.. http:get:: /company
Gets the company creation form.
**Example request**:
.. sourcecode:: http
GET /company/ ... | 7824270cd0f53ee9207fbcf1f4b5ecb492c64260 | 75,353 |
def get_plans(app_configuration, subproject_name):
"""Return a flattened list of standardised plans."""
ack = _make_app_config_kwargs(app_configuration, subproject_name)
plans = []
products = get_products(**ack)
print('Using these products:-')
print(products)
for product in products:
... | 4b1e38cca81b8919934bf2bee1fcfbe84000d7af | 75,354 |
def main(files_dirs):
"""
Parameters
----------
files_dirs : seq
list of strings w/ files and/or dirs
"""
return assemble_result(get_merkle_tree(files_dirs)) | a748a2e8777dc975f58434ab727c00bc69b3cdfa | 75,355 |
def format_quote(username, content):
"""Returns a formatted quote depending on the markup language.
:param username: The username of a user.
:param content: The content of the quote
"""
profile_url = url_for('user.profile', username=username)
content = "\n> ".join(content.strip().split('\n'))
... | 12f146611722faa02c668b48a1bd260e31697cb6 | 75,356 |
def PyObject_RichCompareBool(space, ref1, ref2, opid):
"""Compare the values of o1 and o2 using the operation specified by opid,
which must be one of Py_LT, Py_LE, Py_EQ,
Py_NE, Py_GT, or Py_GE, corresponding to <,
<=, ==, !=, >, or >= respectively. Returns -1 on error,
0 if the result is false, 1 o... | 090743304e36f56c80adf32ea222f7765820abb1 | 75,357 |
def cal_percent(image):
"""
Class Name,B,G,R
0,0,0,0
低矮植被,0,255,255
其它,255,255,255
树木,0,255,0
建筑物,255,0,0
不透水面,0,0,255
汽车,255,255,0
surfaces (RGB: 255, 255, 255)
Building (RGB: 0, 0, 255)
low vegetation (RGB: 0, 255, 255)
Tree (RGB: 0, 255, 0)
Car (RGB: 255, 255,... | 850f1f4d2fbbf070eb8bc8847caf419ce8849037 | 75,358 |
def query_db(query, args=(), one=False):
"""Queries the database and returns a list of dictionaries."""
cur = g.db.execute(query, args)
rv = cur.fetchall()
return (rv[0] if rv else None) if one else rv | 71a668b5bbdb8f140cf245ea8b1b1499c3bcae9f | 75,360 |
def complex_derivative ( fun , z , h = 0 , I = 2 , err = False , real = True , imag = True ) :
"""Get a complex derivative
- The function is assumed to be analytical (Cauchy-Riemann conditions are valid).
>>> fun = ...
>>> d = complex_derivative ( fun , x = 1+2j )
"""
Z = complex ( z )
... | 159fe17f1b8ae880dc147cb1a808a44732ceb15c | 75,361 |
def numpy_to_gdal_type(numpy_type):
"""Set the GDAL raster data type based on the numpy array data type
The following built in functions do roughly the same thing
NumericTypeCodeToGDALTypeCode
GDALTypeCodeToNumericTypeCode
Args:
numpy_type (:class:`np.dtype`): numpy array type (i.e. np.boo... | 4200a6f83ec22179983771d3bf9418c8d6a05431 | 75,362 |
async def client_fixture(transport: tuple[AsyncMock, AsyncMock]) -> Client:
"""Mock a client."""
return Client("test-password") | 184bd95fa7b60f7eb5f69f85307885a955efa693 | 75,364 |
def calculate_diff_metrics(util1, util2):
"""Calculate relative difference between two utilities"""
util_diff = {}
for metric_k1, metric_v1 in util1.items():
if metric_k1 not in util2:
continue
util_diff[metric_k1] = {}
for avg_k1, avg_v1 in metric_v1.items():
... | 45b8dc7a2441333870c8a0faa5b6e8da56df8a40 | 75,365 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | e2e64d97e917cd645755914dead6a7c07f153ba3 | 75,366 |
from typing import List
from typing import Union
def get_complete_binary_metrics() -> List[Union[AUC, str, BinaryMetric]]:
"""Return complete list of binary metrics.
This method returns ALL the implemented metrics.
The set of metrics includes accuracy, balanced accuracy, AUROC, AUPRC,
F1 Score, Reca... | 84741336f55de182a39fee8ab6fc88893c4ef3b0 | 75,367 |
from typing import Dict
from typing import Any
async def provider() -> Dict[str, Any]:
"""Define a basic example data provider function."""
async with HTTPClient() as client:
response = await client.get("https://httpbin.org/html")
dom = PyQuery(response.text)
return {
"title": "Example... | 4c9275ad3abbaa1366fade7b20f2d6b4f0f44b26 | 75,368 |
from typing import Dict
from typing import Optional
def improve_policy_with_q_pi(
agent: MdpAgent,
q_pi: Dict[MdpState, Dict[Action, float]],
epsilon: Optional[float] = None
) -> int:
"""
Improve an agent's policy according to its state-action value estimates. This makes the policy gre... | cdf6f8cf638c198b60bb27d0d158720cec922c34 | 75,369 |
def dfmnet_model(
phase, source_shot, target_shot,
source_evecs, source_evecs_trans, source_evals,
target_evecs, target_evecs_trans, target_evals):
"""Build DFMnet model.
Args:
phase : train\test.
source_shot : SHOT descriptor of source shape.
... | 7f5b6ab8e8ea86ea49657ad432c1118f27ea7292 | 75,370 |
def davies_bouldin(
adata: AnnData, partition_key, obsm_representation: str = None
):
"""
By default, computes the Davies-Bouldin index for the adata with respect
to the clustering specified by partition_key.
If given a value for obsm_representation, computes the index on the
representation of t... | d6dd1c2ef56d084e8554b9be7e94d4f642ce1bec | 75,371 |
def clean_text(text: str) -> list[str]:
"""Return text as a list of words that have been cleaned up.
Cleaning up involves:
- removing punctuation
- converting all letters to lowercase (because our VADER keywords
are all written as lowercase)
"""
# Remove punctuation from text
... | 47b1475c9df69f339585ce2f17378df913e541ba | 75,372 |
from datetime import datetime
def make_biz_message_identification(participant_id):
""" Generate message id, structure: BYYYYMMDDbbbbbbbbbbbXAAAnnnnnnnnnnn """
date = datetime.now().strftime('%Y%m%d')
serial_identifier = 'PSP'
source = 'B'
serial_nunmber = rand_x_digit_num(11)
mid = "B{date}{... | dc408c155c3996ac18ab70c669c178543cbe23fd | 75,373 |
def rpht_output(file_name):
""" Read the projected frequencies
"""
# Read the file and read in the non-zero frequencies
freqs = []
with open(file_name, 'r') as freq_file:
for line in freq_file:
if line.strip() != '':
freqs.append(float(line.strip()))
# Build... | e2f7e181f68c23be276588e662dd7db9f7355270 | 75,374 |
def load_trp(filename):
"""Loads a Tibia Replay recording (file extension .trp)
Loads a Tibia Replay recording and returns a Recording object.
Arguments:
filename: The filename of the Tibia Replay file.
"""
r = Recording()
with open(filename, 'rb') as f:
magic = utils.read_u16... | 668d894acdf126d532d90879235c29fe0e8b227f | 75,375 |
def delete_comment(request):
"""API delete_comment"""
if request.method == 'POST':
id = request.POST['id']
comment = get_object_or_404(Comment, pk=id)
if request.user.username == comment.userid or request.user.is_staff:
comment.status = '6deleted'
else:
r... | 16f6b7126fd84b1321dacf8ad63d01773cc9d9f2 | 75,376 |
def deep_get(d, keys, default=None):
"""
Source: https://stackoverflow.com/questions/25833613/python-safe-method-to-get-value-of-nested-dictionary
Example:
d = {'meta': {'status': 'OK', 'status_code': 200}}
deep_get(d, ['meta', 'status_code']) # => 200
deep_get(d, ['garbage... | ba7faa699206b068b2d0c57b0d43b00afcef09eb | 75,377 |
def read_tables(csv_files, delimiter):
"""Read a list of csv/tsv files into data frames.
Raises
------
ValueError
If the csv files don't have the same number of columns
"""
dfs = [pd.read_csv(f, dtype=str, sep=delimiter) for f in csv_files]
headers = [read_header(f) for f in csv_fi... | fccc0d301aba8faff03279c9c535c343d8546248 | 75,379 |
def precision_score(y_true, y_pred, average=None):
"""
For each class `j`, return the ratio of the number
of correct classificatin of `j` over number of times
`j` was predicted in total.
Parameters
----------
y_true : iterable object
Ground values.
y_pred : iterale object
... | 6381e1835fa11f0829edde881113007e98e04c50 | 75,380 |
def exists(
store: BaseAccessStore,
args: Args,
) -> bool:
"""
checks if relationship exists between the principal and the granted
for the given principal and granted types
if the combo id key exists, the relationship exists
"""
res = store.get(
key="-".join([args.principal, arg... | bd2c27b1c4463ed3e16e2f6dc385d56fc17177a7 | 75,381 |
def get_type_id(geometry):
"""Returns the type ID of a geometry.
- None is -1
- POINT is 0
- LINESTRING is 1
- LINEARRING is 2
- POLYGON is 3
- MULTIPOINT is 4
- MULTILINESTRING is 5
- MULTIPOLYGON is 6
- GEOMETRYCOLLECTION is 7
Parameters
----------
geometry : Geom... | 3ef08841efcb6b01f948ea744e76c10ef4713670 | 75,382 |
import re
import json
def _parse_url(stylesheet: str) -> set[_Url]:
"""Parse $url{...} symbol in template stylesheet."""
urls = set()
for match in re.finditer(r"\$url\{.+\}", stylesheet):
match_text = match.group()
json_text = match_text.replace("$url", "")
url_property: dict[str,... | 7f05a1ddf80a7fbd43f77b6a0b98281ffaf13564 | 75,383 |
from typing import Iterable
from typing import Callable
from typing import Iterator
def combine(
augmenters: Iterable[Callable[[Language, Example], Iterator[Example]]]
) -> Callable[[Language, Example], Iterator[Example]]:
"""Combines a series of spaCy style augmenters.
Args:
augmenters (Iterable... | dd78efdab2fe006ffb5cdd59910d1e69818e23dc | 75,384 |
def test_yearplot_cmap_fillcolor_linewidth(events):
"""
The appearance can be changed by using another colormap. Here we also use
a darker fill color for days without data and remove the lines.
"""
ax = calmap.yearplot(events, cmap='YlGn', fillcolor='grey', linewidth=0)
return ax.figure | 737d5247cf37bd217a7e0d4a0a24c0218e8a18f8 | 75,385 |
from typing import List
from typing import Tuple
import re
def extract_format_items(s: str) -> List[Tuple[int, str]]:
"""Return a list (index, format item) pairs from a c-style format string.
Based on:
https://stackoverflow.com/questions/30011379/how-can-i-parse-a-c-format-string-in-python
"""
c... | 93ce59d40dd60772a9ea6235c945a17d71ca07d0 | 75,386 |
def text_progress(current, total):
"""Opens the photo_import_settings.json file in a text editor
Parameters:
current (String): The currently completed progress
total (String): The total amount
Returns:
progress (String): A formatted string with the current progress [current/total]... | b04b5bf018ff96c2e0f4ed5f1ce60c20c21e9574 | 75,387 |
from typing import Union
def copy_and_reset_model(
model: Union[keras.Model, nn.Module, BaseEstimator]
) -> Union[nn.Module, keras.Model]:
"""
Get a clone of a model (i.e. with the same architecture) and reset the weights \
of this copy.
:param model: A TF or Torch model. Alternatively, an ar... | b96220177be2280913baeb4a43673a64e63221cb | 75,389 |
def _householder_factor(newton, halley, hh3):
"""
:param newton:
:param halley:
:param hh3:
:return:
"""
return (1 + 0.5 * halley * newton) / (1 + newton * (halley + hh3 * newton / 6)) | 373e3155557a2403ec79e78a5239d54f2ca651f5 | 75,390 |
def is_loopback(address):
"""
Check if an address is a loopback address or a common name for the loopback
interface.
:param str address: The address to check.
:return: Whether or not the address is a loopback address.
:rtype: bool
"""
if address == 'localhost':
return True
elif is_valid(address) and ip_addr... | 7b49bc545d7abb8b87354842caf9c5487cec1399 | 75,391 |
def calculate_distances(station_list, epicenter):
"""
Calculates distanes from all stations
"""
distances = {}
# Find station coordinates from station list
st_file = open(station_list, 'r')
for line in st_file:
line = line.strip()
if not line:
# skip blank li... | 082776745121e6d2552bed846d4182ead6d08cff | 75,392 |
def hsv_shift_image_precalc(image, precalc, image_info=None):
"""
----------
Author: Damon Gwinn (gwinndr)
----------
- Computes an hsv shifted image based on precalculated values
- dhue * CV2_HSV_H_MAX is added as a shift to hue
- dsat and dexp are multiplied as a scaling to sat and exp
... | 854f41e6ff1399b89db09c6c6797f61665362b73 | 75,393 |
def predict_churn(query):
"""
This function classifies the array in input
:param query: the logs to classify
:return: the log related to churn
"""
model = get_model()
# use model to predict classification for query
classification_results = model.predict(query)
return classification... | 0d2e981d4b190f53805e116a7c55f01d7139df67 | 75,394 |
def p2class(fg, bg, pval):
"""Assign a table cell (td) CSS class given a p-value.
Heat map:
higher p-values -> more blue
p-values near significance -> white
smaller p-values -> more red
Foreground deletions -> gray, inserts -> gold.
"""
if fg == '-':
return 'del'
... | ceefc78ed4052782c95421ab267697843fd9abb7 | 75,396 |
def epokaerecom_story(soup):
"""
Function to pull the information we want from Epokaere.com stories
:param soup: BeautifulSoup object, ready to parse
"""
hold_dict = {}
#text
try:
article_body = soup.find('article', attrs={"class": "article"})
maintext = [para.text.strip() fo... | 1609972612321847c8f8bf350f1cf977c44a9ee1 | 75,397 |
import re
def setup(runner: Runner, args):
"""
Determine how the user wants to set up the proxy in the cluster.
"""
# OpenShift doesn't support running as root:
if (
args.expose.has_privileged_ports()
and runner.kubectl.cluster_is_openshift
):
raise runner.fail("OpenSh... | 164fb7406712440cb0704d35002279468be6f904 | 75,399 |
def get_array(namefile):
""" Return an array from file with index + vector in each line"""
list_vect = []
first = True
len_sup = 0
with open(namefile, 'r') as f:
for line in f:
vec = []
new_line = line.replace('\n', '')
new_line = new_line.split(',')
... | 9e5fb9a27eb3009bf74083c605a341d2cab70159 | 75,401 |
def toy_reward(config):
""" The reward function to maximize (ie. returns performance from a fake training trial).
Args:
config: dict() object defined in unit-test, not ConfigSpace object.
"""
reward = 10*config['b'] + config['c']
reward *= 30**config['a']
if config['d'] == '... | cc8ae7dfc31c8867fd1fb14720521d0b52e11074 | 75,402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.