content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def avg_pds_from_events(
times,
gti,
segment_size,
dt,
norm="frac",
use_common_mean=True,
silent=False,
fluxes=None,
errors=None,
):
"""Calculate the average periodogram from a list of event times or a light curve.
If the input is a light curve, the time array needs to be un... | 904f43b36380e07e115d23c6677b61bca155d898 | 5,400 |
import random
def check_random_state(seed):
"""
Turn seed into a random.Random instance
If seed is None, return the Random singleton used by random.
If seed is an int, return a new Random instance seeded with seed.
If seed is already a Random instance, return it.
Otherwise raise ValueError.
... | 347481de01f4a3bba59bc9a2c484c10d4857e1e2 | 5,401 |
def chunk(seq, size, groupByList=True):
"""Returns list of lists/tuples broken up by size input"""
func = tuple
if groupByList:
func = list
return [func(seq[i:i + size]) for i in range(0, len(seq), size)] | e7cece99822a01476b46351cebc1345793485cbd | 5,402 |
def registerNamespace(namespace, prefix):
"""
Register a namespace in libxmp.exempi
@namespace : the namespace to register
@prefix : the prefix to use with this namespace
"""
try:
registered_prefix = libxmp.exempi.namespace_prefix(namespace)
# The namespace already exists, return actual prefix.
return r... | 6e7dbed515651f252222a283dc1cda08941fa4c5 | 5,403 |
def definition():
"""
Lists the parent-child relationships through the curriculum structure.
"""
sql = """
--Course to session
SELECT c.course_id as parent_id,
CASE WHEN cc.course_id IS NULL THEN 0 ELSE 1 END as linked,
cs.course_session_id as child_id, 'course' as parent,
cs.description + ' ' + ... | e8dc6a720dcd5f62854ce95e708a88b43859e2cc | 5,404 |
def create_user(strategy, details, backend, user=None, *args, **kwargs):
"""Aggressively attempt to register and sign in new user"""
if user:
return None
request = strategy.request
settings = request.settings
email = details.get("email")
username = kwargs.get("clean_username")
if ... | afdff23d6ca578ef652872ba11bcfe57264b0a9b | 5,405 |
def prendreTresorPlateau(plateau,lig,col,numTresor):
"""
prend le tresor numTresor qui se trouve sur la carte en lin,col du plateau
retourne True si l'opération s'est bien passée (le trésor était vraiment sur
la carte
paramètres: plateau: le plateau considéré
lig: la ligne où se trou... | 5fa94fb875e34068f4e391c66952fe4cc4248ddf | 5,406 |
import os
import logging
import yaml
def load_styles(style_yaml) -> dict:
""" Load point style dictionary """
default_style = {"icon_image": DEFAULT_ICON_IMAGE,
"icon_color": DEFAULT_ICON_COLOR,
"icon_scale": DEFAULT_ICON_SCALE,
"text_scale": DEFAUL... | 940a540c5ee7bad266d5a51bfafee2a9d2197128 | 5,407 |
import os
def everything_deployed(project, chain, web3, accounts, deploy_address) -> dict:
"""Deploy our token plan."""
yaml_filename = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..","crowdsales", "allocated-token-sale-acceptance-test.yml"))
deployment_name = "testrpc"
chain_... | f486f63838cef1d4da6f5dfdacad28a1a0f560fe | 5,408 |
def task_get_all(context, filters=None, marker=None, limit=None,
sort_key='created_at', sort_dir='desc', admin_as_user=False):
"""
Get all tasks that match zero or more filters.
:param filters: dict of filter keys and values.
:param marker: task id after which to start page
:param ... | 4d03e8f7ae15411c2cb597aeb06e25cd40c4f033 | 5,409 |
def updateAppMonConf(AppID, requestModel):
"""Update an Application Monitoring Configuration for a given application
Args:
AppID (str): This is the application ID of the Web App you are interested in.
requestModel: This is the data you wish to update and you need to put it in this
f... | 0b61eae04b79702b2722d0c0bc5dafe48dcdf21f | 5,410 |
def plot_morphology(morphology,
order=MORPHOLOGY_ORDER,
colors=MORPHOLOGY_COLORS,
metastases=None,
metastasis_color=METASTASIS_COLOR,
ax=None,
bg_color='#f6f6f6',
**kwargs):
""... | 62048ced8ede14e9aa505c6e45dd5b196d12297d | 5,411 |
import os
def scores_summary(CurDataDir, steps = 300, population_size = 40, regenerate=False):
"""Obsolete for the one above! better and more automatic"""
ScoreEvolveTable = np.full((steps, population_size,), np.NAN)
ImagefnTable = [[""] * population_size for i in range(steps)]
fncatalog = os.listdir(... | a0e31a9647dee013aa5d042cc41f3793a097e1c2 | 5,412 |
import requests
def post(name,url,message,params=None):
"""Wrap a post in some basic error reporting"""
start = dt.now()
s = requests.session()
if params is None:
response = s.post(url,json=message)
else:
response = s.post(url,json=message,params=params)
end = dt.now()
if n... | 9180424171cdf4cb7bf16a938d7207a99af0987f | 5,413 |
def get_lin_reg_results(est, true, zero_tol=0):
"""
Parameters
----------
est: an Estimator
A covariance estimator.
true: array-like, shape (n_features, n_features)
zero_tol: float
Output
------
out: dict with keys 'utri' and 'graph'
"""
est_coef = get_coef(est)[... | 0f963c135d0bd74a70714ef47ed6f2b0191df846 | 5,414 |
import requests
import logging
def download_file(requested_url: str) -> str:
"""Download a file from github repository"""
url = f"https://github.com/{requested_url.replace('blob', 'raw')}"
resp = requests.get(url)
logging.info(F"Requested URL: {requested_url}")
if resp.status_code != 200:
... | f96d68843f6291aa3497a6e7a5b1e30e2ea4005e | 5,415 |
import warnings
def readBody(response):
"""
Get the body of an L{IResponse} and return it as a byte string.
This is a helper function for clients that don't want to incrementally
receive the body of an HTTP response.
@param response: The HTTP response for which the body will be read.
@type r... | bbc693fca1536a3699b0e088941d9577de94d8dd | 5,416 |
def is_valid_mac(address):
"""Verify the format of a MAC address."""
class mac_dialect(netaddr.mac_eui48):
word_fmt = '%.02x'
word_sep = ':'
try:
na = netaddr.EUI(address, dialect=mac_dialect)
except Exception:
return False
return str(na) == address.lower() | f8bb59a986773307f803dd52154ec03eaddb8597 | 5,417 |
def build_state_abstraction(similar_states, mdp, tol=0.1):
"""
"""
bools = similar_states + np.eye(similar_states.shape[0]) < tol # approximate abstraction
if bools.sum() == 0:
raise ValueError('No abstraction')
mapping, parts = partitions(bools)
idx = list(set(np.array([p[0] for p i... | d4d9354507172ee92ea11c915de0376f0c873878 | 5,418 |
def diagram(source, rstrip=True):
"""High level API to generate ASCII diagram.
This function is equivalent to:
.. code-block:: python
Diagram(source).renders()
:param source: The ADia source code.
:type source: str or file-like
:param rstrip: If ``True``, the trailing wihtespaces at t... | 2a386b49052a7f4dd31eb4f40dec15d774d86b94 | 5,419 |
def eng_to_kong(eng_word: str)-> list[str]:
"""
Translate given English word into Korean into matching pronounciation,
matching the English Loanword Orthography.
For example, "hello" will be translated into 헐로.
# Panics
When given a english word that it cannot translate, `eng_to_kong` will rai... | 0b0d55fdacdea1493d73de85c21dc9c086352b99 | 5,420 |
import logging
import os
def visualize_demux(base_dir, data_artifact):
"""
:param base_dir: Main working directory filepath
:param data_artifact: QIIME2 data artifact object
:return: QIIME2 demux visualization object
"""
logging.info('Visualizing demux...')
# Path setup
export_path = ... | 80d4e4d1eba50bdae09838e625628d9d860341f9 | 5,421 |
def socfaker_dns_answers():
"""
A list of DNS answers during a DNS request
Returns:
list: A random list (count) of random DNS answers during a DNS request
"""
if validate_request(request):
return jsonify(str(socfaker.dns.answers)) | c1f641e1a0e977363067937487a6455800e6a25c | 5,422 |
import os
def create_app():
"""Create and configure and instance of the
Flask Application"""
app = Flask(__name__)
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('HEROKU_POSTGRESQL_COPPER_URL')
app.config['SQLALCHEMY_TR... | a5a2a0022d3f204410db3669910e48e1cd518457 | 5,423 |
def bilin(x, y, data, datax, datay): # --DC
""" x, y ARE COORDS OF INTEREST
data IS 2x2 ARRAY CONTAINING NEARBY DATA
datax, datay CONTAINS x & y COORDS OF NEARBY DATA"""
lavg = ( (y - datay[0]) * data[1,0] + (datay[1] - y) * data[0,0] ) / (datay[1] - datay[0])
ravg = ( (y - datay[0]) * data[1,1] + ... | 59a740f65c7187a08cdc09cef8aa100b01c652cf | 5,424 |
import array
def slice_data(xdata, ydata, x_range):
"""
crops or slices the data in xdata,ydata in the range x_range on the x axis
"""
data = zip(xdata, ydata)
sliced_data = [d for d in data if d[0] >= x_range[0] and d[0] <= x_range[1]]
return array(zip(*sliced_data)) | faf90781e2f073e74a7b11cd80d7c127c0db1bb3 | 5,425 |
def best_low_rank(A, rank):
"""
Finding the best low rank approximation by SVD
"""
u, s, vh = np.linalg.svd(A)
s = np.sqrt(s[:rank])
return u[:, range(rank)] @ np.diag(s), np.diag(s) @ vh[range(rank)] | 5df8197fc0113bfa74a36803445a6a300766880f | 5,426 |
def get_bangumi(uid: int, type_: str = "bangumi", limit: int = 114514, callback=None, verify: utils.Verify = None):
"""
自动循环获取追番/追剧列表
:param callback: 回调函数
:param uid:
:param type_:
:param limit:
:param verify:
:return:
"""
if verify is None:
verify = utils.Verify()
... | b5a2a553a3bf13ded7eb30c53ce536b4a2b9e043 | 5,427 |
def local_cases_range(start_date='2020-06-01',end_date='2020-07-01',areaname='Hartlepool'):
"""calculate new cases in a time range"""
try:
q=DailyCases.objects.filter(areaname=areaname,specimenDate=start_date)[0]
start_total=q.totalLabConfirmedCases
q=DailyCases.objects.filter(areaname=areaname,specimenDate=e... | 747f03f2ef9925f7dc252798bb7f3844cd31d2c0 | 5,428 |
def ecal_phisym_flattables(process, produce_by_run : bool=False):
"""
Add the NanoAOD flat table producers.
This functions adjust also the output columns.
Should be called once nMisCalib has been set in the EcalPhiSymRecHitProducer
"""
process.load('Calibration.EcalCalibAlgos.EcalPhiSymFlatTabl... | f6f48ab2e5b1df6a3e58c5e3130be56861eb1384 | 5,429 |
def nx_add_prefix(graph, prefix):
"""
Rename graph to obtain disjoint node labels
"""
assert isinstance(graph, nx.DiGraph)
if prefix is None:
return graph
def label(x):
if isinstance(x, str):
name = prefix + x
else:
name = prefix + repr(x)
... | c8f05052c613adc17423637186867b70db31e70d | 5,430 |
def infected_asymptomatic_20x80():
"""
Real Name: b'Infected asymptomatic 20x80'
Original Eqn: b'Infected asymptomatic 20+Infected asymptomatic 80'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
return infected_asymptomatic_20() + infected_asymptomatic_80() | fd9cba446672bf8ebcc5fe2fc7f2f961129bdb71 | 5,431 |
import json
import os
def make_forecast_json(data: str):
"""Generate custom forecast file in JSON format
:param data: JSON string containing weather.gov data
"""
try:
if data:
# Current conditions
conditions_now: str = data["properties"]["periods"][0]
# D... | 9b65f30c3b26db8ffa1818db073723eef57fe7f0 | 5,432 |
def biosample_table_data():
"""Return a dictionary containing the expected values of the BioSample Table"""
columns = [
"id",
"BioSample_id",
"BioSampleAccession",
"BioSampleAccessionSecondary",
"BioSampleBioProjectAccession",
"BioSampleSRAAccession",
"Bi... | 65e5d5bb5416a8f113100562fba8f2e6fd66796a | 5,433 |
def grid_adapter3D(
out_dim=(100.0, 100.0),
in_dim=(50.0, 50.0),
z_dim=-10.0,
out_res=(10.0, 10.0, 10.0),
in_res=(5.0, 5.0, 5.0),
out_pos=(0.0, 0.0),
in_pos=(25.0, 25.0),
z_pos=0.0,
in_mat=0,
out_mat=0,
fill=False,
):
"""
Generate a grid adapter.
3D adapter from ... | 9c14a4f9b27ec14cdc550f81fd861207a5674616 | 5,434 |
from typing import Sequence
from typing import Tuple
from typing import Mapping
from typing import Any
from functools import reduce
from typing import cast
def concat_dtypes(ds: Sequence[np.dtype]) -> np.dtype:
"""Concat structured datatypes."""
def _concat(
acc: Tuple[Mapping[Any, Any], int], a: ... | bef7d8ebe30f41297adbf8f1d8de9b93f646c8f4 | 5,435 |
def mutation(param_space, config, mutation_rate, list=False):
"""
Mutates given configuration.
:param param_space: space.Space(), will give us information about parameters
:param configs: list of configurations.
:param mutation_rate: integer for how many parameters to mutate
:param list: boolean... | 38427cfee226589d72117f102d2befdbe8ebbcc0 | 5,436 |
from typing import Union
from typing import Callable
from typing import Optional
from typing import Tuple
def uncertainty_batch_sampling(classifier: Union[BaseLearner, BaseCommittee],
X: Union[np.ndarray, sp.csr_matrix],
n_instances: int = 20,
... | eb95ad79f4326d89c94a42aa727e2e3c338e021e | 5,437 |
import re
def only_digits(raw, force_int=False):
"""Strips all not digit characters from string.
Args:
raw (str or unicode): source string.
Kwargs:
force_int (boolean): not to seek for dot, seek only for int value.
Returns:
int or float: in dependence of "raw" argument conte... | 413763588b067f335f7401fb914f1d6f3f8972fa | 5,438 |
def namedtuple(typename, field_names, verbose=False):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', 'x y')
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args o... | ce2e4b2f6fe0243a8ac5c418d10c6352c95ea302 | 5,439 |
from typing import Optional
from typing import Sequence
def get_users(compartment_id: Optional[str] = None,
external_identifier: Optional[str] = None,
filters: Optional[Sequence[pulumi.InputType['GetUsersFilterArgs']]] = None,
identity_provider_id: Optional[str] = None,
... | 4d404eb1069c829bb757f3870efc548583998434 | 5,440 |
def se_resnet20(num_classes: int = 10,
in_channels: int = 3
) -> ResNet:
""" SEResNet by Hu+18
"""
return resnet(num_classes, 20, in_channels, block=partial(SEBasicBlock, reduction=16)) | da1d1327d5e5d1b55d3b4cc9d42dbf381ece029f | 5,441 |
def parallel_threaded(function):
"""
A decorator for running a function within a parallel thread
"""
def decorator(*args, **kwargs):
t = ParallelThread(target=function,
args=args, kwargs=kwargs)
t.daemon = True
t.start()
return t
return decorator | 9f4936b0ab7de3d550b404043d6b0e37dbb3a066 | 5,442 |
def Upsample(x, size):
"""
Wrapper Around the Upsample Call
"""
return nn.functional.interpolate(x, size=size, mode="bilinear", align_corners=True) | dfaabb3999047589b2d755a2cc631b1389d172b1 | 5,443 |
def get_user_playlists(spotipy_obj, username):
"""Gets and returns all Spotify playlists owned by the username specified.
Parameters:
spotipy_obj: Spotipy object
username: Spotify username
Returns:
List of dictionaries, each dictionary a Spotify playlist object.
"""
# Gra... | 90c06e0ddd91a7a84f4d905dd9334f9b4c27f890 | 5,444 |
import zipfile
from . import mocap
import os
def osu_run1(data_set="osu_run1", sample_every=4):
"""Ohio State University's Run1 motion capture data set."""
path = os.path.join(access.DATAPATH, data_set)
if not access.data_available(data_set):
access.download_data(data_set)
zip = zipfile.Z... | db4687276c69c9bfdcbc30e7c6f46a26fa0f4c19 | 5,445 |
import os
def package_data(pkg, root_list):
"""
Generic function to find package_data for `pkg` under `root`.
"""
data = []
for root in root_list:
for dirname, _, files in os.walk(os.path.join(pkg, root)):
for fname in files:
data.append(os.path.relpath(os.path.... | 6ffe84ef045e460a7bc2613e14e1670a9f6a48e2 | 5,446 |
def create(dataset, target, features=None, l2_penalty=1e-2, l1_penalty=0.0,
solver='auto', feature_rescaling=True,
convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'],
step_size = _DEFAULT_SOLVER_OPTIONS['step_size'],
lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'... | 3988ac27163873a8feff9fd34a5e8fe87e923487 | 5,447 |
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
args = list()
for arg in name_or_flags:
args.append(arg)
return args, kwargs | 0cae66e8b23211affc97fd8857f17b48a73cf286 | 5,448 |
def get_logger():
"""
Provides the stem logger.
:returns: **logging.Logger** for stem
"""
return LOGGER | 8189cae16a244f0237f641e613783a484be5cf38 | 5,449 |
def get_graphql_type_for_model(model):
"""
Return the GraphQL type class for the given model.
"""
app_name, model_name = model._meta.label.split('.')
# Object types for Django's auth models are in the users app
if app_name == 'auth':
app_name = 'users'
class_name = f'{app_name}.graph... | d9f2b4093c290260db864cedd6b06958651bf713 | 5,450 |
from pathlib import Path
def load_image_files(container_path, dimension=(64, 64)):
"""
Load image files with categories as subfolder names
which performs like scikit-learn sample dataset
"""
image_dir = Path(container_path)
folders = [directory for directory in image_dir.iterdir() if dir... | 1c92309c7f8f0b99db841fed21901d37e143f41c | 5,451 |
from datetime import datetime
import calendar
def create_calendar(year=None, month=None):
"""
Create an inline keyboard with the provided year and month
:param int year: Year to use in the calendar,
if None the current year is used.
:param int month: Month to use in the calendar,
if None the c... | 232dd093b08c53f099b942d4497aef920002f5d4 | 5,452 |
def format_allowed_section(allowed):
"""Format each section of the allowed list"""
if allowed.count(":") == 0:
protocol = allowed
ports = []
elif allowed.count(":") == 1:
protocol, ports = allowed.split(":")
else:
return []
if ports.count(","):
ports = ports.s... | 0c07feec16562826a1f38a11b1d57782adf09b4d | 5,453 |
import os
def upload_image():
"""
form-data:
image: a jpeg picture
:return: a file pathname, assigned by backend.
"""
if 'image' not in request.files:
return '', 400
f = request.files['image']
if f.filename == '':
return '', 400
if not _allowed_file(f.filename):
... | f74f90a3acce30e550e92d3cec51039450db7401 | 5,454 |
def get_airmass(when, ra, dec):
"""Return the airmass of (ra,dec) at the specified observing time.
Uses :func:`cos_zenith_to_airmass`.
Parameters
----------
when : astropy.time.Time
Observation time, which specifies the local zenith.
ra : astropy.units.Quantity
Target RA angle(... | 2d2b25963cc5814c8189b117734963feda762d88 | 5,455 |
def get_metadata(class_):
"""Returns a list of MetaDataTuple structures.
"""
return list(get_metadata_iterator(class_)) | 95bc083464431cd8bc3c273989680732f711c5c1 | 5,456 |
def get_register(regname):
"""
Get register value. Exception will be raised if expression cannot be parse.
This function won't catch on purpose.
@param regname: expected register
@return register value
"""
t = gdb.lookup_type("unsigned long")
reg = gdb.parse_and_eval(regname)
return ... | 43d077b59dc0b1cb8a6233538a2a1291216c1ec4 | 5,457 |
import re
def create_queries(project_id, ticket_number, pids_project_id, pids_dataset_id,
pids_table):
"""
Creates sandbox and truncate queries to run for EHR deactivated retraction
:param project_id: bq name of project
:param ticket_number: Jira ticket number to identify and title... | 2940468b76ccd4d16dfb1bbddf440be635eaaf8d | 5,458 |
def load_and_estimate(file, arguments, denoise=medfilt, data=None):
"""Loads mean+std images and evaluates noise. Required for parallelization."""
# Pipeline for µCT data
if data is not None:
# Evaluate noise on data
noises = np.zeros(len(metrics))
for m in range(len(metrics)):
... | 63b53eb5441dd9a2e9f4b558005b640109fea220 | 5,459 |
import torch
def calc_self_attn(
bert_model: BertModel, protein: dict, device="cuda:0", **kwargs
):
"""Calculate self-attention matrices given Bert model for one protein.
Args:
bert_model: a BertModel instance
protein: a dict object from LM-GVP formatted data (json record).
de... | 4d076cc232207c9c446c4f9f52f1156af2afabf2 | 5,460 |
def compute_median_survival_time(times, surv_function):
"""
Computes a median survival time estimate by looking for where the survival
function crosses 1/2.
Parameters
----------
times : 1D numpy array
Sorted list of unique times (in ascending order).
surv_function : 1D numpy array... | 22103bc705acb791c0937a403aa9c34e9145e1c2 | 5,461 |
def TDMAsolver_no_vec(coeffs):
"""
TDMA solver, a b c d can be NumPy array type or Python list type.
refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm
and to http://www.cfd-online.com/Wiki/Tridiagonal_matrix_algorithm_-_TDMA_(Thomas_algorithm)
"""
a = coeffs[1:, 0]
b = coef... | cdec1baa7ce0fe2baef71631b0ba678a0f7559dc | 5,462 |
def aggregate_ant(data, sub_num, response_type="full"):
"""
Aggregate data from the ANT task.
Calculates various summary statistics for the ANT task for a given subject.
Parameters
----------
data : dataframe
Pandas dataframe containing a single subjects trial data for the task.
su... | be01651d450560a5c36bc6240025fe59352d6347 | 5,463 |
def parse_search_after(params):
"""Validate search_after and return it as a list of [score, ID]."""
search_pair = params.get("search_after")
sort = params.get("sort")
if not search_pair or not sort:
return
if '_' not in search_pair or len(search_pair.split("_")) != 2:
return
_sco... | f44228d4f5b47129218d122adcb29e41a81c5a1f | 5,464 |
import torch
def compute_cosine_distance(
features, others=None, cuda=False,
):
"""Computes cosine distance.
Args:
input1 (torch.Tensor): 2-D feature matrix.
input2 (torch.Tensor): 2-D feature matrix.
Returns:
torch.Tensor: distance matrix.
"""
if others is None:
... | 702fe068f99efc1b8dda7f03d361dcceb62c7426 | 5,465 |
from typing import Any
def convert_dict_keys_case(obj: Any, case_style: str = CaseStyle.CAMEL):
"""
This function recursively changes the case of all the keys in the obj
argument
"""
case_style = process_case_style(case_style=case_style)
if isinstance(obj, (tuple, list)):
return type(... | 2b09a7d8ace030ba2543f9bdb74e7201e07243e1 | 5,466 |
def chain_exception(new_exc, old_exc):
"""Set the __cause__ attribute on *new_exc* for explicit exception
chaining. Returns the inplace modified *new_exc*.
"""
if DEVELOPER_MODE:
new_exc.__cause__ = old_exc
return new_exc | ce19e735a26fb03d170f74d6590fb256cd70d70a | 5,467 |
def make_input_fn(x_out, prob_choice):
"""Use py_func to yield elements from the given generator."""
inp = {"inputs": np.array(x_out).astype(np.int32),
"problem_choice": prob_choice}
flattened = tf.contrib.framework.nest.flatten(inp)
types = [t.dtype for t in flattened]
shapes = [[None] * len(t.sha... | 1e5e8717cb348a9114dd15ddce50cb33af50b75c | 5,468 |
import re
def url_validate(url):
"""
URL验证
用于登录传递URL
"""
regex = r'^\?next=((/\w+)*)'
if isinstance(url, str) and re.match(regex, url):
return url.split('?next=')[-1]
return '/' | 7a5aa5866018d1bf16c0f4ede527a770da760e17 | 5,469 |
from typing import Tuple
def mie_harmonics(x: np.ndarray, L: int) -> Tuple[np.ndarray]:
"""Calculates the spherical harmonics of the mie field.
The harmonics are calculated up to order L using the iterative method.
Parameters
----------
x : ndarray
The cosine of the angle defined by the ... | 3998b065737db276142a3a25ee30c866ab52fbbd | 5,470 |
def is_version_dir(vdir):
"""Check whether the given directory contains an esky app version.
Currently it only need contain the "esky-files/bootstrap-mainfest.txt" file.
"""
if exists(pathjoin(vdir,ESKY_CONTROL_DIR,"bootstrap-manifest.txt")):
return True
return False | 931d46c96523bd63d1087cb612a73d98d6338ae2 | 5,471 |
def session_decrypt_raw(encrypted_message, destination_key):
"""
Decrypts the message from a random session key, encrypted with the
destination key.
Superior alternative when the destination key is slow (ex RSA).
"""
block_size = destination_key.block_size
encrypted_session_key = encrypted_... | 7b13ea5d689e050aba5f5a4c6de9c0ca5346bb76 | 5,472 |
def gef_pybytes(x):
"""Returns an immutable bytes list from the string given as input."""
return bytes(str(x), encoding="utf-8") | 8e8cff61e035ac2ef9f6a2cf462a545a05c0ede8 | 5,473 |
def plot_2d_morphing_basis(
morpher,
xlabel=r"$\theta_0$",
ylabel=r"$\theta_1$",
xrange=(-1.0, 1.0),
yrange=(-1.0, 1.0),
crange=(1.0, 100.0),
resolution=100,
):
"""
Visualizes a morphing basis and morphing errors for problems with a two-dimensional parameter space.
Parameters
... | a99fc0a710d42557ec35be646171a25ce640c01e | 5,474 |
import numpy
def single_lut_conversion(lookup_table):
"""
This constructs the function to convert data using a single lookup table.
Parameters
----------
lookup_table : numpy.ndarray
Returns
-------
callable
"""
_validate_lookup(lookup_table)
def converter(data):
... | 6d01aa69053d964933bf330d8cf2340ea3f13eba | 5,475 |
def signal_average(cov,bin_edges=None,bin_width=40,kind=3,lmin=None,dlspace=True,return_bins=False,**kwargs):
"""
dcov = cov * ellfact
bin dcov in annuli
interpolate back on to ell
cov = dcov / ellfact
where ellfact = ell**2 if dlspace else 1
"""
modlmap = cov.modlmap()
assert np.all... | 3075cdef1a7063c295a60c06b368bd337870c883 | 5,476 |
def find_tree_diameter(g):
"""
Standard awesome problem
So for each node, I want to find the maximum distance to another node
:param n:
:param g:
:return:
"""
# First finding the arbitary node that is maximum distance from root
# DFS - First time
q = deque()
q.append((1,0))... | 393e6f9b95316c005a3a056bdd291047f96853ec | 5,477 |
def edge_list_to_adjacency(edges):
"""
Create adjacency dictionary based on a list of edges
:param edges: edges to create adjacency for
:type edges: :py:list
:rtype: :py:dict
"""
adjacency = dict([(n, []) for n in edge_list_to_nodes(edges)])
for edge in edges:
adjacency... | c756baf0cb1182ab79df0846afd97296a0b42679 | 5,478 |
def __renormalized_likelihood_above_threshold_lnlikelihood(data, thr=__thr, alpha=models.__alpha, beta=models.__beta, num_mc=models.__num_mc, **kwargs):
"""
only include data that is above thr, treats them all as signals, and renormalizes the likelihood so that it only covers "detectable data"
"""
truth... | 47d8d75ef136eb809fa62f77226734ad5201d49e | 5,479 |
def _build_tags(model_uri, model_python_version=None, user_tags=None):
"""
:param model_uri: URI to the MLflow model.
:param model_python_version: The version of Python that was used to train the model, if
the model was trained in Python.
:param user_tags: A collection o... | 8807967b3e9d89dbb7a24542d2709bc9293992df | 5,480 |
def test_token(current_user: usermodels.User = Depends(get_current_user)):
"""
Test access token
"""
return current_user | b74580436bba2d02c14a0840fcc0a139e637abd2 | 5,481 |
def student_list_prof_request():
"""Return a JSON containing adding instructor requests, or raise 401 if not authorized."""
role_student = Role.query.filter_by(name='student').first()
if current_user.is_authenticated and has_membership(current_user.id, role_student):
list_approved = request.args.get... | 488a5b342cdb8a83ff94f0c234f5a0996c0c0203 | 5,482 |
def set_complete(request, id):
"""
Marque un ticket comme complet
:param request:
:param id:
"""
ticket = Tickets.objects.get(pk=id)
ticket.complete = 1
ticket.save()
return redirect('/ticket/id=%s' % id) | a37e24751e6899c1cc9f413c6d0a356825b1c79f | 5,483 |
import pathlib
def parse_version_from_path(path):
"""Get version parts from a path name."""
path = pathlib.Path(path).absolute()
version = path.name
try:
parts = version.split("_")
ret = {}
ret["major"] = try_int(parts[0])
ret["minor"] = try_int(parts[1])
ret["p... | 56abb214d6c3b6033a77b10c4d1a1d836ce0f8bd | 5,484 |
from typing import Dict
from typing import Any
from typing import Sequence
import math
import itertools
def assign_partitions_to_actors(
ip_to_parts: Dict[int, Any],
actor_rank_ips: Dict[int, str]) -> Dict[int, Sequence[Any]]:
"""Assign partitions from a distributed dataframe to actors.
This ... | 884b2b05f965c8e3517f9e49019b0bfbf06f0298 | 5,485 |
from typing import Tuple
def unsorted_array(arr: list) -> Tuple[list, int, Tuple[int, int]]:
"""
Time Complexity: O(n)
"""
start, end = 0, len(arr) - 1
while start < end and arr[start] < arr[start + 1]:
start += 1
while start < end and arr[end] > arr[end - 1]:
end -= 1
f... | c3370a3e76009ef26ae3e1086e773463c312c6bb | 5,486 |
def get_tol_values(places):
# type: (float) -> list
"""List of tolerances to test
Returns:
list[tuple[float, float]] -- [(abs_tol, rel_tol)]
"""
abs_tol = 1.1 / pow(10, places)
return [(None, None), (abs_tol, None)] | 5af82438abbc0889374d62181ca7f0b7ee3c0fbe | 5,487 |
def index(atom: Atom) -> int:
"""Index within the parent molecule (int).
"""
return atom.GetIdx() | 64d385588f683a048dfa9d54ea25d85c14f04cb7 | 5,488 |
def specification_config() -> GeneratorConfig:
"""A spec cache of r4"""
return load_config("python_pydantic") | ca4936fac7499cf986fb7ae201a07b77d6b7d917 | 5,489 |
def _wait_for_stack_ready(stack_name, region, proxy_config):
"""
Verify if the Stack is in one of the *_COMPLETE states.
:param stack_name: Stack to query for
:param region: AWS region
:param proxy_config: Proxy configuration
:return: true if the stack is in the *_COMPLETE status
"""
lo... | b9ed5cd161b2baef23da40bc0b67b8b7dfc2f2ea | 5,490 |
from typing import Optional
def create_order_number_sequence(
shop_id: ShopID, prefix: str, *, value: Optional[int] = None
) -> OrderNumberSequence:
"""Create an order number sequence."""
sequence = DbOrderNumberSequence(shop_id, prefix, value=value)
db.session.add(sequence)
try:
db.sess... | 49484a1145e0d2c0dde9fdf2935428b5f68cd190 | 5,491 |
import os
import shutil
import csv
def move_wheel_files(name, req, wheeldir, user=False, home=None):
"""Install a wheel"""
scheme = distutils_scheme(name, user=user, home=home)
if scheme['purelib'] != scheme['platlib']:
# XXX check *.dist-info/WHEEL to deal with this obscurity
raise NotI... | 8e466a16a965f5955ff49cdbee1027b3e3d3074b | 5,492 |
import os
def read_hdulist (fits_file, get_data=True, get_header=False,
ext_name_indices=None, dtype=None, columns=None,
memmap=True):
"""Function to read the data (if [get_data] is True) and/or header (if
[get_header] is True) of the input [fits_file]. The fits file... | 54188e63edb3432035fe851bd81d9e478138b728 | 5,493 |
def calcMFCC(signal, sample_rate=16000, win_length=0.025, win_step=0.01,
filters_num=26, NFFT=512, low_freq=0, high_freq=None, pre_emphasis_coeff=0.97,
cep_lifter=22, append_energy=True, append_delta=False):
"""Calculate MFCC Features.
Arguments:
signal: 1-D numpy array.
... | b10429bec859af3f5e6302e7f2f185bf64178922 | 5,494 |
def get_user(domain_id=None, enabled=None, idp_id=None, name=None, password_expires_at=None, protocol_id=None, region=None, unique_id=None):
"""
Use this data source to get the ID of an OpenStack user.
"""
__args__ = dict()
__args__['domainId'] = domain_id
__args__['enabled'] = enabled
__ar... | e7f6a874816673ebab1fe2f5e807def02fe232d1 | 5,495 |
def use(workflow_id, version, client=None):
"""
Use like ``import``: load the proxy object of a published `Workflow` version.
Parameters
----------
workflow_id: str
ID of the `Workflow` to retrieve
version: str
Version of the workflow to retrive
client: `.workflows.client.Cl... | d8f34e521af161e8840e11c8c888fd959e8584c9 | 5,496 |
def logout():
"""
Route for logout page.
"""
logout_user()
return redirect(url_for('index')) | 4e59dd9a6b59639e24053be072f4ade4fb23d922 | 5,497 |
def ipv4_size_check(ipv4_long):
"""size chek ipv4 decimal
Args:
ipv4_long (int): ipv4 decimal
Returns:
boole: valid: True
"""
if type(ipv4_long) is not int:
return False
elif 0 <= ipv4_long <= 4294967295:
return True
else:
return False | 97c5d5c7472fb81e280f91275b5a88b032ee7927 | 5,498 |
def generate_gate_hadamard_mat() -> np.ndarray:
"""Return the Hilbert-Schmidt representation matrix for an Hadamard (H) gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element.
The result is a 4 times 4 real matrix.
Parameters
----------
... | 8dd36adb0cef79cbc758267fb7adf371f7b698b0 | 5,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.