content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fbx_mat_properties_from_texture(tex):
"""
Returns a set of FBX metarial properties that are affected by the given texture.
Quite obviously, this is a fuzzy and far-from-perfect mapping! Amounts of influence are completely lost, e.g.
Note tex is actually expected to be a texture slot.
"""
# M... | 363c9f60084a55aa8d9c01c2f06d4d30d5e45993 | 29,590 |
def get_from_STEAD(key=None,
h5file_path='/mnt/GPT_disk/DL_datasets/STEAD/waveforms.hdf5'):
"""
Input:
key, h5file_path
Output:
data, p_t, s_t
"""
HDF5 = h5py.File(h5file_path, 'r')
if key.split('_')[-1] == 'EV':
dataset = HDF5.get('earthquake/... | 9bab2db49eab81abe72cb27e86d3cdf787c4e902 | 29,591 |
import traceback
def _safeFormat(formatter, o):
"""
Helper function for L{safe_repr} and L{safe_str}.
"""
try:
return formatter(o)
except:
io = NativeStringIO()
traceback.print_exc(file=io)
className = _determineClassName(o)
tbValue = io.getvalue()
r... | 610e8063fa91d211e749be829c2d562fa1b86ea6 | 29,592 |
from datetime import datetime
import pytz
def now_func():
"""Return current datetime
"""
func = get_now_func()
dt = func()
if isinstance(dt, datetime.datetime):
if dt.tzinfo is None:
return dt.replace(tzinfo=pytz.utc)
return dt | c715be9fde2d245c79536d792b775678bc743aaa | 29,594 |
import itertools
def flatten_search_result(search_result):
"""
Converts all nested objects from the provided search result into non-nested `field->field-value` dicts.
Raw values (such as memory size, timestamps and durations) are transformed into easy-to-read values.
:param search_result: result to ... | 380b244bcee0d968532db512b6bf79cc062ef962 | 29,595 |
def xroot(x, mu):
"""The equation of which we must find the root."""
return -x + (mu * (-1 + mu + x))/abs(-1 + mu + x)**3 - ((-1 + mu)*(mu + x))/abs(mu + x)**3 | 5db07cc197f1bc4818c4591597099cd697576df2 | 29,597 |
import random
def spliter(data_dict, ratio=[6, 1, 1], shuffle=True):
"""split dict dataset into train, valid and tests set
Args:
data_dict (dict): dataset in dict
ratio (list): list of ratio for train, valid and tests split
shuffle (bool): shuffle or not
"""
if len(ratio)... | 793af274e3962d686f2ef56b34ae5bc0a53aac5b | 29,598 |
import scipy
def smooth(x, window_len=None, window='flat', method='zeros'):
"""Smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
:param x: the input signal (numpy array)
:param window_len: the dimension of the smoothing wi... | 148c1f4b420ce825d3b658e90329dac7b9360c2c | 29,599 |
from typing import Callable
from typing import List
from typing import Iterable
def copy_signatures(
target_function: Callable,
template_functions: List[TemplateFunction],
exclude_args: Iterable[str] = None,
) -> Callable:
"""A decorator that copies function signatures from one or more template functi... | 39f6054002b01433e84a0722c2851fff999eb6cf | 29,600 |
def landing():
"""
displays the landing page.
"""
return render_template('landing.html') | b7ea7741f84bbbd2e35522547d24cf7740359b11 | 29,601 |
def dict2pdb(d):
"""Transform an atom dictionary into a valid PDB line."""
(x, y, z) = d['coords']
args = (d['at_type'], d['ser_num'], d['at_name'], d['alt_loc'],
d['res_name'][-3:], d['chain_id'], d['res_id'], d['res_ic'],
x , y , z , d['occupancy'], d['bfactor'], d['seg_id'], d['el... | 0cbcee043f0663bbb4f88b5070760fa079cd6111 | 29,603 |
def spark_collect():
"""Spark's collect
:input RDD data: The RDD to collect.
:output list result: The collected list.
"""
def inner(data: pyspark.rdd.RDD) -> ReturnType[list]:
o = data.collect()
return ReturnEntry(result=o)
return inner | 99554cba28df7175b7b6e688d526f8b26767b909 | 29,604 |
import torch
def freeze_layers(
model: torch.nn.Sequential,
n_layers_to_train: int
) -> torch.nn.Sequential:
"""
Function to freeze given number of layers for selected model
:param model: Instance of Pytorch model
:param n_layers_to_train: number of layers to train, counting from the l... | bfeca127c684de0815493ef621dce790b3a090f3 | 29,605 |
from io import StringIO
import csv
def test_derive_files_CyTOF_analysis():
"""Check that CyTOF analysis CSV is derived as expected."""
ct = load_ct_example("CT_cytof_with_analysis")
artifact_format_specific_data = {
"cell_counts_assignment": {"B Cell (CD27-)": 272727, "B Cell (Memory)": 11111},
... | 22cfa9b7c96d35b6be4e2f2bc5bc9eb0e4a536ca | 29,607 |
def get_headers(wsgi_env):
"""
Extracts HTTP_* variables from a WSGI environment as
title-cased header names.
"""
return {
key[5:].replace('_', '-').title(): value
for key, value in wsgi_env.iteritems() if key.startswith('HTTP_')} | 01e7140a670957c691fec01dd90d53bdc29425bd | 29,608 |
def get_chats_between_users(user1, user2):
"""
Returns all chat objects between 2 users sorted by date posted.
Note: It does not check if they are a connection
"""
return Chat.objects.filter(Q(sender = user1, receiver = user2) | Q(sender = user2, receiver = user1)).order_by('-date_posted') | 1f9aba3f10e59776fb3e2eaa1bfcdf55eccf5fd6 | 29,609 |
def merge(source, destination):
"""
Deep-Merge two dictionaries.
Taken from http://stackoverflow.com/a/20666342/1928484.
>>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
>>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
>>> merge(b, a) == { 'fir... | 43524fcba1bd073311cad9128daac9c31cf84b6c | 29,610 |
def SequenceToConjunction(node):
"""Transform all SEQUENCE nodes into CONJUNCTION nodes.
Sequences have the same semantic meaning as conjunctions, so we transform them
to conjunctions to make query matching code simpler.
Arguments:
node: Root of the tree to transform.
Returns:
A tree with all SEQUE... | bb7bf69ed8c6329f4aa0eafef67a0925a4818a3d | 29,611 |
import json
def email_addresses_view_all(self) -> dict:
"""
Retrieve all existing EmailAddresses.
:param self:
:return
{
"ResponseType":"EmailAddresses",
"Version":"1.0",
"EmailAddresses":
[
{
"Version":"1.0",... | c30fdc8bec641adc723ca924db364c172088bbd8 | 29,612 |
def adjusted_r2_score(ctx, pipeline, initial_metrics, num_rows):
"""Calculates the Adjusted R2 Score.
See: https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2
Parameters:
ctx (RecordingContext): The current context.
pipeline (Pipeline): The pipeline being evaluated.
... | 406b7e0fa4a55bac08e0e7e53000622828013baf | 29,613 |
import torch
def bilinear_sampling(img, dp):
"""
warp rgbd images using projected depth * pixel and bilinear sampling
"""
b, hw, _ = dp.shape
_, _, h, w = img.shape
dp = dp.reshape(-1, 3) # reshape dp to (b*h*w, 3)
# homogeneous coord (wx, wy, w) -> real coord (x, y, 1)
# restrict dep... | 529f24e80ca2bf785efc95db4d20cbbc13d66e2f | 29,614 |
def mname(obj):
""" Get the full dotted name of the test method """
mod_name = obj.__class__.__module__.replace('h5py.tests.','')
return "%s.%s.%s" % (mod_name, obj.__class__.__name__, obj._testMethodName) | 85a4a4f1aec25d57212f31968d5a42f8dc8d39e0 | 29,615 |
def sharpe(simple_returns, riskfree_rate, period=period.MONTHLY):
"""Compute the sharpe ratio of series of returns. Commonly used to measure the performance
of an investment compared to a risk-free asset, after adjusting for its risk.
Return the difference between the returns of the investment and the risk... | abd50018545f8ba2bc34e7d45cfefd2727594c66 | 29,616 |
def get_all_listing_types():
"""
Get all listing types
"""
return models.ListingType.objects.all() | cfed714fd52f64680f9eaffdd9068318dfcb1cfe | 29,617 |
import torch
import logging
def load_model(config_path, model_path):
""" Not knowing exactly what model we may have saved, try to load both types. """
def load_gpt():
try:
mconf = GPTConfig.from_json(config_path)
model = GPT(mconf)
model.load_state_dict(torch.load(... | 0ae334fd6b4e851424b90335d4369cfb1ee4acc5 | 29,618 |
from unittest.mock import Mock
def protocol(monkeypatch):
"""Rflinkprotocol instance with mocked handle_packet."""
monkeypatch.setattr(PacketHandling, "handle_packet", Mock())
return PacketHandling(None) | d4808028847a2e52e26eace8ae45ceb366690579 | 29,619 |
from typing import Dict
from typing import Any
def new_from_at_rest(ethereum_network_at_rest: Dict[str, Any]) -> "EthereumNetwork":
"""Instantiate a new EthereumNetwork model from storage
Args:
ethereum_network_at_rest: The dto of the at-rest network from storage
Returns:
Instantiated Ethe... | 03626be090ad5582329e61b6d0d1c4fa000316e6 | 29,620 |
def get_auth_twitter_consumer(hashed_twitter_id: str) -> tweepy.OAuthHandler:
"""auth twitter with saved tokens.
Args:
hashed_twitter_id(str):
Returns:
tweepy.OAuthHandler:
"""
user = user_db_session.query(User.token, User.token_secret).filter(User.hashed_user_id == hashed_twitter_id... | 3720153629181920b0a7152c5801d5f9fee38023 | 29,621 |
def retrieve_object_coordinates_from_db(
con,
object_ids,
key_object,
verbose=False):
"""
object_ids is a pd.DataFrame with rows representing objects and columns
Plate_Name
Image_Metadata_WellID
Image_Metadata_FieldID
<key_object>_Number_Object_Num... | bc9996de17197223ca828821f8a89b6881ff934e | 29,622 |
def zip(fn):
"""
Higher-order tensor zip function.
fn_zip = zip(fn)
c = fn_zip(a, b)
Args:
fn: function from two floats-to-float to apply
a (:class:`Tensor`): tensor to zip over
b (:class:`Tensor`): tensor to zip over
Returns:
:class:`Tensor` : new tensor d... | 7e6d990352edac102423c364b2745f4009a0ce44 | 29,623 |
import re
def config_file_has_self_install_dirs(config_file):
"""Config file has self install dirs"""
has_self_install_dirs = False
with open(config_file) as _f:
for line in _f:
if re.search(r'^hard_drive_\d+_label\s*=\s*(amigaosdir|kickstartdir|userpackagesdir)', line, re.I) or \
... | 5e095570ea20156cc3d38cf7379f199b5b8af5bc | 29,624 |
def implied_volatility(price, F, K, r, t, flag):
"""Returns the Black delta of an option.
:param price:
:type price: float
:param F: underlying futures price
:type F: float
:param K: strike price
:type K: float
:param r: annual risk-free interest rate
:type r: float
:param t: ti... | 24def9d6b21518574d4aba0e72bde7bf2a723252 | 29,625 |
def cc_audio_offset(audio_file_1, audio_file_2):
"""
Get the audio offset between two WAV files, uses cross correlation
Code influenced by https://github.com/rpuntaie/syncstart/blob/main/syncstart.py
:param audio_file_1:
:param audio_file_2:
:return:
"""
sample_rate_1, audio_1 = wavfi... | 8983d5299cf2b67efa0e6c6dbd37bbdcd872ca09 | 29,627 |
def add_monoatomic(mof,ads_species,ads_pos):
"""
Add adsorbate to the ASE atoms object
Args:
mof (ASE Atoms object): starting ASE Atoms object of structure
ads_species (string): adsorbate species
ads_pos (numpy array): 1D numpy array for the proposed
adsorption position
Returns:
mof (ASE Atoms object... | 963432ab247ae6b729e60627bad583d1939c483b | 29,628 |
def df_aidxf_ctl():
"""Example df_aidxf of a molecule with a fragment combination of type connection tripodal linker."""
mol = Chem.MolFromSmiles('C1CC2CC1CCCCC1CCNC3CCCCCCC4CC2CC4CCCC13')
return pd.DataFrame([
['mol_ctl', 'XXX', 'QA', 0, [9, 10, 11, 12, 13, 28], 56.0, mol, Chem.Mol... | 66eef548be3e8d61749a61996afb83af2e0ff055 | 29,630 |
def make_dunder_main(manifest):
"""Generate a __main__.py file for the given manifest."""
prelude = manifest.get("prelude_points", [])
main = manifest.get("entry_point")
scripts = prelude + [main]
return MAIN_TEMPLATE.format(**locals()) | 7504eb97c8b83d2a377bd7e00d06b294eed824c6 | 29,631 |
def prefix_exists(bucket, key):
"""ensure_object_exists
:param bucket:
:param key:
"""
objects = S3_CLIENT.list_objects(Bucket=bucket, Prefix=key)
contents = objects.get('Contents')
if contents:
return len(contents) > 0
return False | 7575449b319b21c69df0e9d1f3a3a88d8404a145 | 29,632 |
def mae(y, y_pred):
"""mean absolute error for two ranks(encoded as strings)"""
errors = [abs(i - find_position(y, c))
for i,c in enumerate(y_pred) ]
return np.mean(errors) | 23fa9a51dd80c15c723ac2ad2487ec0f2a1119c6 | 29,633 |
def create_update_model_fn():
""" """
def update_model(model):
""" """
utils.apply_mask(model, use_cuda=False)
return model
return update_model | 85bd6cdcf37ab705119959c1f9385b992f7b2702 | 29,635 |
def index_select_batch(data, indices):
"""Gather `indices` as batch indices from `data`, which can either be typical nd array or a
list of nd array"""
assert isinstance(indices, (tuple, list)) or (isndarray(indices) and len(indices.shape) == 1)
if isndarray(data):
return data[indices]
asse... | c66e787fcc599628a71569dce77dcda2c175345f | 29,636 |
import select
import time
def start_process(cmd):
"""
Start BrowserStackLocal foreground process.
Monitor its output to find a specific text that indicates that the process has
successfully established connection to BrowserStack server and ready to serve.
Credits to https://stackoverflow.com/que... | 7b53d4c0beb9c38068f850a783dbd9df3a377df1 | 29,638 |
def tnr_diff(y_true: pd.Series, y_pred: pd.Series, pa_name: str, priv_grp: int = 1):
""" Returns the between-group difference of True Negative Rates
Args:
y_true (pd.Series): true target values
y_pred (pd.Series): predicted target values
prtc_attr (str): name of the protected attribute
... | a7f266e743d59076ea8fda3b039e11dccba0e68a | 29,639 |
def call(value):
"""Call is meant to be used with the Method filter. It attempts to call
the method specified.
Usage:
{% load custom_filters %}
{% if foo|method:"has_access"|call %}
This will invoke foo.has_access()
"""
if not callable(value):
return "[%s is not calla... | 1bb4217b74bf69b55d4c2cae1c29a396e19f5153 | 29,640 |
def permute_by_indices(list_of_things, *list_of_index_transpositions):
"""Given a list_of_things and a list of pairs of transpositions of indices
[(i, j), (k, m), ...], return the list_of_things with the i-th an j-th
values swapped, the k-th- and m-th values swapped, and so on.
Examples
--------
... | 31d7f73028fcb4c3a43750d1ade0c27e1b563dbb | 29,641 |
import re
def _string_to_int(string: str) -> int:
"""
a helper function convert from string to int, like S1 -> 1
Args:
string (str): input string
Returns:
(int): return value if this is a int, return 0 if this is not a int
"""
r = re.findall('\d+', string)
if (len(r) > ... | d4dbea658e6092edb27b85154b319e098c588a76 | 29,642 |
from pathlib import Path
def create_moving_path(**kwargs):
"""
User interface function to create Path object for moving load.
:keyword:
* start_point (`Point`): Start point of path
* end_point (`Point`): End point of path
* increments (`int`): Increment of path steps. Default is 50
* mid... | 05de795c61e7b3fc4c3f4c2aa14505b4a6fcf986 | 29,643 |
def np_ortho(shape, random_state, scale=1.):
"""
Builds a numpy variable filled with orthonormal random values
Parameters
----------
shape, tuple of ints or tuple of tuples
shape of values to initialize
tuple of ints should be single shape
tuple of tuples is primarily for co... | c5369bee504bf367717de41bca24689211bcd866 | 29,644 |
import ast
def _bind_generic_argument_list(field_list):
# type: (syntax.GenericArgumentList) -> ast.GenericArgumentList
"""Bind a generic argument list."""
ast_field_list = _bind_field_list(field_list, ast.GenericArgumentList)
ast_field_list.fields = [_bind_field_list_entry(f) for f in field_list.fiel... | 9958c44b11510f437ddb8b671954d60975edbd14 | 29,645 |
from io import StringIO
import six
from typing import Generator
def message_to_string(msg):
"""
Converts python message to string in a proper way.
"""
with closing(StringIO()) as fp:
if six.PY3:
g = Generator(fp, mangle_from_=False, policy=_compat32_crlf)
g.flatten(msg,... | 9824d18c0435db5659fdf261bce78d7c19a57490 | 29,646 |
def calculate_diag_OR(clusters,clusters_ind,status):
"""Calculate the Odds Ratio for the probability of being diagnosed linked to being in a certain cluster
Parameters: clusters (dict): dictionary with cluster number as key and list of patients in cluster as value
clusters_ind (list): indices of... | 7adf6ccc40b6b45bc5b990498ec35fb8f62b3125 | 29,647 |
def build(obj, parent=None):
"""
Safely builds the object by calling its method 'build' only if 'obj' possesses a 'build' method. Otherwise, will convert it to a string using the 'str' function. If a parent is passed, all packages and preamble lines needed to the object will be added to the packages and preambl... | 9011659825a9b2fce887aa9c74d98d70f4cb7a2f | 29,648 |
def _no_negative_zero(val):
"""Make sure -0 is never output. Makes diff tests easier."""
if val == 0:
return 0
return val | 345802e297cc1e1c77a5b1db664715bfc42f3da6 | 29,649 |
import numpy
def weights(basis, X, deriv=None):
"""
Calculates the interpolant value or derivative weights for points X.
:param basis: interpolation function in each direction, eg,
``['L1', 'L1']`` for bilinear.
:type basis: list of strings
:param X: locations to calculate interpolant... | 17724a48779852dc3794799ebcb8eed9ee288164 | 29,650 |
def svn_stream_readline(*args):
"""
svn_stream_readline(svn_stream_t stream, svn_stringbuf_t stringbuf, char eol,
svn_boolean_t eof, apr_pool_t pool) -> svn_error_t
"""
return apply(_core.svn_stream_readline, args) | 2edb1fca651078336ac31ff7a54f563c5e7f1846 | 29,651 |
from typing import Iterable
from typing import Dict
from typing import Hashable
import json
def stream_json(data: Iterable[Dict[Hashable, any]]) -> StreamingHttpResponse:
"""
Stream all elements in `data` as JSON array using the StreamingHttpResponse class.
Parameters
----------
data: Iterable[Dict[Hashable, an... | ba562d71170724e1994567dd70c407123169d126 | 29,652 |
def data_anscombes_quartet(id):
""" Generate one case for each of the Anscombe's quartet """
if id == 1:
x = [10.0, 8.0, 13.0, 9.0, 11.0, 14.0, 6.0, 4.0, 12.0, 7.0, 5.0]
y = [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]
elif id == 2:
x = [10.0, 8.0, 13.0, 9.0, 1... | cfd1f2ec1fbc2af2c9bc360bcd72f85da271a4a9 | 29,653 |
def rinko_curve_fit_eq(X, a, b, c, d, e, f, g, h):
"""
Same as rinko_oxy_eq, but in a form that is more suitible for scipy's curve fit routine
X contains pressure, temperature, voltage, and OS (the normal arguments for rinko_oxy_eq)
"""
press, temp, oxyvo, os = X
o2_cal = RinkoO2Cal(a, b, c, d,... | e811c68341af549dea5f5ad3342fe0f3593695d9 | 29,654 |
def SearchList(items, message="Select an item:", title='FontParts'):
"""
A dialgo to search a given list.
Optionally a `message`, `title` and `allFonts` can be provided.
::
from fontParts.ui import SearchList
result = SearchList(["a", "b", "c"])
print(result)
"""
retur... | eba3139a78748e929ca6f5487deee0379ba383e8 | 29,658 |
import logging
async def bsi_score_trend(
business_id: int,
time_period: str = Query(
..., enum=DATEFILTER.date_filter),
auth: Depends = Depends(get_current_user),
) -> dict[str, int]:
"""
Shows the media presence of the company on a monthly basis. This is calculated using the ‘Business S... | a9449c02823b3f36f7c6d4503abeb78d60ff20ef | 29,659 |
def create_role(party: Party, role_info: dict) -> PartyRole:
"""Create a new party role and link to party."""
party_role = PartyRole(
role=JSON_ROLE_CONVERTER.get(role_info.get('roleType').lower(), ''),
appointment_date=role_info['appointmentDate'],
cessation_date=role_info['cessationDat... | 8793158c1a7d8ca883da6e12e9b47e57206445f3 | 29,660 |
import struct
from re import M
def murmur2_32(byte_data, seed=DEFAULT_SEED):
"""
Creates a murmur2 32 bit integer hash from the given byte_data and seed.
:param bytes byte_data: the bytes to hash
:param int seed: seed to initialize this with
:return int: 32 bit hash
"""
length = len(byte... | 34962f0949c7718d4c977d9c3e69e3e86ba78eff | 29,661 |
def cell_segmenter(im, thresh='otsu', radius=20.0, image_mode='phase',
area_bounds=(0,1e7), ecc_bounds=(0, 1)):
"""
This function segments a given image via thresholding and returns
a labeled segmentation mask.
Parameters
----------
im : 2d-array
Image to be segmented... | f97650c74dd8c7d32b6e1e6851395c988c6056f0 | 29,662 |
def convert_id_to_location(df, locations_df):
"""Converts c3 `id` to covid forecast hub `location_name`.
c3 uses `id` as the PK while covid forecast hub uses `location_name`
(labeled just `location` there instead of `location_name`) as the PK.
locations_df contains `id` and `location_name` mapping.
... | fe789c292603003eedb971aee094c4c4919fb7fc | 29,663 |
def extract_scoring_history_field(aModel, fieldOfInterest, takeFirst=False):
"""
Given a fieldOfInterest that are found in the model scoring history, this function will extract the list
of field values for you from the model.
:param aModel: H2O model where you want to extract a list of fields from the ... | 158d668830cadb61ee9affb47d601dbf3a43e55d | 29,664 |
def get_num_beats(times, voltages):
""" Calculates the number of beats in the sample.
:param times: List of time data
:param voltages: List of voltage data
:return: Int representing the number of detected beats
"""
return get_beats_times(times, voltages).size | 9bc0a5ea664377c529a9dcecf3f82f72ef6e4fdb | 29,665 |
def find_all_indexes_r(text, pattern, itext=0, ipattern=0, indices=None):
"""Recursive implementation of find_all_indexes. The time complexity should
be equialent to find all indexs not recursive."""
if indices is None:
indices = []
if len(text) == itext + ipattern:
if len(pattern) == ip... | bcd447140c92d8ffbbe0577e469d2e9e4cc9edad | 29,666 |
import functools
def image_scale(pts, scale):
"""scale to original image size"""
def __loop(x, y):
return [x[0] * y, x[1] * y]
return list(map(functools.partial(__loop, y=1/scale), pts)) | 943d4f46fb6cd9e9433a9ad53b9baf60e3646273 | 29,667 |
def current_session_view(request):
""" Current SEssion and Term """
if request.method == 'POST':
form = CurrentSessionForm(request.POST)
if form.is_valid():
session = form.cleaned_data['current_session']
term = form.cleaned_data['current_term']
AcademicSession.objects.filter(name=session).... | 736bdab60ba7f0ef2747ce5203253d8c5dd86738 | 29,670 |
def post_css_transform(doc, url):
"""
User-customizable CSS transform.
Given a CSS document (with URLs already rewritten), returns
modified CSS document.
"""
global config
if config.hack_skin and not config.special_mode:
if config.skin == MONOBOOK_SKIN:
doc = monobook_h... | 73ec165288315ab59cbccf663cd181c836ff8c73 | 29,671 |
import json
async def get_user_ads(context, account, community=None):
"""List all ad posts created by account. If `community` is provided,
it lists all ads submitted to that community and their state."""
db = context['db']
account_id = await get_account_id(db, account)
params = {'account_id':... | 945e8375025ff19d9d48a717739d041c10d975d3 | 29,672 |
def MDP2Trans(MDPs, J, action_in_states = False, combined = True):
"""
Input: a list (len-N) of trajectory [state matrix [T * 3], actions, rewards] - I need to modify evaluate.ipynb
Output: a list of (s,a,s',u) (combined together)
"""
def MDP2Trans_one_traj(i):
obs, actions, utilities = MDPs... | ec7e4eb2a5b399126b88dc1f41cfb318b0f565bf | 29,673 |
def get_pullrequests(creds, repository_owner, repository_name, pullrequest_state_strings, limit):
"""
Return list of pull request information as follows. The list is empty when no pull requests are found.
Or, return None on any errors.
state State of the Pull Request.
number ... | 77ee49a994caa54bba6c480933dfc836859c086d | 29,674 |
def remove_nuisance_word_hits(result_str):
"""
>>> a = '#@@@the@@@# cat #@@@in@@@# #@@@the@@@# hat #@@@is@@@# #@@@so@@@# smart'
>>> remove_nuisance_word_hits(a)
'the cat in the hat is so smart'
"""
ret_val = rcx_remove_nuisance_words.sub("\g<word>", result_str)
return ret_val | 56123d09f08221d8e61d8a0bc9a60d8a493e0d2b | 29,675 |
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = ... | 04963a9059bc2440da630adad12b9c560319f605 | 29,676 |
from typing import List
from typing import Union
from typing import Optional
def regression(
method,
x_train_cols: List[Union[str, int]],
y_train_col: List[Union[str, int]],
x_pred_cols: Optional[List[Union[str, int]]] = None,
input_ts="-",
columns=None,
start_date=None,
end_date=None,... | 980b462c01698892b858720259d037bc039edf18 | 29,677 |
import secrets
def get_password(length: int, exclude_punctuation: bool = False) -> str:
"""
Return password.
:param int length: password length
:param bool exclude_punctuation: generate password without special chars
:return: password
:rtype: str
"""
validate_length(length)
alpha... | 87b172db33d26e96619eb533ededb9e5eec7b84d | 29,679 |
def _read_image(filepath, image_size=None):
"""Read an image and optionally resize it (size must be: height, width)."""
cv2 = tfds.core.lazy_imports.cv2
with tf.io.gfile.GFile(filepath, 'rb') as f:
image = cv2.imdecode(
np.fromstring(f.read(), dtype=np.uint8), flags=cv2.IMREAD_GRAYSCALE)
if image_... | 9d0ee02af36ad452d842a651cccae9f7c30e3d8e | 29,680 |
def get_txt_version():
"""Get version string from version.txt."""
try:
with open("version.txt", "r") as fp:
return fp.read().strip()
except IOError:
return None | 62951a878bfb52ae6b00543e1816b9ff298bb907 | 29,681 |
def clear_outliers(points: np.ndarray, confidence:np.ndarray, iterations=1, to_dump=0.05):
"""
clears outliers based on horizontal distance between point and regression line
:param points: array of points in (x,y) form
:param confidence: confidence of points corresponding to points array
:param iter... | 47a7eddfe16ef072036f20e4c0895dfae5ab61d2 | 29,684 |
def parse(content_type):
"""parse the Content-Type header.
"""
return (
Ok(content_type)
.then(lex)
.then(label)
.then(parse_lexeme)
) | e0d045d660eb1501be1e658696f4798088cdb201 | 29,685 |
def _getter(path):
"""Loads configparser config"""
config = _configparser()
# ok if config file does not exist
config.read(path, encoding=OPEN['encoding'])
# return dict(config.items())
# behaves like dict
return config | 98e233865d001a1ce4aeb7c815be433817b1734f | 29,686 |
def unexpected_exception_handler(request: Request, exc: Exception) -> JSONResponse:
"""Обработчик любых непредвиденных и необработанных ошибок"""
service_code = request.app.service_code
classify_exception_and_send_to_sentry(exc)
error_message = "Возникла непредвиденная ошибка. Пожалуйста, обратитесь к а... | dd3254cd3f5073fe6d7222b6c69787302986fbc2 | 29,687 |
def chebyshev_polynomial(X, k):
# 返回一个稀疏矩阵列表
"""Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices."""
print("Calculating Chebyshev polynomials up to order {}...".format(k))
T_k = list()
T_k.append(sp.eye(X.shape[0]).tocsr()) # T0(X) = I
T_k.append(X) # T1(X) = L~... | 6ced4e56f3351987676161d8265f197025d1bafe | 29,688 |
def PIsCompatable (in1, in2):
"""
Tells if two CArrays have compatable geometry
returns True or False
* in1 = first input Python CArray
* in2 = second input Python CArray
"""
################################################################
# Checks
if not PIsA(in1):
pr... | 5a62a549d5a3a6384fdd4759556ad7d5b9b81f4d | 29,689 |
from .sqs.connection import AsyncSQSConnection
from typing import Any
def connect_sqs(
aws_access_key_id: str | None = None,
aws_secret_access_key: str | None = None,
**kwargs: Any
) -> AsyncSQSConnection:
"""Return async connection to Amazon SQS."""
return AsyncSQSConnection(
aws_access_k... | 35d43e3a5be93846207cea6f410799304bdd8032 | 29,690 |
import json
def load_json_from_string(string):
"""Load schema from JSON string"""
try:
json_data = json.loads(string)
except ValueError as e:
raise ValueError('Given string is not valid JSON: {}'.format(e))
else:
return json_data | 66f96373a8e02bf69289e5e4594ac319906475f5 | 29,691 |
def advance_searches(string, pos=0, has_strikethrough=False, has_math=False):
"""
These tokens are special cases,
because they start and end with the same character
therefore, we need to re-search as we progress, to reset the opening character
"""
code_match = code_pattern.search(string, pos)
... | c276a8a26892d7b59356defa9c2b7da309ee8568 | 29,692 |
from scipy import stats
import numpy as np
def two_sample_ttest(arr1, arr2):
"""Performs independent two-sample t-test between two arrays"""
# Remove nan if any
arr1 = arr1[~np.isnan(arr1)]
arr2 = arr2[~np.isnan(arr2)]
tval, pval = stats.ttest_ind(arr1, arr2, nan_policy='omit')
sig = get_sig... | 6175130dccb5bedcad90c6ac918282043bb47ae1 | 29,693 |
import typing
def parse(instructions: typing.List[str]) -> Wire:
"""Calculate the points upon a wire and create a class from them."""
points = [Point(0, 0)]
for instruction in instructions:
dir = instruction[:1]
dist = int(instruction[1:])
for _ in range(dist):
if dir... | fedd7a49b182e2e9650e512a60ec5d49f71cb03d | 29,694 |
def one_shot_gamma_alpha_matrix(k, t, U):
"""Assume U is a sparse matrix and only tested on one-shot experiment"""
Kc = np.clip(k, 0, 1 - 1e-3)
gamma = -(np.log(1 - Kc) / t)
alpha = U.multiply((gamma / k)[:, None])
return gamma, alpha | c73ba2ae67a80ac1b16d415cea043baccea5bb7c | 29,695 |
import logging
def generate_device_watchdog_answer(diameter_request,
origin_host,
origin_realm):
"""
Method used with the purpose of handling DWR requests
and sending DWA responses.(Device Watchdog)
Builds the DWA message, the he... | 43ef49f5091d994134e2025c013b90bfb121f1ed | 29,696 |
from typing import Optional
from typing import Dict
from typing import Union
from typing import Any
def apply(tree: ProcessTree, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> EventLog:
"""
Generate a log by a playout operation
Parameters
---------------
tree
Process t... | 26e2c4b476bc3d5f5481f5c4bb193897e276facd | 29,697 |
import aiohttp
import urllib
async def parse(url: str, session: ClientSession, **kwargs) -> set:
"""Find HREFs in the HTML of `url`."""
found = set()
try:
html = await fetch_html(url=url, session=session, **kwargs)
except (
aiohttp.ClientError,
aiohttp.http_exceptions.HttpProce... | daef240220bb3a4482b306b4322ff9d08a0b2872 | 29,699 |
import logging
def auth(options) -> bool:
"""Set up auth and nothing else."""
objectStore = FB_ObjectStore(options)
if options.get("test", False):
# If we only care if it's valid, just check and leave
auth_token = objectStore.get_cached_auth_token()
# Validate and return cached aut... | be2acdd2564ee05e746ba99fbb10a50e9dc92eb1 | 29,700 |
def _parse_detector(detector):
"""
Check and fix detector name strings.
Parameters
----------
detector : `str`
The detector name to check.
"""
oklist = ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9',
'n10', 'n11']
altlist = [str(i) for i in range(12)]
... | f78d7eb5004b3cb6d3276b0c701263c71668e36e | 29,701 |
def mobius_area_correction_spherical(tria, mapping):
"""
Find an optimal Mobius transformation for reducing the area distortion of a spherical conformal parameterization
using the method in [1].
Input:
tria : TriaMesh (vertices, triangle) of genus-0 closed triangle mesh
mapping: nv x 3 vertex c... | 08d58e2e2ff13533ac733ef49a4f57d4e1d6f41d | 29,702 |
def rel_ordered(x1,x2,x3,x4):
"""
given 4 collinear points, return true if the direction
from x1->x2 is the same as x3=>x4
requires x1!=x2, and x3!=x4
"""
if x1[0]!=x2[0]:
i=0 # choose a coordinate which is varying
else:
i=1
assert x1[i]!=x2[i]
assert x3[i]!=x4[i]
... | 2649250e2ea2619c7f6c21b8dd2cebaeec10647b | 29,703 |
def min_rl(din):
"""
A MIN function should "go high" when any of its
inputs arrives. Thus, OR gates are all that is
needed for its implementation.
Input: a list of 1-bit WireVectors
Output: a 1-bit WireVector
"""
if len(din) == 1:
dout = din[0]
... | 06f0bbce664367307669ddb28c60c65b79de91d3 | 29,704 |
def fetch(u, data, indices, indptr, lmbda):
"""
"""
is_skip = 1
if lmbda > 0:
u0, u1 = indptr[u], indptr[u + 1]
val, ind = data[u0:u1], indices[u0:u1]
if u1 > u0:
is_skip = 0
else:
val = np.empty(0, dtype=data.dtype)
ind = np.empty(0, dtype=np.int3... | cd1d9ffe7ead7711b5e6cd1f2601c1456ce1baaa | 29,705 |
def pgrrec(CONST_STRING, lon, lat, alt, re, f):
"""pgrrec(ConstSpiceChar * CONST_STRING, SpiceDouble lon, SpiceDouble lat, SpiceDouble alt, SpiceDouble re, SpiceDouble f)"""
return _cspyce0.pgrrec(CONST_STRING, lon, lat, alt, re, f) | a1a9889e8c9e2d4b34e480688aeb8a26cb7699b7 | 29,707 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.