content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _health_info(q_len=None):
"""
compute daemon health info
based only on the visible state of the frontend queue
the queue length can be passed by the caller (for visibility during flush)
or it will be taken from len(_g_queue)
"""
if q_len is None:
q_len = len(_g_queue) # no lock... | 36089fe229e4a7fb2b2371bcfaffc9c135cba8ed | 3,614,400 |
import functools
def is_to(func):
"""Decorator that ensures caller is owner, TO, or admin."""
@functools.wraps(func)
async def wrapper(self, *args, **kwargs):
ctx = args[0]
user = ctx.author
tourney = kwargs['tourney']
if not (user == tourney.owner or
tourne... | 427306bd299fb84aaf1d271d09ad3ecedf07a66f | 3,614,401 |
def _check_decorator_declaration(to_check:dict, name:str) -> dict:
"""Checks the declared decorator for correctness
params:
-------
to_check : dict
The dict containing the different
parameter definitions for the decorated
function.
name : str
The name of the dec... | dff0fac9a1b300e3f828a0a405c9ef37bd8cedbd | 3,614,402 |
def tokenise(text_list):
"""
Remove symbols and tokenise strings
Parameters
----------
text_list: list
a list of strings, e.g. review comments
Returns
-------
tokenised_comments: a list of spacy docs
"""
# Remove symbols
text_list = [comment.replace("’", "'") for co... | 99bb6e54fffb841fb50f38491b43eb5968971b8d | 3,614,403 |
from typing import OrderedDict
def sample_most_likely(state_vector):
"""Compute the most likely binary string from state vector.
Args:
state_vector (numpy.ndarray or dict): state vector or counts.
Returns:
numpy.ndarray: binary string as numpy.ndarray of ints.
"""
if isinstance(s... | 05993840065a0e832add3dfcb9697a6c0a64616b | 3,614,404 |
def _get_monomial_basis(x):
"""Get the monomial basis (basis for quadratic functions) of x.
Monomial basis = .5*[x(1)^2 sqrt(2)*x(1)*x(2) ... sqrt(2)*x(1)*x(n) ...
... x(2)^2 sqrt(2)*x(2)*x(3) .. x(n)^2]
Args:
x (np.ndarray): Parameter vector of shape (n,).
Returns:
(np.ndarr... | 853d3c808cbe80c05ffb82338c970192c6ab75af | 3,614,405 |
def cardinal(converted_data, path):
"""
Translates first move on path to cardinal direction.
Args:
converted_data (dict): python readable json
path (list): path from a*
Return:
direction (str): cardinal direction as string
"""
# if x values are same check y values for di... | 6802276a8e06a127383cfbe0dcbe511bd0ef2260 | 3,614,406 |
def sum_to_n(n: int) -> int:
"""
>>> sum_to_n(100)
5050
>>> sum_to_n(10)
55
"""
return sum(i for i in range(1, n + 1)) | 867fc0c6b44b153db8215390fbb34fc47bac0c3e | 3,614,407 |
def catch_error(func):
"""A decorator to read error messages after calling ESP functions."""
def inner(*args, **kwargs):
self = args[0]
func(*args, **kwargs)
self.write('TB?', axis="")
error_string = self.read_error()
if error_string[0] is not '0':
self.abort()
raise NewportError(err... | c0e9f37a5221c01b0cfe72275039834bd608fa15 | 3,614,408 |
def normalize_features(x):
""" x - MEAN(x) / STD(x) """
mean = np.mean(x, axis=0)
std = np.std(x, axis = 0)
std[ np.where(std == 0) ] = 1
x = (x - mean)/std
return x | 852dbb087f41f6faf0d50cdbed7b447a76ea6033 | 3,614,409 |
def set_remove():
"""
>>> sorted(set_remove())
[1, 2]
"""
s = set([1,2,3])
s.remove(3)
return s | 4a8c7971944729fb6c0226a7fbf824d744936f4b | 3,614,410 |
import typing
from datetime import datetime
def from_yyyymmdd(date_str: str) -> typing.Union[date, str, None]:
"""
:param date_str: YYYY-MM-DD # 2020-07-16
:return: str -> date
"""
try:
return datetime.strptime(date_str, "%Y-%m-%d").date() # 2020-07-16
except (ValueError, TypeError):
... | 532343e343279f9ac5d438a3ec16c286f8cfa7d7 | 3,614,411 |
import os
import attr
def skip_if_root(func=None):
"""Skip test if uid == 0.
Note that on Windows (or anywhere else `os.geteuid` is not available) the
test is _not_ skipped.
"""
check_not_generatorfunction(func)
def check_and_raise():
if hasattr(os, "geteuid") and os.geteuid() == 0:
... | 8f02001ff734148956924b997bd2f53a41e6521a | 3,614,412 |
def score_letters(genome, setup_data=None):
"""
We want to form the concept of a letter that is noise tolerant, so we show the
network lots of A's, B's, C's and D's and then ask it to cluster noisy
variants. A basic purity metric is used as the scoring function
"""
try:
data = setup_dat... | 93ed35135f2bba8fad8a4441baf35d1a31caab6f | 3,614,413 |
def openDatabaseConnection(hostname, username, dbpass):
"""
Opens a database connection the MySQL server specified using the credentials
specified.
Returns a connection to the database in a cursor object
"""
connection = MySQLdb.connect(host=hostname, user=username, passwd=dbpass)
return co... | f8404611ca50dec204c10da3eabbde307d8cde51 | 3,614,414 |
from datetime import datetime
import time
def timestamp_after_timestamp(timestamp=None, seconds=0, minutes=0, hours=0, days=0):
""" 给定时间戳(10位),计算该时间戳之后多少秒、分钟、小时、天的时间戳(本地时间) """
# 1. 默认时间戳为当前时间
timestamp = get_current_timestamp() if timestamp is None else timestamp
# 2. 先转换为datetime
d1 = datetime.d... | 6f3eb83cd6fff1a171c885f5c52e6782bb638676 | 3,614,415 |
def clr(*colored_text: str, sep: str = "") -> str:
"""Add the color reset code after each colored_text."""
return (sep + colorama.Style.RESET_ALL).join(
colored_text
) + colorama.Style.RESET_ALL | 5c94cdac3ef5cb643204e4eefb0b3911e785985f | 3,614,416 |
def unvec(vectorized):
"""A function that vectorizes a process in the basis of matrix units, sorted first
by column, then row.
Args:
vectorized (list,numpy.ndarray): Nx1 matrix or N-dimensional vector
Returns:
numpy.ndarray: NxN dimensional column vector
Raises:
ValueError... | 63b54d9965be4bdedf0d6f7af06cab27cac6bbcd | 3,614,417 |
import types
import importlib.machinery
def load_user_defined_function(function_name: str, module_file: str):
"""Function to load arbitrary functions
Args:
function_name (str): name of function to load from function_file
module_file (str): file module where function is defined
Returns:
... | 350eda67efb6d346b8833385a21959dd7bf93f47 | 3,614,418 |
def insert_edge_list():
"""Solution to exercise R-14.8.
Repeat Exercise R-14.7 for the adjacency list representation, as described
in the chapter.
---------------------------------------------------------------------------
Solution:
-------------------------------------------------------------... | 8feca54965fbd5f88d2cc2ed638514e77a0b6ec9 | 3,614,419 |
def lastnb(string: str) -> int:
"""
Return the zero based index of the last non-blank character in
a character string.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lastnb_c.html
:param string: Input character string.
:return: """
string = stypes.string_to_char_p(string)
ret... | 7a6fc8c2f97c5fe59ef5376072f23aa696febf1c | 3,614,420 |
from gin_train.metrics import MetricsDict, accuracy
def multiple_train_test_data(dataset_cls, n=1000):
"""Example of multiple train and evaluation datasets.
Second one has a special evaluation metric
"""
return dataset_cls(), [("valid1", RandomDataset(int(n * 0.1))),
("vali... | f2f1727f0c48a7d43fba03b89d2e80df0041a16f | 3,614,421 |
def _get_lines(update_data = False):
"""
Get data frame of lines with count of jams per line and split number
"""
logger.info('Lines')
if update_data:
# Download data from Athena
logger.debug("Downloading lines")
conn = utils.connect_athena(path='configs/athena... | a9ceb02623f2cf76e6e9e1dc110c2b1dd6e3df3a | 3,614,422 |
def get_s3direct_destinations():
"""Returns s3direct destinations.
NOTE: Don't use constant as it will break ability to change at runtime.
"""
return getattr(settings, 'S3DIRECT_DESTINATIONS', None) | 5ee502f07492580e88541de2cffb39f7106048d5 | 3,614,423 |
import json
import pprint
import os
import torch
import logging
def train_multistep_objective(train_data, test_data, output_dir,
num_epochs=5,
num_test_examples=10000,
window_size={0: 2, 1: 10, 2: 20},
... | 052e18d722a68ccc670850411e2685c65a2cfcd4 | 3,614,424 |
def heuristic_iteration(gloss_tokens, trans_tokens, aln, comparison_function, multiple_matches = True, iteration=1, report=False):
"""
:param gloss_tokens:
:type gloss_tokens: list[str]
:param trans_tokens:
:type trans_tokens: list[str]
:param aln:
:type aln: Alignment
:param comparison... | dffec1a56b687012cce6153e1b89f25da7b830ca | 3,614,425 |
def makeIntervalIndex(k=10, name=None, **kwargs):
"""make a length k IntervalIndex"""
x = np.linspace(0, 100, num=(k + 1))
return IntervalIndex.from_breaks(x, name=name, **kwargs) | 72046e2af64c530189bd1f31775e8bcae11fcfa9 | 3,614,426 |
import yaml
import os
def get_context(config_fname: str, ignore_io_errors: bool, **kwargs):
"""
Load the config yaml as the base context, and enrich it with the
information added by the context preprocessors defined in the file.
"""
with open(config_fname) as f:
context = yaml.safe_load(f)... | 8a10c25e16553d0cc61b33b080661f8c2fcaf0a2 | 3,614,427 |
import itertools
def run_demo(num_primes=30):
""" Calculate primes by recursive filtering """
input = OneOne()
output = ManyOne()
@fork_proc
def source():
for n in itertools.count(start=2):
input << n
def worker(port_in, port_out):
prime = ~port_in
port_o... | 5e82e8e86f41de6517c8064b6ff444c3d071eb06 | 3,614,428 |
from typing import List
def get_group_members(user: User, user_group: UserGroup) -> List[User]:
"""
Get the users who belong to this group.
:param user:
:param user_group:
:return:
"""
return get_read_permitted_records(user, user_group.members) | d9f5fb989674fe2f631dde8b78dae443e8eec993 | 3,614,429 |
def set_dataset_args(args, fields, multi_label_data=None):
"""Return dataset arguments dict
"""
dataset_args = set_basic_dataset_args(args)
objective_field = (None if not hasattr(args, 'objective_field')
else args.objective_field)
if multi_label_data is not None and objective... | 4e5163b0eeb66d736b2d085d401552572c6be38d | 3,614,430 |
def complete(request, reference_id):
""" Upon completion of a transaction, users are sent back to this URL.
If SIMPLEPAY_COMPLETE_REDIRECT is defined in settings.py, the user will
be redirected to this URL. Otherwise the simplepay.transaction_complete.html
template will be displayed to ... | 1346e4070a4b0e18947be5684c58a5dd52fb1387 | 3,614,431 |
def debug():
"""Determine whether to we are in debugging mode."""
# look through all open files to see if this plugin is currently being
# edited
for w in sublime.windows():
for v in w.views():
if v.file_name() == __file__:
return True
return False | b219bc8ebfcef7f8edc03a130679ba07cc6b6c9b | 3,614,432 |
def load_corpus(corpus, split=0.8, V=10000, shuffle=0):
"""Load a named corpus and split train/test along sentences.
This is a convenience wrapper to chain together several functions from this
module, and produce a train/test split suitable for input to most models.
Sentences are preprocessed by canon... | 0b8e38f4b249f06c01255de19a95db4d0e1b9ed8 | 3,614,433 |
def get_graylog_response(message, fields=None):
"""Search for a given log message (with possible additional fields)
within a local Graylog instance"""
fields = fields if fields else []
tries = 0
while True:
try:
return _parse_api_response(
api_response=_get_api_r... | a0c404b0873febf37d36af12a9b8df033ea67c11 | 3,614,434 |
def decrypt(sk, c):
"""Decrypt a cyphertext based on the provided key."""
return (c % sk) % 2 | d3a96f66e1b449ffbd5b6ca1ba0827455b83f9e2 | 3,614,435 |
import itertools
def _collapse_series_by_column(grouped_series, sort_data_col):
"""
For each grouped series, take each of its timeseries and
organize them by a data column/key name. Group by the specified
column/key name and extract metadata from them. This intended
to help with cases where there ... | e1baec4b8ec49feaf1ce01811e5911ba3c461125 | 3,614,436 |
def ramp9(params, phase, args=dict(n=6, guess=[1, 0.003, 0.6, 0.009, 0.35, 4e-4])):
"""Model Ramp Eq. 9 from Stevenson et al. (2011).
params: 6-sequence
parameters that define the function, as shown below.
phase: NumPy array.
Orbital phase (or more generally, 'time')
Functional form:
... | 24d8a5ecab5f5fc71240973c0ba62bc23f4791f6 | 3,614,437 |
def view_other_user(request, other_user_id):
"""
Allows the user to view another users profile, and send them follow/friend requests.
Depending on what the relationship is between the user and other_user_id, different
templates will be rendered.
"""
if User.objects.filter(id=other_user_id, type... | 4331cd13b5587a6a670a4a6b0d8146bb55df4a7d | 3,614,438 |
def rebin_image(bin_size, image, wht_map, sigma_bkg, ra_coords, dec_coords, idex_mask):
"""
rebins pixels, updates cutout image, wht_map, sigma_bkg, coordinates, PSF
:param bin_size: number of pixels (per axis) to merge
:return:
"""
numPix = int(len(image)/bin_size)
numPix_precut = numPix * ... | 74cd1ad95ddf5ec553a8116661ff442a5627f80b | 3,614,439 |
def resize_and_crop(image, new_width, new_height, crop=True):
"""
Resize image and maintain aspect ration, then crop
:param image: input image as PIL Image
:param new_width: width of crop
:param new_height: height of crop
:param crop: False if only resizing is required
:return: resized (and ... | 074f10e7f0efeb9b0b03ad2018b819f19b3b37b8 | 3,614,440 |
def merge_dataframes(df1, df2, df1_column_names, column_keys):
"""
Merge two dataframes using a column value as a key.
Args:
df1 (table): [description]
df2 (table): [description]
column_keys (string): [description]
"""
df1 = df1[df1_column_names]
df1[column_keys] = df1[c... | 2fb102be693a742fdfb6cd2c57ab6751a05f2c19 | 3,614,441 |
def hmsdms_to_deg(ra='05h56m0s', dec='+07d25m0s'):
"""
Determine Coordinates in degree from format {RA in HMS, DEC in DMS} to {RA and DEC in degrees}
This can then be copy/pasted in http://simbad.u-strasbg.fr/simbad/sim-fcoo
Example usage:
_ = hmsdms_to_deg(ra='05h55m10.30536s', dec... | c685718f1230da85d6c464813629d680222825a9 | 3,614,442 |
from typing import Dict
from typing import Any
def delete_user(
user: UserBase = Depends(auth_user),
db: Session = Depends(get_db)
)-> Dict[str, Any]:
"""
deletes the currently logged in user
Parameters
----------
None
Returns
--------
user_id : UUID
"""
return ... | 623741f9e3a43e04a244999ff42e8de9f71eb317 | 3,614,443 |
def de_coalesce_visibility(vis: Visibility, vistemplate: Visibility, params={}) -> Visibility:
""" De-coalesce visibility in time and frequency i.e. replicate to template Visibility
This is the opposite of coalescing - the Visibility is expanded into sampling independent
of baseline length.
:p... | 182898dd2c240aa0e05b04218e3ad7dc1a0aa18d | 3,614,444 |
import random
def stickyheptominos_twocolor(rows, cols, seed=None):
"""
A row sticky heptominos, with jitter and randomly oriented.
"""
if seed is not None:
random.seed(seed)
centerx = cols // 2
centery = rows // 2
# Place one methuselah every N grid spaces
# maximum number ... | 95429403e7af9c88ab5de06e4efea096531865c5 | 3,614,445 |
import os
def list_images(remove_ext=True):
"""Based on the .png files in the data/images folder, return the paths."""
data = os.path.join(here, "data", "images")
return list_folder(data, remove_ext=remove_ext, ext=".png") | a46781044c229831762be990667ce8b6110765fa | 3,614,446 |
def cli_ncbi_link_bioproject(email, password, endpoint, org_name, bioproj_accession):
"""Create a pangea group from an NCBI BioProject.
Creates a Pangea SampleGroup corresponding to the given bioproject accession.
- This SampleGroup is a Pangea Library that can contain samples
- A PangeaSample is cre... | cd8a6e7f6520633aef5c6e20d79a36847b199128 | 3,614,447 |
async def project_edit(
project_id: int,
project: CreateAndUpdateProject,
db=Depends(get_db),
current_user=Depends(get_current_active_user)
):
"""
Update existing project
"""
try:
return edit_project(db, project_id, project)
except Exception as e:
return JSONResponse(... | 4a4f5c1a223bb2dcd93beb4c922616bd5fb710e1 | 3,614,448 |
def preprocess_image(image):
"""
预处理图片,包括变形到(1,width, height)形状,数据归一到0-1之间
:param image: 输入一张图片
:return: 预处理好的图片
"""
image = image.resize((width, height))
image = img_to_array(image)
image = np.expand_dims(image, axis=0) # (width, height)->(1,width, height)
image = vgg19.preprocess_... | 7ed80ec44266789d9cf73064cc884122a8ab8707 | 3,614,449 |
from typing import Any
import inspect
def is_valid_broker(obj: Any) -> bool:
"""
Helper utils to check if an object can
be used as a broker in `WebSocketManager`.
Exposed to developers who need to implement a
custom broker.
"""
return (
(hasattr(obj, 'subscribe') and inspect.iscoro... | 9452c2f8698264e28b72c5b597ff4c9804ea419e | 3,614,450 |
async def enable_entity(
hass: HomeAssistant, entry_id: str, entity_id: str
) -> er.RegistryEntry:
"""Enable a disabled entity."""
entity_registry = er.async_get(hass)
updated_entity = entity_registry.async_update_entity(entity_id, disabled_by=None)
assert not updated_entity.disabled
await hass... | b0c2882a0435355ab26006aa6ce0dc0f106a9e62 | 3,614,451 |
import itertools
def summary(result):
"""A summary string of a result object.
Args:
result (AugmentedResult): The result object to get the summary of.
Returns:
str: The summary string.
"""
assert isinstance(result, AugmentedResult)
untested = list(
result.augmented_results(
... | 2aa1d9308c72596081c01ee15eb6c55e8fe0a3f3 | 3,614,452 |
from typing import List
from typing import Union
def compute_unique_fused_charges(
charges: List[BaseCharge], flows: Union[np.ndarray,
List[bool]]) -> BaseCharge:
"""
For a list of charges, compute all possible fused charges resulting
from fusing `charges`.
Args... | 9cbdf66a4c9af5c24ddf78240c8ffad3c62807ad | 3,614,453 |
def get_window(image, window_size, centre_coordinates):
"""
Get a window in image taking into account boundary conditions
image: a numpy array representing our image
window_size: an odd number specifying the size of the window
centre_coordinates: a list containing the x-y coordinates of ... | 41a2e83c045500d4462d405477730e95edb31671 | 3,614,454 |
import sys
def truncation_logic(df, snappt, lencolname, gordcolname, elevcolname):
"""Figure out where to stop this flowpath."""
df["distance"] = df["geometry"].distance(snappt["geometry"])
# 91 gully head
# 98 Gulley Head -10m
# 99 Gulley Head +10m
# 100 Gulley Head -20m
# 101 Gulley Head... | d896d2c79ba7510aa680cb3f185424c435845956 | 3,614,455 |
from typing import get_origin
def get_base_generic_type(object_type):
"""
Utility method to return the equivalent non-customized type for a Generic type, including user-defined ones.
for example calling it on typing.List<~T>[int] will return typing.List<~T>.
If the type is not parametrized it is retu... | 03be217c9894d4523a0ab4030957d46f9b75fa88 | 3,614,456 |
import math
def centre_dot(dot_ls):
"""计算多个经纬度坐标的中心点"""
lng = 0
lat = 0
count = len(dot_ls)
for dot in dot_ls:
lng += float(dot[0]) * math.pi / 180
lat += float(dot[1]) * math.pi / 180
lng /= count
lat /= count
center_dot = (lng * 180 / math.pi, lat * 180 / math.pi)
... | bf7012b5c622e05734e394c912b7f000a3119fca | 3,614,457 |
import requests
def get_steam_app_html(app_id):
"""
Get html from Steam app's Steam store page.
:param app_id: Steam Store app id
:return: html string from Steam store page.
"""
url = get_steam_app_url(app_id)
request = requests.get(url)
return request.text | bd3352f9404436f4588f716b4a4350f3f28c002e | 3,614,458 |
def get_elevator_floor(actual_floor):
"""
Given an actual floor, convert it to an elevator
button number by skipping the thirteenth floor
Parameters
----------
actual_floor: int
The actual floor we're traveling to
Returns
----------
elevator_floor: int
What the eleva... | 9a76b2c2ef5af9964a3eaefe93fd4a764caaafad | 3,614,459 |
from optparse import OptionParser
import os
def parse_options():
"""
set up command line parser options
"""
usage = 'usage: %prog [options]'
parser = OptionParser(usage=usage)
parser.add_option('-t', '--task', dest='task', type='str',
help='tasks: u09, u08, u07, m07... | ab6e89068d3b61d0cadd844a34a818fe037a0e6a | 3,614,460 |
import os
import subprocess
def test_invoking_prediction_tools(
prediction_query,
test_dir,
subprocess_returncode_1,
monkeypatch,
):
"""Test invoking prediction tools."""
def mock_getcwd(*args, **kwargs):
return test_dir
def mock_changing_dir(*args, **kwargs):
return
... | aca21b653fe55f457f6327cf2afd7b7e7d9bd8cb | 3,614,461 |
def _compute_attention(attention_mechanism, cell_output, attention_state,
attention_layer):
"""Computes the attention and alignments for a given attention_mechanism."""
alignments, next_attention_state = attention_mechanism(
cell_output, state=attention_state)
# Reshape from [batch_size, memory_time]... | bc1f5a01eae155d1285cc2830dfb2a967a4d212d | 3,614,462 |
def find(db, clazz, name):
""" Find something by name"""
dao = Daos.createBaseDao(db, clazz)
for item in dao.getAll():
if item.name == name:
return item
return None | 0ade7a1bdebc39f1910665ff3a44132928f26f89 | 3,614,463 |
def search_location_reports_by_tags(tag_name_list): # works
"""returns a list of LocationReports that contain a certain tag"""
all_location_reports = get_all_location_reports()
location_report_key_set = set()
tag_key_list = []
for tn in tag_name_list:
tag = create_or_get_tag(tn)
... | 75a5cafa10d7fa4d69a609637025e25009f03007 | 3,614,464 |
def __find_yzwing_candidates(sboard, current_cell_name, num_values, num_intersection_values):
"""
A support method to find candidate cells to be ywing or xyzwing pincers.
"""
candidates = []
current_cell = sboard.getCell(current_cell_name)
current_value_set = current_cell.getValueSet()
assoc... | 34e45339eeee158827e8633cdab33ae80e08b3d0 | 3,614,465 |
def rsck_to_kcrs(src):
"""Converts tensor from RSCK to KCRS format. Usually
used for converting convolution filter tensors.
cuDNN notation is used for dimensions where RS are
spatial dimensions (height and width), C - number
of input channels and K - number of output channels.
"""
assert len... | 7c3b36f1594feec6c68ae36ae6ebc000e51ca687 | 3,614,466 |
import unittest
def I3TestModuleFactory(*test_cases):
"""Test case factory
Create an `I3Module` that runs the given `unittest` test cases on
each Physics frame.
Example
-------
Create a simple test case::
class I3TimeHorizonCutTest(unittest.TestCase):
def testKeys(self):... | c3a37e51042f41bffb64555e3f7e8dcbb71c1db8 | 3,614,467 |
def index():
"""Video streaming home page."""
return "Select a spell to cast." | af7ade462eed869fa4d75722bc46e5beb199bf09 | 3,614,468 |
def dummy_dataframe() -> pd.DataFrame:
"""Create dummy data for testing."""
return pd.DataFrame({"col1": [1, 2], "col2": [4, 5], "col3": [5, 6]}) | 694ad4a1d8f5213318b70ffe863ac61e72f8cfd3 | 3,614,469 |
def rolling_window(a, window,axis=-1,pad=False,mode='reflect',**kargs):
"""
This function produces a rolling window shaped data with the rolled data in the last col
a : n-D array of data
window : integer is the window size
axis : integer, axis to move the window over
... | 84152a36a736fb7e9c57b28bb66ca24498506101 | 3,614,470 |
import os
def execute_with_msg(cmd):
"""
返回命令执行的文本输出
:param cmd:
:return:
"""
core.v("execute_with_msg: " + str(cmd))
r = os.popen(cmd)
text = r.read()
r.close()
return text | 88ff90e1d26a826f8b014873babf17a869060071 | 3,614,471 |
def volume(V, n_iter=100):
"""
Monte Carlo estimate of volume of
convex hull of V, intersected with the unit cube
"""
dim = len(V[0])
included = []
num_in = 0
for _ in range(n_iter):
x = np.random.random(dim) - 0.5
incl = in_hull(x, V)
num_in += incl
in... | f904f13816c52a72603eea1a65c319c535eedefe | 3,614,472 |
def color_set(num, black=False, cset='xkcd'):
"""Retrieve a (small) set of color-strings with hand picked values.
Arguments
---------
num : int
Number of colors to retrieve.
black : bool
Include 'black' as the first color.
cset : str, {'xkcd', 'def'}
Which set of colors ... | 3ec8c1f01c2690a491bfba2d13e8b0d0f46507d7 | 3,614,473 |
def encode_length(mtype, length):
# type: (MainType, Length) -> int
"""
Encode length to integer value for header encoding.
The `length` value has MainType-specific semantics:
For MainTypes `META`, `SEMANTIC`, `CONTENT`, `DATA`, `INSTANCE`:
Length means number of bits for the body.
... | b45800aabf05062438df324d3179cb63104be3dd | 3,614,474 |
def out_in_advance(play_dict, bto=None, bfrom=None):
"""runner out when advancing by next base
- play_dict: play dictionary
- bto : base to, heading to
- bfrom: base coming from, previous base
"""
bto = '1' if not bto and not bfrom else bto
if bfrom:
play_dict[bfrom] = 0
play... | 5fa607d8fb901becd31cd1b7763e42953419baea | 3,614,475 |
import tqdm
def calc_nkt(fldr, slices, dump_step, species_np, k_list, verbose):
"""
Calculate density fluctuations :math:`n(k,t)` of all species.
.. math::
n_{A} ( k, t ) = \sum_i^{N_A} \exp [ -i \mathbf k \cdot \mathbf r_{i}(t) ]
where :math:`N_A` is the number of particles of species :math... | be6758d9074a6a60bd3b2c7c46f00f0c1f8e812e | 3,614,476 |
def _get_reader(source, batch_size):
"""Returns 'CsvReader' for the given source
Parameters
----------
source: str or bytes
Name of the SageMaker Channel, File, or directory from which the data is being read or
the Python buffer object from which the data is being read.
... | 495917fb23665a186cae1efde57b1a67b62b186f | 3,614,477 |
def Spline(points, n_points=None):
"""Create a spline from points.
Parameters
----------
points : np.ndarray
Array of points to build a spline out of. Array must be 3D
and directionally ordered.
n_points : int, optional
Number of points to interpolate along the points arra... | b3ab55d426bb9d9395121b90d4174ad41edc175b | 3,614,478 |
def get_version():
"""
Get PDC version info
"""
return VERSION | f127128c7c8f51f11175e471acacd85a0ca29814 | 3,614,479 |
from typing import List
def _get_mock_tokenizer():
"""Creates a mock tokenizer."""
class MockSpieceModel:
"""Mock Spiece model for testing."""
def __init__(self):
self._special_piece_to_id = {
"<unk>": 0,
}
for piece in set(list('!"#$%&\"()*+,-./:;?@[\\]^_`{|}~')):
se... | 39e39e41afbad7649e4e29b3fb6dfc13dc897fe8 | 3,614,480 |
def make_processing_action(processing_step: BaseProcessingStep):
"""
Generate the admin action function for processing steps
"""
def perform_processing_step(modeladmin, request, queryset):
last_error = None
last_content = None
error_counter = 0
success_counter = 0
... | 71330c5cd608d08ceb44a1b869eabbb2f86e12b3 | 3,614,481 |
def grid_search(model,
model_params,
make_feature_pipeline,
make_target_pipeline,
pipeline_params,
train_data):
"""
Grid search combined with cross validation
args
model (sklearn model)
model_params (list) contains dictionaries of parameters
make_feature_pipeline (function)
make... | bc173af3e057dcdefa2c177891f282ce60bbec96 | 3,614,482 |
def processes(method):
"""
Returns Dict of all task id => process
"""
return background_processes.get(method, dict()) | d74ab26dcddde77a640eb277f01cad615e420968 | 3,614,483 |
def permissions(store: BaseAccessStore, user_id: str) -> list:
"""
get all the direct and indirect user-permission relationships for this user
first, get the relationships in which a group is granted to this user
follow the group inheritance chain to get all the associated group-group relationships... | 585d27c1934f0afa4efd13f9dc89dbc6e7895867 | 3,614,484 |
import logging
def get_local_grb_rate(rate_name=None, with_range=False):
"""Returns local grb rate
:param rate_name: Name of chosen evolution
:param with_range: Boolean to return +/- one sigma range functions alongside central rate
:return: Normalised evolution, equal to 1 at z=0
"""
if rate... | ede0c7036945a6ccdc40551b73da7c5882963a34 | 3,614,485 |
def create_task(conn, task):
"""
Create a new task
:param conn:
:param task:
:return:
"""
sql = ''' INSERT INTO News(V2.1DATE, V2SOURCECOLLECTIONIDENTIFIER, V2SOURCECOMMONNAME, V2DOCUMENTIDENTIFIER, V1LOCATIONS, V1ORGANIZATIONS, V1.5TONE, V2GCAM, V2.1ALLNAMES, TITLE)
VALUES(?,... | 89f1b00b72741d5bd7eff783a9f51cb07b30a469 | 3,614,486 |
from typing import Callable
from typing import Optional
from re import S
import sys
import click
import time
def wait_for_job(task_id: str, status_callback: Callable[[], Optional[S]]) -> S:
"""
Wait for a job to complete (with a CLI spinner) and return its final result.
:param task_id: ID of the task (us... | 6be7aaeb892ded831834a8c9aea73e098bc37033 | 3,614,487 |
def delete_global_account_limit(account, rse_expression, issuer, vo='def', session=None):
"""
Delete a global account limit..
:param account: The account name.
:param rse_expression: The rse expression.
:param issuer: The issuer account_core.
:param vo: The VO to act ... | b350a7c0189eebfaec7755a1d903c18db691cb56 | 3,614,488 |
def generateEmailFlags(emailFlagTuples):
"""
Takes emailFlagTuples and generates the part of the
script case statement which accepts email flags.
"""
emailFlagString = ""
for emailFlagTuple in emailFlagTuples:
#add a new line and indent
emailFlagString += "\n "
#add flag character
emai... | d83ae2f8a135218351fb20af378fe3bf702a2344 | 3,614,489 |
def tail(n):
"""
Returns the last n rows of a DplyFrame
:param n: number of rows to select
:return: a function that returns a new DplyFrame
"""
return lambda d1: DplyFrame(d1.pandas_df.tail(n)) | 6a50b5c43e78c9a84b31baac3f5153b90f4f96f5 | 3,614,490 |
import requests
import logging
def export_jira_data(jira_base_url, jira_credentials_file, jira_filter, xml_filename):
"""Export XML assessment data from Jira to a file.
Parameters
----------
jira_base_url: str
The base URL of the Jira server that houses the assessment data.
jira_credenti... | 277bea9aa0f959a78f249b1382822fd768a0272f | 3,614,491 |
def _struct_alignment(alignments):
"""
Returns the minimum alignment for a structure given alignments for its fields.
According to the C standard, it the lowest common multiple of the alignments
of all of the members of the struct rounded up to the nearest power of two.
"""
return bounding_power... | e2b3be903c2e4c5c444707c630a312365992526e | 3,614,492 |
def apply_operations(context_arrays, operations):
"""
:param context_arrays: numpy arrays to be transformed into a format such that can be fed into a TensorFlow op graph
:return: tensor-ready arrays
"""
preprocessed_context_arrays = []
for context_array in context_arrays:
preprocessed_f... | 027402a2721481e42cef7588603fe2df2e5f22cb | 3,614,493 |
def _get_audio_parameters(param_dict):
"""
Get audio parameters from a dictionary of parameters. An audio parameter can
have a long name or a short name. If the long name is present, the short
name will be ignored. If neither is present then `AudioParameterError` is
raised.
Expected parameters ... | 5638157b4695272b94b7756ddce7abe0d57af694 | 3,614,494 |
def _table_xml(x, y, w, h, bClosed=True, sXmlCells=None):
"""
XML Table element as a string
"""
if bClosed:
# close the list of coordinates
sPoints = "%d,%d %d,%d %d,%d %d,%d %d,%d" % (x, y, x + w, y, x + w, y + h, x, y + h, x, y)
else:
sPoints = "%d,%d %d,%d %d,%d %d,%d" % (... | 51e25bda4b20019ee7cfa593324b019d7e2c0f9e | 3,614,495 |
def server_add_floating_ip(request, server, address):
"""
Associates floating IP to server's fixed IP.
"""
server = novaclient(request).servers.get(server)
fip = novaclient(request).floating_ips.get(address)
return novaclient(request).servers.add_floating_ip(server, fip) | 0c8d3e3999ce8d1a6917d908c42d2f48d14764d2 | 3,614,496 |
def _constraintsearch(df, significance_level=0.05, verbose=3):
"""Contrain search.
test_conditional_independence() returns a tripel (chi2, p_value, sufficient_data),
consisting in the computed chi2 test statistic, the p_value of the test, and a heuristig
flag that indicates if the sample size was suffi... | 70da2aa62113c5eb949e0428e9d18f01ef93f7e0 | 3,614,497 |
def _fix_filename(filename):
"""Return a filename which we can use to identify the file.
The file paths printed by llvm-cov take the form:
/path/to/repo/out/dir/../../src/filename.cpp
And then they're truncated to 22 characters with leading ellipses:
...../../src/filename.cpp
This makes it real... | d4b005f591879aab44275d100e725f61b5d6a764 | 3,614,498 |
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'blogs/topics.html', context) | 9111994f8c6b39a99507e94997251d23b96df4b9 | 3,614,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.