content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def remove_useless_lines(text):
"""Removes lines that don't contain a word nor a number.
Args:
text (string): markdown text that is going to be processed.
Returns:
string: text once it is processed.
"""
# Useless lines
useless_line_regex = re.compile(r'^[^\w\n]*$', re.MULTILINE | re.UNICODE)
pr... | fd33cdb243b6887d11846736f922bb4e1332d549 | 3,639,719 |
def get_candidate(word):
"""get candidate word set
@word -- the given word
@return -- a set of candidate words
"""
candidates = set()
candidates |= meanslike(word)
candidates |= senselike(word)
# remove '_' and '-' between words --> candidates is a LIST now
candidates = [w.replac... | 8e2b7359f681cd96bb1ddad68cbfe77c1ae2e79b | 3,639,720 |
def _build_proxy_response(response: RawResponse, error_handler: callable) -> dict:
"""Once the application completes the request, maps the results into the format required by
AWS.
"""
try:
if response.caught_exception is not None:
raise response.caught_exception
message = ''.... | c07e52da6c6e952c35bda18b9d5600d756280f9b | 3,639,721 |
def reduce_any(input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
Wrapper around the tf.reduce_any to handle argument keep_dims
"""
return reduce_function(tf.reduce_any, input_tensor, axis=axis,
keepdims=keepdims, name=name,
... | bdf25f573caef2d9c0926c92d8ce4b4a3b682775 | 3,639,723 |
def get_customer_profile_ids():
"""get customer profile IDs"""
merchantAuth = apicontractsv1.merchantAuthenticationType()
merchantAuth.name = constants.apiLoginId
merchantAuth.transactionKey = constants.transactionKey
CustomerProfileIdsRequest = apicontractsv1.getCustomerProfileIdsRequest()
Cus... | ba6cb076870961b4ab226b2aeb3ab07b1b5eb848 | 3,639,724 |
from typing import List
def compare_alignments_(prediction: List[dict], ground_truth: List[dict], types: List[str]) -> (float, float, float):
"""
Parameters
----------
prediction: List of dictionaries containing the predicted alignments
ground_truth: List of dictionaries containing the ground trut... | 57648544c152bff0acc52271d453b58a0d8e8cad | 3,639,725 |
import inspect
def shim_unpack(
unpack_fn, # type: TShimmedFunc
download_dir, # type str
tempdir_manager_provider, # type: TShimmedFunc
ireq=None, # type: Optional[Any]
link=None, # type: Optional[Any]
location=None, # type Optional[str],
hashes=None, # type: Optional[Any]
progr... | 561d473584da5f96cbffadb543cee129c9c6e0ef | 3,639,726 |
def xavier_uniform(x):
"""Wrapper for torch.nn.init.xavier_uniform method.
Parameters
----------
x : torch.tensor
Input tensor to be initialized. See torch.nn.init.py for more information
Returns
-------
torch.tensor
Initialized tensor
"""
return init.xavier_unifor... | f407fa3e35d1bd708e6cfe4b003a788bed4eb443 | 3,639,727 |
def create_test_data(site, start=None, end="now", interval=5, units='minutes' , val=50, db='test_db', data={}):
"""
data = {'R1':[0,0,0,..],'R2':[0,0,123,12,...]...} will not generate date but use fixed data set
if val is not set random data will be generated if data is not existing
"""
... | 56e5f65650a2fb1eb2a829d9443cd0a588402c3a | 3,639,729 |
def Nmin(e, dz, s, a, a_err):
"""Estimates the minimum number of independent structures
to detect a difference in dN/dz w/r to a field value given
by dNdz|field = a +- a_err, at a statistical significance s,
using a redshift path of dz per structure"""
e = np.array(e).astype(float)
dz = np.array... | c603f90e35802b6b7401c14abda3bb350d0e6941 | 3,639,730 |
import string
def remove_punctuation(list_of_string, item_to_keep=""):
"""
Remove punctuation from a list of strings.
Parameters
----------
- list_of_string : a dataframe column or variable containing the text stored as a list of string sentences
- item_to_keep : a string of punctuation ... | cb9190bc160f8e725479b531afab383c6857ceac | 3,639,731 |
import requests
import pickle
def save_sp500_tickers(force_download=False):
"""Get the S&P 500 tickers from Wikipedia
Parameters
----------
force_download : bool
if True, force redownload of data
Returns
-------
tickers : pandas.DataFrame
The S&P50... | 94ddf34acbda542fe039f988887b904bb2ac9da4 | 3,639,732 |
def get_search_keywords(testcase):
"""Get search keywords for a testcase."""
crash_state_lines = testcase.crash_state.splitlines()
# Use top 2 frames for searching.
return crash_state_lines[:2] | 15c1611aeff33f9d8bba843f076b31abfb4023ba | 3,639,733 |
def make_protein_index(proteins):
"""Indexes proteins
"""
prot_index = {}
skip = set(['sp', 'tr', 'gi', 'ref', ''])
for i, p in enumerate(proteins):
accs = p.accession.split('|')
for acc in accs:
if acc in skip:
continue
prot_index[acc] = i
... | be54ca3a123fe13efbb8c694187dd34d944fd654 | 3,639,734 |
def jvp_solve_Hz(g, Hz, info_dict, eps_vec, source, iterative=False, method=DEFAULT_SOLVER):
""" Gives jvp for solve_Hz with respect to eps_vec """
# construct the system matrix again and the RHS of the gradient expersion
A = make_A_Hz(info_dict, eps_vec)
ux = spdot(info_dict['Dxb'], Hz)
uy = sp... | 0d861f9c6a899c70da7d095cb6ac436586e75bdd | 3,639,735 |
from typing import Union
def encode(X: Union[tf.Tensor, np.ndarray], encoder: keras.Model, **kwargs) -> tf.Tensor:
"""
Encodes the input tensor.
Parameters
----------
X
Input to be encoded.
encoder
Pretrained encoder network.
Returns
-------
Input encoding.
... | a97abdc611643e4cd1ed944ff27ef7402e824acb | 3,639,736 |
def _step2(input):
"""
_step2 - function to apply step2 rules
Inputs:
- input : str
- m : int
Measurement m of c.v.c. sequences
Outputs:
- input : str
"""
# ational -> ate
if input.endswith('ational') and _compute_m(input[:-7]) > 0:
return input[:-1 * len('ational')] + 'ate'
# tional -> tion
elif in... | 5181d55de4ef7c33778dfbe80707e4e621018d5c | 3,639,737 |
from typing import cast
def compute_annualized_volatility(srs: pd.Series) -> float:
"""
Annualize sample volatility.
:param srs: series with datetimeindex with `freq`
:return: annualized volatility (stdev)
"""
srs = hdataf.apply_nan_mode(srs, mode="fill_with_zero")
ppy = hdataf.infer_samp... | 517d56e53885fdcb5eee3ed0fa3acae766d9c7e2 | 3,639,738 |
from datetime import datetime
def json_sanitized(value, stringify=stringified, dt=str, none=False):
"""
Args:
value: Value to sanitize
stringify (callable | None): Function to use to stringify non-builtin types
dt (callable | None): Function to use to stringify dates
none (str ... | 6f50e3bb5a07417b05cb95813d2cc5a89ad12a2b | 3,639,739 |
def rescan_organization_task(task, org, allpr, dry_run, earliest, latest):
"""A bound Celery task to call rescan_organization."""
meta = {"org": org}
task.update_state(state="STARTED", meta=meta)
callback = PaginateCallback(task, meta)
return rescan_organization(org, allpr, dry_run, earliest, latest... | 2241bf6630bdd63c231f011708ac392c3d1a8234 | 3,639,740 |
def python(cc):
"""Format the character for a Python string."""
codepoint = ord(cc)
if 0x20 <= codepoint <= 0x7f:
return cc
if codepoint > 0xFFFF:
return "\\U%08x" % codepoint
return "\\u%04x" % codepoint | b0c2042c653043c0831a35ffc13d73850e29af2f | 3,639,741 |
import logging
def stop_execution(execution_id):
"""
Stop the current workflow execution.
swagger_from_file: docs/stop.yml
"""
name = execution_id # str | the custom object's name
body = kubernetes.client.V1DeleteOptions() # V1DeleteOptions |
grace_period_seconds = 56 # int | The durati... | d7d4264a81f106de31c49d5825de114a20f79966 | 3,639,742 |
def reshape_signal_batch(signal):
"""Convert the signal into a standard batch shape for use with cochleagram.py
functions. The first dimension is the batch dimension.
Args:
signal (array): The sound signal (waveform) in the time domain. Should be
either a flattened array with shape (n_samples,), a row ... | 344ce1a9a695e99fa470a5d849afb40bc381c9df | 3,639,743 |
import scipy
import itertools
def tryallmedoids(dmat, c, weights=None, potential_medoid_inds=None, fuzzy=True, fuzzyParams=('FCM', 2)):
"""Brute force optimization of k-medoids or fuzzy c-medoids clustering.
To apply to points in euclidean space pass dmat using:
dmat = sklearn.neighbors.DistanceMetric.ge... | 34ba39d57bdce6b52b3c5e8eef085ef928d02038 | 3,639,744 |
from typing import Union
def human_timedelta(s: Union[int, float]) -> str:
"""Convert a timedelta from seconds into a string using a more sensible unit.
Args:
s: Amount of seconds
Returns:
A string representing `s` seconds in an easily understandable way
"""
if s >= MONTH_SECONDS... | 84725ecf4e4d59d423505978b8255f96a6483cd0 | 3,639,745 |
from functools import reduce
def rate_cell(cell, board, snake, bloom_level=4):
""" rates a cell based on proximity to other snakes, food, the edge of the board, etc """
cells = []
# Get all the cells of "bloom_level" number of circles surrounding the given cell.
for x in range(-bloom_level, bloom_lev... | ab78b4b822789b32e2a768dcb9d55f5398b34a13 | 3,639,746 |
def edges_are_same(a, b):
"""
Function to check if two tuple elements (src, tgt, val) correspond
to the same directed edge (src, tgt).
Args:
tuple_elements : a = (src, val, val) and b = (src, val, val)
Returns:
True or False
"""
if a[0:2] == b[0:2]:
return True
... | 04c4d414402a57cafa0028d0ecd140bedd2539d7 | 3,639,747 |
def conv_mrf(A, B):
"""
:param A: conv kernel 1 x 120 x 180 x 1 (prior)
:param B: input heatmaps: hps.batch_size x 60 x 90 x 1 (likelihood)
:return: C is hps.batch_size x 60 x 90 x 1
"""
B = tf.transpose(B, [1, 2, 3, 0])
B = tf.reverse(B, axis=[0, 1]) # [h, w, 1, b], we flip kernel to get c... | 5bca01b656b135f20325441ebcbcfac883627565 | 3,639,748 |
from typing import Dict
from typing import Tuple
def get_alert_by_id_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]:
"""Get alert by id and return outputs in Demisto's format
Args:
client: Client object with request
args: Usually demisto.args()
Returns:
Outputs
... | 74208c66627e2441ff62ad6b4207844241ab7cd6 | 3,639,749 |
def close_issues() -> list[res.Response]:
"""Batch close issues on GitHub."""
settings = _get_connection_settings(CONFIG_MANAGER.config)
try:
github_service = ghs.GithubService(settings)
except ghs.GithubServiceError as gse:
return [res.ResponseFailure(res.ResponseTypes.RESOURCE_ERROR, g... | ac59a72b893ebc91090d3ba38a1cbf6cb8844be1 | 3,639,750 |
def _invert_lambda(node: tn.Node) -> tn.Node:
"""Invert a diagonal lambda matrix. """
tensor = node.get_tensor()
assert _is_diagonal_matrix(tensor)
diagonal = tensor.diagonal()
return tn.Node(np.diag(1/diagonal)) | b5c06728b1e88bedec7d19591f0aa4823e90f412 | 3,639,751 |
def map_field_name_to_label(form):
"""Takes a form and creates label to field name map.
:param django.forms.Form form: Instance of ``django.forms.Form``.
:return dict:
"""
return dict([(field_name, field.label)
for (field_name, field)
in form.base_fields.items()]) | dfc2779f498fb479553602a72d9520d398746302 | 3,639,752 |
from typing import Callable
from typing import List
def solve_compound_rec(
recurrence_func: Callable,
parameter_list: List[float],
std_of_compound_dist: float,
max_mRNA_copy_number: int,
recursion_length: int,
index_compound_parameter: int = 3,
compounding_distribution: str = "normal",
... | 22e9106872ed185cf635fe958707da4244eee60c | 3,639,753 |
def create_brand():
"""
Creates a new brand with the given info
:return: Status of the request
"""
check = check_brand_parameters(request)
if check is not None:
return check
name = request.json[NAME]
brand = Brand.query.filter(Brand.name == name).first()
if brand is not Non... | 5c745aa1050b574cc659cf17bc06d1bdeb424b13 | 3,639,754 |
def feature_contained(boundary: geo, **kwargs):
"""Analyse containment for all features within a single-layer vector file according to a Geometry
and return multiple GeoJSON files."""
geom, prop = kwargs["geom"], kwargs["prop"]
if isinstance(geom, geo.Polygon):
prop["valid"] = boundary.contains(... | 5fbad0dbb915dfa5e422bfeb356a63d4290df07d | 3,639,756 |
import time
def compute(n=26):
""" Computes 2 to the power of n and returns elapsed time"""
start = time.time()
res = 0
for i in range(2**n):
res += 1
end = time.time()
dt = end - start
print(f'Result {res} in {dt} seconds!')
return dt | d816c587302830f0acd20a59905c8634fcf20b49 | 3,639,757 |
from re import S
import mpmath
def _real_to_rational(expr, tolerance=None, rational_conversion='base10'):
"""
Replace all reals in expr with rationals.
Examples
========
>>> from sympy import Rational
>>> from sympy.simplify.simplify import _real_to_rational
>>> from sympy.abc import x
... | ce685079459e3bc6e19decc2f22c3bc8198411c0 | 3,639,758 |
import multiprocessing
import itertools
import functools
def run(block, epsilon, ratio, prng, alpha=2, beta=1.2, gamma=1.0, theta=None, verbose=False):
"""Run HDPView
1st phase, divide blocks.
2nd phase, perturbation.
Prepare parameters and execute HDPView
Args:
block (CountTa... | 51a7f9f8a739de76b3c8b188a2d0495f42be1cbe | 3,639,759 |
def wait_for_view(class_name):
"""
Waits for a View matching the specified class. Default timeout is 20 seconds.
:param class_name:the {@link View} class to wait for
:return:{@code true} if the {@link View} is displayed and {@code false} if it is not displayed before the timeout
"""
return get_... | 8829f1af924540d92923c1ce44742f8d4d223ca8 | 3,639,760 |
def _create_table():
"""helper for crc calculation"""
table = []
for i in range(256):
k = i
for _ in range(8):
if k & 1:
k = (k >> 1) ^ 0xEDB88320
else:
k >>= 1
table.append(k)
return table | 830317e62dcfb7bca63f1186b46a2882e0bb399f | 3,639,761 |
def average_syllables(verses):
"""
Takes a list of verses
Returns the mean number of syllables among input verses
"""
verse_count = len(verses)
syll_counts = list(map(count_syllables, verses))
syll_count = sum(syll_counts)
return syll_count / verse_count | 4cb4d53431b5ccaa2c4ca08083242089feb61be5 | 3,639,762 |
def _create_subplots_if_needed(ntotal,
ncols=None,
default_ncols=1,
fieldorder='C',
avoid_single_column=False,
sharex=False,
sharey=Fa... | d164cd0d73632fcbcb38face930e2aa5c7300728 | 3,639,763 |
def template_file_counter(session, templates, fetch_count=False):
"""Create template file counter."""
file_counts = {}
default_count = None
if fetch_count:
file_counts = TemplatesDAO.query_file_counts(session=session, templates=templates)
default_count = 0
def counter(template: Temp... | 9a931e11385cba0c7f2968740cc8059da341cd50 | 3,639,764 |
def _init_matrices_nw(aln1, aln2, gap_open_penalty, gap_extend_penalty):
"""initialize score matrix and traceback matrix for global alignment
Parameters
----------
aln1 : list
list of activities, which is the first sequence to be aligned
aln2 : list
list of activities, which is the ... | 46c4426a5570ed9dceb0409b5bd4ac2ccb8efb10 | 3,639,765 |
import re
def parse_path_params(end_point_path):
"""Parse path parameters."""
numeric_item_types = ['Lnn', 'Zone', 'Port', 'Lin']
params = []
for partial_path in end_point_path.split('/'):
if (not partial_path or partial_path[0] != '<' or
partial_path[-1] != '>'):
c... | 895c3b3663c33a6883ba34d7bbfb20de1491910d | 3,639,766 |
def read_pid_stat(pid="self"):
"""
Returns system process stat information.
:param pid: The process ID.
:returns: The system stat information.
:rtype: dict
"""
with open("/proc/%s/stat" % (pid,), "rb") as f:
stat = f.readline().split()
return {
"utime": int(stat[13]),
... | 5ec6b21b09372e71e6dcf8c60f418bcbc4beee64 | 3,639,767 |
def simple_split_with_list(x, y, train_fraction=0.8, seed=None):
"""Splits data stored in a list.
The data x and y are list of arrays with shape [batch, ...].
These are split in two sets randomly using train_fraction over the number of
element of the list. Then these sets are returned with
the arra... | c99ae6507b934b42577949ee3a9226e68e870da9 | 3,639,768 |
def get_star(star_path, verbose=False, recreate=False):
"""Return a varconlib.star.Star object based on its name.
Parameters
----------
star_path : str
A string representing the name of the directory where the HDF5 file
containing a `star.Star`'s data can be found.
Optional
---... | f6ccd804e5998e42a0fb4d1d4368e2d65244d855 | 3,639,770 |
from datetime import datetime
def get_relative_days(days):
"""Calculates a relative date/time in the past without any time offsets.
This is useful when a service wants to have a default value of, for example 7 days back. If an ISO duration format
is used, such as P7D then the current time will be factore... | 58e429708e7d1c3cbda88c09bfb978f32cb1892a | 3,639,773 |
def find_pending_trade(df):
""" Find the trade value according to its sign like negative number means Sell type
or positive number means Buy """
p_df = pd.DataFrame()
p_df['Type'] = df['Buy_Qty'] - df['Sell_Qty']
return p_df['Type'].map(lambda val: trade_type_conversion(val)) | 1e764929cb047b6d8314732902dcc273176c924b | 3,639,774 |
def rtri(x, a, b):
"""Convolution of rect(ax) with tri(bx)."""
assert a > 0
assert b > 0
return b*(step2(x + 1/(2*a) + 1/b) - 2*step2(x + 1/(2*a)) + step2(x + 1/(2*a) - 1/b) - step2(x - 1/(2*a) + 1/b) + 2*step2(x - 1/(2*a)) - step2(x - 1/(2*a) - 1/b)) | 74745bf680507a2d3627c31c14ccc24db4b2d2d1 | 3,639,775 |
def make_xgboost_predict_extractor(
eval_shared_model: tfma.EvalSharedModel,
eval_config: tfma.EvalConfig,
) -> extractor.Extractor:
"""Creates an extractor for performing predictions using a xgboost model.
The extractor's PTransform loads and runs the serving pickle against
every extract yielding a copy... | 01c44814023e2c960ec695ee8a7282f2a9d0b21f | 3,639,776 |
def training_dataset() -> Dataset:
"""Creating the dataframe."""
data = {
"record1": [
{"@first_name": "Hans", "@last_name": "Peter"},
{"@first_name": "Heinrich", "@last_name": "Meier"},
{"@first_name": "Hans", "@last_name": "Peter"},
],
"record2": [
... | 1d3ecc780044036aa8f8425abf8dba556649af98 | 3,639,777 |
def get_full_frac_val(r_recalc,fs,diff_frac=0,bypass_correction=0):
"""
Compute total offset in number of samples, and also fractional sample correction.
Parameters
----------
r_recalc : float
delay.
fs : float
sampling frequency.
diff_frac : 0
[unused] 0 b... | 23bf8326472844b16c87ac28e1065156bf20ce8b | 3,639,779 |
import inspect
def get_code():
"""
returns the code for the min cost path function
"""
return inspect.getsource(calculate_path) | bad3e06b11b0897b9225ffc9ab6dc81972f4442b | 3,639,780 |
import functools
def box_net(images,
level,
num_anchors,
num_filters,
is_training,
act_type,
repeats=4,
separable_conv=True,
survival_prob=None,
strategy=None,
data_format='channels_last'):
"""Box... | 8caab72f716c0f754efb82467556a5b016d2f72e | 3,639,781 |
from typing import Set
def get_distance_to_center(
element: object, centers: "Set[object]", distance_function: "function"
) -> float:
"""
Returns the distance from the given point to its center
:param element: a point to get the distance for
:param centers: an iteratable of the center points
... | bd4a400e5a98711d00c5c236ce02945bd2014719 | 3,639,782 |
def auto_delete_file_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem when corresponding
`Worksheet` object is updated with a new file.
"""
if not instance.pk:
return False
db_obj = Worksheet.objects.get(pk=instance.pk)
exists = True
try:
old_f... | 2ab584fffbe2224109c4d4ea0446c22650df493f | 3,639,783 |
def clean_immigration_data(validPorts: dict, immigration_usa_df: psd.DataFrame, spark: pss.DataFrame) -> psd.DataFrame:
"""[This cleans immigration data in USA. It casts date of immigrant entry, city of destination, and port entry.]
Args:
validPorts (dict): [dictionery that includes valid entry ports i... | 8746f0f4e35745d653549c32c5a804422d22c588 | 3,639,784 |
from pathlib import Path
def prepare(args: dict, overwriting: bool) -> Path:
"""Load config and key file,create output directories and setup log files.
Args:
args (dict): argparser dictionary
Returns:
Path: output directory path
"""
output_dir = make_dir(args, "results_tmp", "ag... | dca02f4180e91423fa61e8da36e9ac095dbe3ca4 | 3,639,785 |
def dd_wave_function_array(x, u_array, Lx):
"""Returns numpy array of all second derivatives
of waves in Fourier sum"""
coeff = 2 * np.pi / Lx
f_array = wave_function_array(x, u_array, Lx)
return - coeff ** 2 * u_array ** 2 * f_array | d815afe12916643c46fcc7b8f108ce5aad840e3b | 3,639,786 |
def handle_health_check():
"""Return response 200 for successful health check"""
return Response(status=200) | 3ff055a7dc5e1318dd0e283ace87399c54e361b2 | 3,639,788 |
def pow(x, n):
""" pow(x, n)
Power function.
"""
return x**n | 09d62a68607bf0dab8b380a0c3ee58c6ed4497d6 | 3,639,789 |
def download_cad_model():
"""Download cad dataset."""
return _download_and_read('42400-IDGH.stl') | 1f7aad5ed9c8f62ffef16cb3f44207b83aced204 | 3,639,790 |
def dot_product(u, v):
"""Computes dot product of two vectors u and v, each represented as a tuple
or list of coordinates. Assume the two vectors are the same length."""
output = 0
for i in range(len(u)):
output += (u[i]*v[i])
return output | 6362776bef32870d3b380aecbb2037483e049092 | 3,639,791 |
from datetime import datetime
def precise_diff(
d1, d2
): # type: (typing.Union[datetime.datetime, datetime.date], typing.Union[datetime.datetime, datetime.date]) -> PreciseDiff
"""
Calculate a precise difference between two datetimes.
:param d1: The first datetime
:type d1: datetime.datetime or... | 21c2a2a275ce23e8282c0563218d4aacc1f0accd | 3,639,792 |
def subset_lists(L, min_size=0, max_size=None):
"""Strategy to generate a subset of a `list`.
This should be built in to hypothesis (see hypothesis issue #1115), but was rejected.
Parameters
----------
L : list
List of elements we want to get a subset of.
min_size : int
Minimum... | 1ad343ed6459c12b6c454c71505e8cfa04e9e36e | 3,639,794 |
def DCNPack(x, extra_feat, out_channels, kernel_size=(3, 3), strides=(1, 1), padding='same', dilations=(1, 1),
use_bias=True, num_groups=1, num_deform_groups=1, trainable=True, dcn_version='v2', name='DCN'):
"""Deformable convolution encapsulation that acts as normal convolution layers."""
with tf.v... | 091669ff8608c2783916d042bac2b2756ca25973 | 3,639,795 |
def endtiming(fn):
"""
Decorator used to end timing.
Keeps track of the count for the first and second calls.
"""
NITER = 10000
def new(*args, **kw):
ret = fn(*args, **kw)
obj = args[0]
if obj.firststoptime == 0:
obj.firststoptime = time.time()
elif ob... | 493fd06b0c28ef1c8c4f3c38c555cf5e52013d80 | 3,639,796 |
def CreateRailFrames(thisNurbsCurve, parameters, multiple=False):
"""
Computes relatively parallel rail sweep frames at specified parameters.
Args:
parameters (IEnumerable<double>): A collection of curve parameters.
Returns:
Plane[]: An array of planes if successful, or an empty array ... | bf62e197d6b7cb83453b43ce441eb062000ca069 | 3,639,797 |
def news(stock):
"""analyzes analyst recommendations using keywords and assigns values to them
:param stock: stock that will be analyzed
:return recommendations value"""
stock = yf.Ticker(str(stock))
reco = str(stock.recommendations) # Stands for recomend
reco = reco.split()
reco.revers... | 2385f5c212c8802e6572b6efe69c1c791a68c261 | 3,639,798 |
def get_pulse_coefficient(pulse_profile_dictionary, tt):
"""
This function generates an envelope that smoothly goes from 0 to 1, and back down to 0.
It follows the nomenclature introduced to me by working with oscilloscopes.
The pulse profile dictionary will contain a rise time, flat time, and fall tim... | 1db21359bbbcec44214752ecb5c08a6ee0592593 | 3,639,799 |
def parse_variable_char(packed):
""" Map a 6-bit packed char to ASCII """
packed_char = packed
if packed_char == 0:
return ""
if 1 <= packed_char <= 10:
return chr(ord('0') - 1 + packed_char)
elif 11 <= packed_char <= 36:
return chr(ord('A') - 11 + packed_char)
elif 37 <=... | e4ff95bca48ae97a22c20dda4fd82e082c32be27 | 3,639,800 |
def analyse(tx):
"""
Analyses a given set of features. Marks the features with zero
variance as the features to be deleted from the data set. Replaces
each instance of a null(-999) valued feature point with the mean
of the non null valued feature points. Also handles the outliers
by clipping th... | 2bfd46b2cb70da9822a4a86f588e187ab941ea88 | 3,639,802 |
import regex
def validate_word_syntax(word):
"""
This function is designed to validate that the syntax for
a string variable is acceptable.
A validate format is English words that only contain alpha
characters and hyphens.
:param word: string to validate
:return: boolean true or false
... | 47b732ffc0c2c91c5a092d7367b49bb8946697be | 3,639,803 |
def next_page(context):
"""
Get the next page for signup or login.
The query string takes priority over the template variable and the default
is an empty string.
"""
if "next" in context.request.GET:
return context.request.GET["next"]
if "next" in context.request.POST:
retu... | 6abc1c8ef260366e53f335a27ee42f0356c91b63 | 3,639,804 |
import numpy
def make_train_test_sets(input_matrix, label_matrix, train_per_class):
"""Return ((training_inputs, training_labels), (testing_inputs, testing_labels)).
Args:
input_matrix: attributes matrix. Each row is sample, each column is attribute.
label_matrix: labels matrix. Each row is s... | bd71f48ed9405a89dfa42b3cb6cfe45b064a6b4d | 3,639,805 |
def add_coords_table(document: Document, cif: CifContainer, table_num: int):
"""
Adds the table with the atom coordinates.
:param document: The current word document.
:param cif: the cif object from CifContainer.
:return: None
"""
atoms = list(cif.atoms())
table_num += 1
headline = "... | 6b351138624bd530739d199898fbc4f0cfb56bb1 | 3,639,806 |
import numpy
def bz(xp, yp, zp, spheres):
"""
Calculates the z component of the magnetic induction produced by spheres.
.. note:: Input units are SI. Output is in nT
Parameters:
* xp, yp, zp : arrays
The x, y, and z coordinates where the anomaly will be calculated
* spheres : list o... | 16d85978e50de16ab6af91c6ee83392b7fa43e3e | 3,639,807 |
def update_stocks():
"""
method to update the data (used by the spark service)
:return:
"""
global stocks
body = request.get_json(silent=True)
'''
{
"data" : [
{
"symbol" : "string",
"ask_price" : "string",
"last_sale_t... | f1db3a9a1ba7cd20aad2e8ddc0bea66997ef11dd | 3,639,808 |
from typing import Iterable
from re import T
from typing import Sequence
import itertools
def chunks_from_iterable(iterable: Iterable[T], size: int) -> Iterable[Sequence[T]]:
"""Generate adjacent chunks of data"""
it = iter(iterable)
return iter(lambda: tuple(itertools.islice(it, size)), ()) | 76bf5a8742f082da860caec477c72338fcc4510e | 3,639,809 |
from typing import Dict
def summary_overall(queryset: QuerySet) -> Dict[str, Decimal]:
"""Summarizes how much money was spent"""
amount_sum = sum([value[0] for value in queryset.values_list('amount')])
return {'overall': amount_sum} | 6d2d276ca891f99ac171001c99ff0d90b530a5b1 | 3,639,811 |
import torch
def _get_trained_ann(train_exo: "ndarray", train_meth: "ndarray") -> "QdaisANN2010":
"""Return trained ANN."""
train_data = BiogasData(train_exo, train_meth)
ann = QdaisANN2010(train_data.train_exo.shape[1])
try:
ann.load_state_dict(torch.load("./assets/ann.pt"))
except IOErro... | 08bd38450e217c00643ab7fefe1c1860fc5d1ebf | 3,639,812 |
def pi_float():
"""native float"""
lasts, t, s, n, na, d, da = 0, 3.0, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
return s | 8a6a6a5942ddd61ecdf65b782bb2fc0f0519ddb5 | 3,639,813 |
def iso3_to_country(iso3):
""" Take user input and convert it to the short version of the country name """
if iso3 == 'Global':
return 'Global'
country = coco.convert(names=iso3, to='name_short')
return country | 2c2904ba8befe802d531b371f046ff4a3ba4db22 | 3,639,814 |
def test_bivariate(N, n_neighbors, rng, noise):
"""Test with bivariate normal variables"""
mu = np.zeros(2)
cov = np.array([[1., 0.8], [0.8, 1.0]])
xy_gauss = rng.multivariate_normal(mu, cov, size=N)
x, y = xy_gauss[:, 0], xy_gauss[:, 1]
z = rng.normal(size=N)
cmi_analytic = -0.5 * np.log(d... | 827b968c6333402066d1fa4282ce90c2cdb175f5 | 3,639,815 |
import math
def osm_tile_number_to_latlon(xtile, ytile, zoom):
""" Returns the latitude and longitude of the north west corner of a tile, based on the tile numbers and the zoom level"""
n = 2.0 ** zoom
lon_deg = xtile / n * 360.0 - 180.0
lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
lat_deg = mat... | 8afbbb218835311bebcfe6a0d611e0e62bfcffc3 | 3,639,816 |
def prodtab_111():
"""
produces angular distance from [1,1,1] plane with other planes up to (321) type
"""
listangles_111 = [anglebetween([1, 1, 1], elemref) for elemref in LISTNEIGHBORS_111]
return np.array(listangles_111) | cb49c087e5b5090bca788f9c33862c37c42c2f1c | 3,639,817 |
def cuda_cos(a):
""" Trigonometric cosine of GPUArray elements.
Parameters:
a (gpu): GPUArray with elements to be operated on.
Returns:
gpu: cos(GPUArray)
Examples:
>>> a = cuda_cos(cuda_give([0, pi / 4]))
array([ 1., 0.70710678])
>>> type(a)
<class 'p... | e411bde08f133c8f9109ff5815f44a3ff5262282 | 3,639,818 |
from typing import Counter
def top_diffs(spect: list, num_acids: int) -> list:
"""Finds at least num_acids top differences in [57, 200]
Accepts ties
:param spect: a cyclic spectrum to find differences in
:type spect: list (of ints)
:type keep: int
:returns: the trimmed leaderboard
:rtype... | 1ca2b08f6ecbf69b1ab2189b1cbbff9b4e1c2e8d | 3,639,819 |
import typing
def form_sized_range(range_: Range, substs) -> typing.Tuple[
SizedRange, typing.Optional[Symbol]
]:
"""Form a sized range from the original raw range.
The when a symbol exists in the ranges, it will be returned as the second
result, or the second result will be none.
"""
if not... | ac0d4299198f0e5611acb8167107f56f2b49bb0f | 3,639,820 |
def line_integrals(vs, uloc, vloc, kind="same"):
"""
calculate line integrals along all islands
Arguments:
kind: "same" calculates only line integral contributions of an island with itself,
while "full" calculates all possible pairings between all islands.
"""
if kind == "sam... | 8808c3afd4374465bd64aa0db658d8843a74a4da | 3,639,822 |
def crop_black_borders(image, threshold=0):
"""Crops any edges below or equal to threshold
Crops blank image to 1x1.
Returns cropped image.
"""
if len(image.shape) == 3:
flatImage = np.max(image, 2)
else:
flatImage = image
assert len(flatImage.shape) == 2
rows = np.wh... | 77ec884f4f173844f5d5124a29bb94eb641e25ec | 3,639,823 |
def change_password():
"""Allows user to change password"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# If password and confirmation don't match, accuse error
if request.form.get("new_password... | afff43726d3e30a1ea09af20df1099b00c14b843 | 3,639,824 |
def add_placeholders(components):
"""Add placeholders for missing DATA/INSTANCE components"""
headers = [s[:2] for s in components]
for prefix in ("CD", "CR"):
if prefix not in headers:
components.append(prefix + ("C" * 11))
return components | 303f1590042acc60aa753e5e317417de01fafafc | 3,639,825 |
from ..items import HieroClipItem
def clipsToHieroClipItems(clips):
"""
@itemUsage hiero.items.HieroClipItem
"""
clipItems = []
if clips:
for c in clips:
i = HieroClipItem(c)
clipItems.append(i)
return clipItems | bf4c6aaff649796cc1a24eb7ba3102fb01178ab3 | 3,639,826 |
import hashlib
def md5(s, raw_output=False):
"""Calculates the md5 hash of a given string"""
res = hashlib.md5(s.encode())
if raw_output:
return res.digest()
return res.hexdigest() | 238c2a6c6b06a046de86e514698c7ef5622f770b | 3,639,827 |
def _get_pk_message_increase(cache_dict: dict,
project_list: list) -> str:
"""根据项目列表构建增量模式下PK播报的信息.
### Args:
``cache_dict``: 增量计算的基础.\n
``project_list``: PK的项目列表.\n
### Result:
``message``: PK进展的播报信息.\n
"""
amount_dict = _get_pk_amount(project_list)
incr... | 9343626fe8208e5e08c39abda9c6b26252ac6b2b | 3,639,829 |
def flatten(dic, keep_iter=False, position=None):
"""
Returns a flattened dictionary from a dictionary of nested dictionaries and lists.
`keep_iter` will treat iterables as valid values, while also flattening them.
"""
child = {}
if not dic:
return {}
for k, v in get_iter(dic):
... | 4597a0330468e955cadda37f89f73bed7db1ecb5 | 3,639,830 |
import json
def game_get_state():
"""The ``/game/state`` endpoint requires authentication and expects no
other arguments.
It can be reached at ``/game/state?secret=<API_SECRET>``.
It is used to retrieve the current state of the game.
The JSON response looks like::
{
"state_id... | b5b3bda433764413fb6116b5b8f13d6e9dfef866 | 3,639,831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.