content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def safe_query_string(request):
"""Turn the QUERY_STRING into a unicode- and ascii-safe string.
We need unicode so it can be combined with a reversed URL, but it
has to be ascii to go in a Location header. iri_to_uri seems like
a good compromise.
"""
qs = request.META['QUERY_STRING']
try:
... | 45,500 |
def _create_input_dict(function_graph,
func_arg_placeholders,
initial_value=None):
"""Create a mapping from graph tensor names to function tensor names."""
if initial_value is None:
input_dict = {}
else:
input_dict = dict(initial_value)
for op in function_gr... | 45,501 |
def process(document, rtype=None, api=None):
""" Extracts spelling-corrected tokens in specified format from given texterra-annotated text. """
corrected_tokens = []
if annotationName in document['annotations']:
if rtype == 'annotation':
for token in document['annotations'][annotationNam... | 45,502 |
def get_hashed_path (path: Path, *, algorithm=hashlib.sha256, stretching_count: int=256) -> bytes:
"""
obfuscate a filename.
I recommend this function, if you want to hide from anybody guess a file information from file-name.
"""
p = Path(path)
return p.with_name(base64.urlsafe_b64encode(generate_hash_by_... | 45,503 |
def quantile(values, q):
"""
Returns q-th quantile.
"""
values = sorted(values)
size = len(values)
idx = int(round(size * q)) - 1
if idx == 0:
raise ValueError("Sample size too small: %s" % len(values))
return values[idx] | 45,504 |
def parse_child_text(parent, selector, parser, index=0):
"""Parse the text content of the child element of parent as specified by the given CSS selector
If index is specified, parse the text content of the matching child element at the specified zero-based index; otherwise, parse the text content of the first matchi... | 45,505 |
def uniformCostSearch(problem):
"""Search the node of least total cost first."""
"*** YOUR CODE HERE ***"
from sets import Set
startState = problem.getStartState()
if problem.isGoalState(startState):
return []
# Each element in the fringe stores the state and the cost to reach it.
fr... | 45,506 |
def eval_run(cfg, cfg_name, experiment_identifier, run, net, eval_data, callbacks=tuple(), load_best=True):
"""
Evaluate a training run.
:param cfg: Experiment config
:type cfg: config.defaults.Experiment
:param cfg_name: Config name
:type cfg_name: str
:param experiment_identifier: 8-chara... | 45,507 |
def load_tab_c(tables, fname):
"""Load table C (operators) from 'fname' into object Tables."""
if not os.path.exists(fname):
raise BufrTableError(_text_file_not_found % fname)
with open(fname, "r") as fh:
for line in fh:
if line.startswith('#') or len(line) < 3:
c... | 45,508 |
def test_chelyabinsk_outcome(realistic_planet):
"""
This test asserts the solver's outcome of Chelyabinsk as an airburst event.
The inputs for Chelyabinsk come from from Collins et al. (2017).
"""
frame, out = realistic_planet.impact(9.75, 1.9e4, 3300, 2e6, 20)
assert out['outcome'] == "A... | 45,509 |
def create_new_dataset(data, num_schedules):
"""
creates a dataset where each row is the twenty timesteps of a schedule alongside the chosen task
creates a schedule array that tracks when each schedules starts and ends
:return:
"""
X = []
Y = []
schedule_array = []
for i in range(0, ... | 45,510 |
def replication_load(options, args):
"""%(prog)s load <server:port> <path>
Load the contents of a local directory into glance.
server:port: the location of the glance instance.
path: a directory on disk containing the data.
"""
# Make sure server and path are provided
if len(args) ... | 45,511 |
def init_language():
"""
기본 언어 설정. 없으면 영어. 글-로벌
"""
yaml_data = read_yaml("config.yaml", '!default')
if yaml_data:
lang = yaml_data.get('LANGUAGE')
return lang + "\\" if lang else ""
else: return "" | 45,512 |
def temp_checkout(svnrepos, path, rev):
"""Check out file revision to temporary file"""
fd, temp = tempfile.mkstemp()
fp = os.fdopen(fd, 'wb')
try:
root = svnrepos._getroot(rev)
stream = fs.file_contents(root, path)
try:
while 1:
chunk = core.svn_stream_read(stream, core.SVN_STREAM_CHU... | 45,513 |
def __clean_term__(term, convert_letter = True, w_space = True, is_url=True):
"""
Prepares an input term to be queried in a url
Input
----------------------------------------------------------------
term : str
term to clean
convert_letter : bool (default True)
... | 45,514 |
def merge_vocabs(vocabs, vocab_size=None):
"""
Merge individual vocabularies (assumed to be generated from disjoint
documents) into a larger vocabulary.
Args:
vocabs: `torchtext.vocab.Vocab` vocabularies to be merged
vocab_size: `int` the final vocabulary size. `None` for no limit.
... | 45,515 |
def find_local_minimum(data, threshold=None):
"""
Find local minimum in data.
:param data: input data.
:param threshold: (optional) local minimum whose value is not less than threshold won't be selected.
:return: a 1-D array.
"""
local_min_idx = argrelextrema(data, np.less)
local_min_idx... | 45,516 |
def mouse_annotations(mouse_file):
"""
Updates and get JSON file for mouse annotations
"""
zipped_rows = get_rows_from_file(mouse_file, '\n')
# Too many processes causes the http requests causes the remote to respond with error
pool = mp.Pool(processes=1)
annotations = pool.map(mouse_single_... | 45,517 |
def thomsen_parameters(vp, vs, rho, lb, dz):
"""
Liner, C, and T Fei (2006). Layer-induced seismic anisotropy from
full-wave sonic logs: Theory, application, and validation.
Geophysics 71 (6), p D183–D190. DOI:10.1190/1.2356997
Args:
vp (ndarray): P-wave interval velocity.
vs (ndarr... | 45,518 |
def replace_last(source_string, replace_what, replace_with):
""" Function that replaces the last ocurrence of a string in a word
:param source_string: the source string
:type source_string: str
:param replace_what: the substring to be replaced
:type replace_what: str
:param ... | 45,519 |
def unescape(text):
"""Unescapes text
>>> unescape(u'abc')
u'abc'
>>> unescape(u'\\abc')
u'abc'
>>> unescape(u'\\\\abc')
u'\\abc'
"""
# Note: We can ditch this and do it in tokenizing if tokenizing
# returned typed tokens rather than a list of strings.
new_text = []
esc... | 45,520 |
def patched_novoed_tasks(mocker):
"""Patched novoed-related tasks"""
return mocker.patch("applications.models.novoed_tasks") | 45,521 |
def cart2spherical(x, y, z):
"""
Converts to spherical coordinates
:param x: x-component of the vector
:param y: y-component of the vector
:param z: z-component of the vector
:return: tuple with (r, phi, theta)-coordinates
"""
vectors = np.array([x, y, z])
r = np.sqrt(np.sum(vectors... | 45,522 |
def run_sample():
"""Runs the sample."""
# TODO(developer): Replace this variable with your Google Analytics
# account ID (e.g. "123456") before running the sample.
account_id = "YOUR-GA-ACCOUNT-ID"
audit_account_user_links(account_id) | 45,523 |
def get_JD(year=None, month=None, day=None, hour=None, min=None, sec=None,
string=None, format='yyyy-mm-dd hh:mm:ss', rtn='jd'):
"""compute the current Julian Date based on the given time input
:param year: given year between 1901 and 2099
:param month: month 1-12
:param day: days
:param... | 45,524 |
def get_final_feature(feature_1, feature_2, metric_list):
"""Get the difference between two features.
:param feature_1: the first feature
:type feature_1: numpy array
:param feature_2: the second feature
:type feature_2: numpy array
:param metric_list: the metrics which will be used to comp... | 45,525 |
def add_ioc_queries_to_entities(ti_lookup: TILookup, container: str = "ti", **kwargs):
"""
Add TI functions to entities.
Parameters
----------
ti_lookup : TILookup
TILookup instance.
container : str
The name of the container to add query functions to
"""
ioc_queries = c... | 45,526 |
def removeZeros(infile, outfile, prop=0.5, genecols=2):
"""Remove lines from `infile' in which the proportion of zeros is equal to or higher than `prop'. `genecols' is the number of columns containing gene identifiers at the beginning of each row. Writes filtered lines to `outfile'."""
nin = 0
nout = 0
... | 45,527 |
def cuboid(origin, bounds, direction, color=Vec4(1), normal_as_color=NAC):
"""
Return GeomNode of the cuboid,
Args:
origin: center of the cuboid
bounds: 3-Tuple of length, width and height
direction: normal vector of the up face
color: Vec4
normal_as_color: whether t... | 45,528 |
def fireball_get_HS_dat(cd, fname='HS.dat'):
""" """
f = open(cd+'/'+fname, "r")
nlines = int(f.readline())
#print(nlines)
s = f.readlines()
assert nlines==len(s)
i2aoao = np.zeros((nlines,4), dtype=int)
i2h = np.zeros((nlines))
i2s = np.zeros((nlines))
i2x = np.zeros((nlines,3))
for i,... | 45,529 |
def create(db: Session, request: UsersRequestSchema):
""" Creates a new user.
:return: UserModel
"""
user = UserModel(
username=request.username,
group=request.group
)
db.add(user)
db.commit()
db.refresh(user)
return user | 45,530 |
def format_timedelta(time):
"""Format a timedelta for use in a columnar format. This just
tweaks stuff like ``'3 days, 9:00:00'`` to line up with
``'3 days, 10:00:00'``
"""
result = str(strip_microseconds(time))
parts = result.split()
if len(parts) == 3 and len(parts[-1]) == 7:
retu... | 45,531 |
def describe_protein(s1, s2, codon_table=1):
"""
"""
codons = util.codon_table_string(codon_table)
description = ProteinAllele()
s1_swig = util.swig_str(s1)
s2_swig = util.swig_str(s2)
codons_swig = util.swig_str(codons)
extracted = extractor.extract(s1_swig[0], s1_swig[1],
s2... | 45,532 |
def _convert_gradient_function(
proto: tf.compat.v1.NodeDef,
graph: Any,
library: Mapping[str, _LibraryFunction],
) -> Mapping[str, _LibraryFunction]:
"""Convert a custom_gradient function."""
op = graph.as_graph_element(proto.name)
input_specs = tuple([tf.TensorSpec.from_tensor(v) for v in op.inputs]... | 45,533 |
def generate_warp_function(chromatic_consts=None,
drift=None,
n_dim=3,
verbose=True):
"""Function to generate a spot translating function"""
## check inputs
if chromatic_consts is None:
_ch_consts = np.zeros([n_dim,... | 45,534 |
def Dfunc(sign,k,N,dphi,si,sd,xF=[],F=[],beta=np.pi/2):
"""
Parameters
----------
sign : int
+1 | -1
k : wave number
N : wedge parameter
dphi : phi-phi0 or phi+phi0
si : distance source-D
sd : distance D-observation
beta : skew incidence angle
xF : array
sup... | 45,535 |
def exec(tag, tmpdir):
"""
Run analyzer(s) against the local tagged image and write the result in a local fs
:param tag: str tag name to analyze on local host (e.g. alpine:latest)
:param tmpdir: valid and existing file path
:return:
"""
global config
click.echo('Getting tag manifest for:... | 45,536 |
def deprecated(since=nicos_version, comment=''):
"""This is a decorator which can be used to mark functions as deprecated.
It will result in a warning being emitted when the function is used.
The parameter ``since`` should contain the NICOS version number on which
the deprecation starts.
The ``co... | 45,537 |
def create_rlimits():
"""
Create a list of resource limits for our jailed processes.
"""
rlimits = []
# Allow a small number of subprocess and threads. One limit controls both,
# and at least OpenBLAS (imported by numpy) requires threads.
nproc = LIMITS["NPROC"]
if nproc:
rlimi... | 45,538 |
def validate_file(file_path):
"""check type and validate his_fn. Raise error is incorrect
:function: TODO
:returns: TODO
"""
if not isinstance(file_path, pathlib.Path):
file_path = pathlib.Path(file_path)
if not file_path.is_file():
raise TypeError(
... | 45,539 |
def save_processed_image_uuid(username, uuid):
"""Updates existing user by adding the uuid of the processed image
:param username: user email as string type which serves as user id
:param uuid: UUID4 of processed image
:returns: adds uuid of processed image to mongo database
"""
try:... | 45,540 |
def test_atom_connect_col():
""" Check for existed connect_to column"""
# dataframe already have connect_to column
[_, test_bond] = data_compile.get_df(path + '/samples/user.txt')
test_df = data_compile.get_df_user([path + '/samples/user.txt'])
try:
data_compile.atom_connect(test_df, t... | 45,541 |
def get_existing_archives(s3bucket):
"""
Returns a generator that yields all the dates of the existing archives
"""
for obj in s3bucket.objects.filter(Prefix=settings.S3_KEY_PREFIX):
match = re.match(f"{settings.S3_KEY_PREFIX}-(?P<date>.+)\\.json\\.gz", obj.key)
yield date.fromisoformat(... | 45,542 |
def web_request():
"""Mock web request for views testing."""
return web_request_func() | 45,543 |
def _NormalizeDiscoveryUrls(discovery_url):
"""Expands a few abbreviations into full discovery urls."""
if discovery_url.startswith('http'):
return [discovery_url]
elif '.' not in discovery_url:
raise ValueError('Unrecognized value "%s" for discovery url')
api_name, _, api_version = disc... | 45,544 |
def computeAirmass(dec, ha, lat=config['observatory']['latitude'],
correct=[75., 10.]):
"""Calculates the airmass for a given declination and HA (in degrees).
By default, assumes that the latitude of the observation is the one set
in the configuration file. If correct is defined, abs(HA)... | 45,545 |
def metric_op(metric):
"""Converts Keras metrics into a metric op tuple.
NOTE: If this method is called in for loop, the runtime is O(n^2). However
the number of eval metrics at any given time should be small enough that
this does not affect performance. Any impact is only during graph construction
time, and... | 45,546 |
def gif_from_list(img_list, filename, fps=1):
"""Creates a gif file from a list of images
Parameters
----------
img_list: list
The list of images to make into a gif file
filename : str
The name of the file of the gif that will be created without extension
fps : int, optional
... | 45,547 |
def get_geostore(geostore_id, format='esri'):
""" make request to geostore microservice for user given geostore ID """
config = {
'uri': '/geostore/{}?format={}'.format(geostore_id, format),
'method': 'GET',
}
return request_to_microservice(config) | 45,548 |
def srmi(df, n=9):
"""
SRMIMI修正指标 srmi(9)
如果收盘价>N日前的收盘价,SRMI就等于(收盘价-N日前的收盘价)/收盘价
如果收盘价<N日前的收盘价,SRMI就等于(收盘价-N日签的收盘价)/N日前的收盘价
如果收盘价=N日前的收盘价,SRMI就等于0
"""
_srmi = pd.DataFrame()
_srmi['date'] = df.date
_m = pd.DataFrame()
_m['close'] = df.close
_m['cp'] = df.close.shift(n)
_m... | 45,549 |
def define_pairs(grid: 'np.ndarray'):
"""Take a sequence grid and return all pairs of neighbours.
Returns a list of dictionaries containing the indices of the pairs
(neighbouring only), and the corresponding sequence numbers
(corresponding to the image array)
"""
nx, ny = grid.shape
footpr... | 45,550 |
def _length_normalization(length_norm_power, length, dtype=tf.float32):
"""Returns length normalization factor."""
return tf.pow(((5. + tf.cast(length, dtype)) / 6.), length_norm_power) | 45,551 |
def unregistercls(self, schemacls=None, data_types=None):
"""Unregister schema class or associated data_types.
:param type schemacls: sub class of Schema.
:param list data_types: data_types to unregister.
"""
return _REGISTRY.unregistercls(schemacls=schemacls, data_types=data_types) | 45,552 |
def get_relation_mapper() -> RelationMapper:
"""Get the relation mapper. Create and load if necessary."""
global _relation_mapper
if _relation_mapper is not None:
return _relation_mapper
path = mapping_root.joinpath("reltoid")
if not path.is_file():
create_mapping()
_relation_ma... | 45,553 |
def griffin_lim(stftm_matrix, max_iter=100):
""""Iterative method to 'build' phases for magnitudes."""
stft_matrix = np.random.random(stftm_matrix.shape)
y = librosa.core.istft(stft_matrix, hop_size, window_size)
for i in range(max_iter):
stft_matrix = librosa.core.stft(y, fft_size, hop_size, wi... | 45,554 |
def export_sssom():
"""Export the meta-registry as SSSOM."""
rows = []
for prefix, resource in bioregistry.read_registry().items():
mappings = resource.get_mappings()
for metaprefix, metaidentifier in mappings.items():
if metaprefix not in CURIE_MAP:
continue
... | 45,555 |
def strip_pathname1(name):
"""remove ../ and ./ and leading/trailing blanks and path separators
from input string ``name``, replace any remaining path separator
with '/', and keep only the last part of the path"""
return (name.replace('..' + os.sep, '').replace('.' + os.sep, '').strip().strip(os.sep).sp... | 45,556 |
def parse_subtitle_stream_id(input_file: str, input_sid: Union[int, str, None]) -> Optional[int]:
"""Translate the CLI `-s` parameter into a stream index suitable for subtitle_options()."""
subtitle_streams = tuple(list_subtitle_streams(input_file))
external_sub_file = find_sub_file(input_file)
if input... | 45,557 |
def setup_web3(config_file, _logger=None):
"""
:param config_file: Web3 object instance
:param _logger: Logger instance
:return: web3 instance
"""
network_rpc = os.environ.get("EVENTS_RPC", "http:127.0.0.1:8545")
if _logger:
_logger.info(
f"EventsMonitor: starting with th... | 45,558 |
def routes_to_geojson(
feed: "Feed",
route_ids: Optional[Iterable[str]] = None,
*,
split_directions: bool = False,
include_stops: bool = False,
) -> Dict:
"""
Return a GeoJSON FeatureCollection of MultiLineString features representing this Feed's routes.
The coordinates reference system ... | 45,559 |
def read_input():
"""
Read user input and return state of running the game.
If user press Esc or exit game window stop game main loop.
Returns:
bool: Should game still be running?
"""
# Should we still run game after parsing all inputs?
running = True
# Look at every event in ... | 45,560 |
def add_to_date(date, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, as_string=False, as_datetime=False):
"""Adds `days` to the given date"""
from dateutil.relativedelta import relativedelta
if date==None:
date = now_datetime()
if hours:
as_datetime = True
if isinstance(date, string_type... | 45,561 |
def test_cli_filters_ontology():
"""Test the available attributes returned by apybiomart filters for the
closure_ECO dataset."""
runner = CliRunner()
result = runner.invoke(cli.main,
["filters",
"--dataset", "closure_ECO"])
assert result.exit_co... | 45,562 |
def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
if (z.rea... | 45,563 |
def update(data: dict) -> None:
"""Update a single key."""
# Set up a query to get the current key object but don't fetch it
token = data.pop("token")
key = ApiKey.query.filter_by(token=token)
# Run the query to get the current object and record it
# for auditing purposes
original_info = Ap... | 45,564 |
def IntegerHeap(i):
"""Return an integer heap for 2^i-bit integers.
We use a BitVectorHeap for small i and a FlatHeap for large i.
Timing tests indicate that the cutoff i <= 3 is slightly
faster than the also-plausible cutoff i <= 2, and that both
are much faster than the way-too-large cutoff i... | 45,565 |
def list_sensors(name_pattern=Sensor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all sensors that match the
provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'sensor*'. Default value: '*'.... | 45,566 |
def test_compare_weights_from_poly_and_grid():
"""Confirm that the weights are identical when they are computed from a grid->grid and grid->poly."""
# Global grid
ds = xe.util.grid_global(20, 12, cf=True)
# A single destination tile
tile = xe.util.cf_grid_2d(-40, -80, -40, 0, 80, 80)
ds['a'] =... | 45,567 |
def make_symbolic_link():
""""make a symbolic link to Data"""
if os.path.exists(VM_DATA):
if os.path.islink(VM_DATA):
pass
else:
print "Error: A directory %s already exists" % VM_DATA
sys.exit()
else:
try:
prog = sp.Popen(["find_config.... | 45,568 |
def preprocessBoilerPower(df2, key):
"""
calculates the average boiler power, because we have timestamps where the boiler is turned off/on often not following the capture period
preprocessing is done as well (set index, interpolation)
:param df2: dataframe of boiler
:param key: sensorname
:r... | 45,569 |
def ProbLate(pmf):
"""Computes the probability of a birth in Week 41 or later.
Args:
pmf: Pmf object
Returns:
float probability
"""
return ProbRange(pmf, 41, 50) | 45,570 |
def inrange(inval, minimum=-1., maximum=1.):
"""
Make sure values are within min/max
"""
inval = np.array(inval)
below = np.where(inval < minimum)
inval[below] = minimum
above = np.where(inval > maximum)
inval[above] = maximum
return inval | 45,571 |
def default_error(exception=None):
"""Render simple error page. This should be overidden in applications."""
# pylint: disable=unused-argument
return HttpResponse("There was an LTI communication error: {}".format(exception), status=500) | 45,572 |
def index_for_shop(shop_id, page):
"""List orders for that shop."""
shop = _get_shop_or_404(shop_id)
brand = brand_service.get_brand(shop.brand_id)
per_page = request.args.get('per_page', type=int, default=15)
search_term = request.args.get('search_term', default='').strip()
only_payment_sta... | 45,573 |
def create_token(author: str, password: str, token_name: str) -> Tuple[int, str]:
"""
Create an account verification token.
This token allows for avoiding HttpBasicAuth for subsequent calls.
Args:
author (`str`):
The account name.
password (`str`):
The account p... | 45,574 |
def nativeAddSlot(self, centerX, centerY, diameter, length, rot, fill, rubberMode):
"""
TOWRITE
:param `centerX`: TOWRITE
:type `centerX`: qreal
:param `centerY`: TOWRITE
:type `centerY`: qreal
:param `diameter`: TOWRITE
:type `diameter`: qreal
:param `length`: TOWRITE
:type `le... | 45,575 |
def getPositionPdf(i):
"""Return the position of the square on the pdf page"""
return [int(i/5), i%5] | 45,576 |
def plm_colombo(LMAX, x, ASTYPE=np.float):
"""
Computes fully-normalized associated Legendre Polynomials and
their first derivative using a Standard forward column method
Arguments
---------
LMAX: Upper bound of Spherical Harmonic Degrees
x: elements ranging from -1 to 1
Keyword argume... | 45,577 |
def describe_entity_recognizer(
describe_entity_recognizer_request: EntityRecognizer,
):
"""[Describe a Entity Recognizer Router]
Args:
describe_entity_recognizer_request (EntityRecognizer): [Based on Input Schema]
Raises:
error: [Error]
Returns:
[type]: [Based on Response... | 45,578 |
def tool_factory(clsname, command_name, base=CommandBase):
""" Factory for WESTPA commands."""
clsdict = {
'command_name': command_name,
}
return type(clsname, (base,), clsdict) | 45,579 |
def plot_single_sd(
sd: SpectralDistribution,
cmfs: Union[
MultiSpectralDistributions,
str,
Sequence[Union[MultiSpectralDistributions, str]],
] = "CIE 1931 2 Degree Standard Observer",
out_of_gamut_clipping: Boolean = True,
modulate_colours_with_sd_amplitude: Boolean = False,... | 45,580 |
def dur_attributes_to_dur(d_half, d_semiqvr):
"""
Convert arrays of d_hlf and d_sqv to d.
- See eq. (2) of the paper.
"""
def d_hlf_dur_sqv_to_d(d_hlf, d_sqv):
return 8 * d_hlf + d_sqv
d = d_hlf_dur_sqv_to_d(d_half, d_semiqvr)
return d | 45,581 |
def copy_dir(source, destination):
"""
Copy a directory tree and returns destination path.
Parameters:
source (string): source containing root directory path
destination (string): target root directory path
Returns:
destination (strin... | 45,582 |
def polyder_vec(p, m):
"""Vectorized version of polyder for differentiating multiple polynomials of the same degree
Parameters
----------
p : ndarray, shape(N,M)
polynomial coefficients. Each row is 1 polynomial, in descending powers of x,
each column is a power of x
m : int >=0
... | 45,583 |
def render_template(out, name, path, context, prefix = None):
"""
Render a template using tenjin.
out: a file-like object
name: name of the template
path: array of directories to search for the template
context: dictionary of variables to pass to the template
prefix: optional prefix to use f... | 45,584 |
def normalize_data(data:np.ndarray) -> np.ndarray:
"""
Subtracts the zero point of the time array and removes nans and infs
:param data: Dataset
:return: zeroed in dataset
"""
x = data[0]
y = data[1]
for i in [np.inf,-np.inf,np.nan]:
if i in y:
n = len(y[y==i])
... | 45,585 |
def _scale_fct_fixed(*args, scale=0):
"""
This is a helper function that is necessary because multiprocessing requires
a picklable (i.e. top-level) object for parallel computation.
"""
return scale | 45,586 |
def start_command(update : Update, context : CallbackContext) :
"""Answers and encourage user to start using the bot through a message"""
start_text = "سلام، تکنولوژی مورد نظرت رو برای من بفرست تا داخل کوئرا به دنبالش بگردم ، با استفاده از دستور /list میتونی ببینی از چه تکنولوژی هایی پشتیبانی میکنم 😃"
star... | 45,587 |
def authorize(vendor_api_key, user_api_key, client_class=Client):
"""Authorize use of the Leaf Data Systems API
using an API key and MME (licensee) code.
This is a shortcut function which
instantiates `client_class`.
By default :class:`cannlytics.traceability.leaf.Client` is used.
Returns:... | 45,588 |
def isclass(obj):
# type: (Any) -> bool
"""
Evaluate an object for :class:`class` type (ie: class definition, not an instance nor any other type).
"""
return isinstance(obj, (type, six.class_types)) | 45,589 |
def filter_score_grouped_pair(post_pair):
"""
Filter posts with a positive score.
:param post_pair: pair of post_id, dict with score, text blocks, and comments
:return: boolean indicating whether post has a positive score
"""
_, post_dict = post_pair
post_score = post_dict['score']
retur... | 45,590 |
def post_nodes():
"""
.. :quickref: Dev API; Update cluster nodes
**Developer documentation**
*Requires admin user.*
Update the status of cluster nodes specified in the request. The endpoint can be used to notify CC-Server after a
dead cluster node has been repaired.
**Example request**
... | 45,591 |
def to_one_hot(y_tensor, n_dims=None):
"""
Take integer y (tensor or variable) with n dims &
convert it to 1-hot representation with n+1 dims.
"""
if(n_dims is None):
n_dims = int(y_tensor.max()+ 1)
_,h,w = y_tensor.size()
y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1)
n_... | 45,592 |
def names():
"""List the names of the available satellites
Returns:
List: List of strings with the names of the available satellites
"""
return sorted(satellites().keys()) | 45,593 |
def subst_perc(ax, subst_type_counts):
"""
subst_type_counts should be list of array with type as 1st element and count as 2nd
"""
# FIXME sort by transition/transversion type. Add Ts/Tv ratio to plot
#colors = [cm.jet(1.*i/len(subst_type_counts)) for i in xrange(len(subst_type_counts))]
color... | 45,594 |
def test_restore_broken(s3_manager):
"""Tests restoring a broken snapshot raises integrity error"""
zfs_list = (
'pool@p1\t0\t19K\t-\t19K\n' # we have no pool/fs snapshots locally
'pool/fs@snap_1_f\t10.0M\t10.0M\t-\t10.0M\n'
'pool/fs@snap_2\t10.0M\t10.0M\t-\t10.0M\n'
)
zfs_manag... | 45,595 |
def read_exechours(filename, verbose = False):
"""
Read exechours_SEMESTER.txt file and return columns as '~astropy.table.Table'.
Parameters
----------
filename : string
program exec hours text file name.
Returns
-------
progtable : '~astropy.table.Table'
Program data t... | 45,596 |
def is_cond_comment(soup):
"""test whether an element is a conditional comment, return a
boolean.
:param soup: a BeautifulSoup of the code to reduce
:type soup: bs4.BeautifulSoup
"""
return isinstance(soup, bs4.element.Comment) \
and re_cond_comment.search(soup.string) | 45,597 |
def sequences_end_with_value(sequences, value, axis=-1):
"""Tests if `sequences` and with `value` along `axis`.
Args:
sequences: A matrix of integer-encoded sequences.
value: An integer value.
axis: Axis of `sequences` to test.
Returns:
A boolean `np.nadarray` that indicates for each sequences i... | 45,598 |
def download_file(service, file_id, local_fd):
"""Download a Drive file's content to the local filesystem.
Args:
service: Drive API Service instance.
file_id: ID of the Drive file that will downloaded.
local_fd: io.Base or file object, the stream that the Drive file's
contents will be... | 45,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.