content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def relu(x):
"""The rectifier activation function. Only activates if argument x is
positive.
Args:
x (ndarray): weighted sum of inputs
"""
# np.clip(x, 0, np.finfo(x.dtype).max, out=x)
# return x
return np.where(x >= 0, x, 0) | 61b7a4ce252c72dd69251a8783c572c8128a01c5 | 3,649,046 |
def k_shortest_paths(G, source, target, k=1, weight='weight'):
"""Returns the k-shortest paths from source to target in a weighted graph flux_graph.
Parameters
----------
flux_graph : NetworkX graph
source : node
Starting node
target : node
Ending node
k : integer, o... | 68918c78b1f33c07cd3494286a00b1c020256b56 | 3,649,047 |
def allowed_file(filename):
"""
Check the image extension
Currently, only support jpg, jpeg and png
"""
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS | 635f89b33c9150b5d7b68415bb85bb8c1d644d1f | 3,649,048 |
def classical_gaussian_kernel(k, sigma):
"""
A function to generate a classical Gaussian kernel
:param k: The size of the kernel, an integer
:param sigma: variance of the gaussian distribution
:return: A Gaussian kernel, a numpy array of shape (k,k)
"""
w = np.linspace(-(k - 1) / 2, (k - 1)... | e1a94134e465f72a7d49e8bb950eb7a8ba97ac54 | 3,649,050 |
def collection_to_csv(collection):
"""
Upload collection value to CSV file
:param collection: Collection
:return: None
"""
print("collection_to_csv")
final_df = pd.DataFrame()
try:
dict4json = []
n_documents = 0
for document in collection.get():
result... | 5d62e0fe1eebb190be47a05d822b8714d396125f | 3,649,051 |
import six
def validate_hatch(s):
"""
Validate a hatch pattern.
A hatch pattern string can have any sequence of the following
characters: ``\\ / | - + * . x o O``.
"""
if not isinstance(s, six.text_type):
raise ValueError("Hatch pattern must be a string")
unique_chars = set(s)
... | 4ddf056dab2681759a462005effc4ae5488a4461 | 3,649,052 |
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.cli.core.profiles import ResourceType
def iot_hub_service_factory(cli_ctx, *_):
"""
Factory for importing deps and getting service client resources.
Args:
cli_ctx (knack.cli.CLI): CLI context.
*_ : all o... | a38ae4a7fedaf8dcbaccba0873e4f519cb51af17 | 3,649,053 |
def filter_example(config, example, mode="train"):
"""
Whether filter a given example according to configure.
:param config: config contains parameters for filtering example
:param example: an example instance
:param mode: "train" or "test", they differs in filter restrictions
:return: boolean
... | 9c49990fe36c0a82d0a99a62fe810a19cd5a8749 | 3,649,054 |
def _dict_flatten(data):
"""Return flattened dict of input dict <data>.
After https://codereview.stackexchange.com/revisions/21035/3
Parameters
----------
data : dict
Input dict to flatten
Returns
-------
fdata : dict
Flattened dict.
"""
def expand(key, valu... | a1db4a552ced44efa45fe4f86fbfe04871463356 | 3,649,055 |
def merkleroot(elements):
"""
Args:
elements (List[str]): List of hashes that make the merkletree.
Returns:
str: The root element of the merkle tree.
"""
return Merkletree(elements).merkleroot | cd5d1e530fda62f9b92a51a03f5fd2cbbe6a9e62 | 3,649,056 |
def category_start(update, context):
"""Separate function for category selection to filter the options with inline keyboard."""
update.message.reply_text(
"Choose a Group",
reply_markup=create_category_inline(trx_categories.keys(), "group_sel"),
)
return CATEGORY_REPLY_CHOOSE_TRX_OPTS | cfc299d8b81785d8418bfb4c280cf88e4137448b | 3,649,057 |
def create_player(mode, race, char_name):
""" Create the player's character """
# Evil
if mode == 2:
if race == 1:
player = character.Goblin(char_name, 1, app)
elif race == 2:
player = character.Orc(char_name, 1, app)
elif race == 3:
player = chara... | 30e143f0cca1053d6e10df0c438065747611e4af | 3,649,059 |
def _get_item(i, j, block):
"""
Returns a single item from the block. Coords must be in block space.
"""
return block[i, j] | 45a12ecb3959a75ad8f026616242ba64174441fc | 3,649,060 |
def calculate_potentials_python(volume, mass, volume_material_mass, mass_material_mass):
""" Easy to read python function which calculates potentials using two Python loops
Still uses NumPy for the rote math.
"""
potentials = np.zeros(len(volume), dtype=np.float32)
for volume_i, volume_coord in enu... | 73395d31bb470ac96b0c05a140fe6e77f56e2d88 | 3,649,061 |
def rect2sphericalcoord3D(
v: list[Number, Number, Number]
) -> list[float, float, float]:
"""Does a 3D coordinate transform
from rectangular to spherical
coordinate system
p = The length of the hypotenuse
or the magnitude of the
vector
theta =... | 8be197341e576465af389f8e20aea25a59fc3d1e | 3,649,062 |
def GetAssignmentByKeyName(key_name):
"""Gets the assignment with the specified key name."""
return Assignment.get_by_key_name(key_name) | a14b9a2033bb995d53219568278d298f305861d7 | 3,649,063 |
def fit_integer_type(n, is_signed=True):
"""Determine the minimal space needed to store integers of maximal value n
"""
if is_signed:
m = 1
types = [np.int8, np.int16, np.int32, np.int64]
else:
m = 0
types = [np.uint8, np.uint16, np.uint32, np.uint64]
if n < 2 ** (8... | bd9ebd447893509b1144a32bac9f9757988b4a60 | 3,649,064 |
def admin_userforms_order_by_field(user_id):
""" Set User's forms order_by preference
"""
if not g.is_admin:
return jsonify("Forbidden"), 403
data = request.get_json(silent=True)
if not 'order_by_field_name' in data:
return jsonify("Not Acceptable"), 406
field_names = [ field['na... | 4d92dc6f9d562a91509ec2b03aff75c4bc376ead | 3,649,065 |
def check_all_rows(A):
"""
Check if all rows in 2-dimensional matrix don't have more than one queen
"""
for row_inx in range(len(A)):
# compute sum of row row_inx
if sum(A[row_inx]) > 1:
return False
return True | e39f4ca3e401c02b13c5b55ed4389a7e6deceb40 | 3,649,066 |
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
def extract_largest_connected_region(vtk_im, label_id):
"""
Extrac the largest connected region of a vtk image
Args:
vtk_im: vtk image
label_id: id of the label
Return:
new_im: processed vtk image
"""
fltr ... | c9510da15b4d3cade331aa3b9b3625af5706e417 | 3,649,067 |
def group_set_array_data_ptr(d):
"""
call view%set_external_data_ptr
hide c_loc call and add target attribute
"""
# XXX - should this check the type/shape of value against the view?
# typename - part of function name
# nd - number of dimensions
# f_type - fortran type
# shape... | 36a18ca9099edf24d37386103f111bde7753ed46 | 3,649,069 |
from typing import cast
def releaseTagName(version: Version) -> str:
"""
Compute the name of the release tag for the given version.
"""
return cast(str, version.public()) | 9f8e350a42e2b50657a87e89e592ae340ba3ee96 | 3,649,070 |
import time
def get_calibrated_values(timeout=10):
"""Return an instance of CalibratedValues containing the 6 spectral bands."""
t_start = time.time()
while _as7262.CONTROL.get_data_ready() == 0 and (time.time() - t_start) <= timeout:
pass
with _as7262.CALIBRATED_DATA as DATA:
return C... | 69e5921b3e487ab3f3c3abbae8a2b237eb75b033 | 3,649,071 |
def customizable_admin(cls):
"""
Returns a customizable admin class
"""
class CustomSearchableAdmin(BaseAdmin):
form = customizable_form(cls)
def __init__(self, *args, **kwargs):
super(CustomSearchableAdmin, self).__init__(*args, **kwargs)
# add the custom field... | dc6ced817b78b7cbf31cbf788d28fcff421d6b02 | 3,649,072 |
def restoreIm(transformeddata, pca, origshape, datamean, datastd):
"""Given a PCA object and transformeddata that consists of projections onto
the PCs, return images by using the PCA's inverse transform and reshaping to
the provided origshape."""
if transformeddata.shape[0] < transformeddata.shape[1]:
... | ce8713648b166f7ce35bb47df33a6b99e2de8687 | 3,649,073 |
def sample(population, k=None):
"""Behaves like random.sample, but if k is omitted, it default to
randint(1, len(population)), so that a non-empty sample is returned."""
population = list(population)
if k is None:
k = randint(1, len(population))
return random_sample(population, k) | 46f7f3365c4574ed9cb09b54f25e30ff23fb3b8d | 3,649,075 |
def add_momentum_ta(df, high, low, close, volume, fillna=False):
"""Add trend technical analysis features to dataframe.
Args:
df (pandas.core.frame.DataFrame): Dataframe base.
high (str): Name of 'high' column.
low (str): Name of 'low' column.
close (str): Name of 'close' column... | 76239057526272874c34eb4250f642745dfc9990 | 3,649,077 |
def get_experiment_type(filename):
"""
Get the experiment type from the filename.
The filename is assumed to be in the form of:
'<reliability>_<durability>_<history kind>_<topic>_<timestamp>'
:param filename: The filename to get the type.
:return: A string where the timesptamp is taken out fro... | e1853a95d034b8f9e36ca65f6f5d200cbf4b86dc | 3,649,078 |
from typing import Any
def async_check_significant_change(
hass: HomeAssistant,
old_state: str,
old_attrs: dict,
new_state: str,
new_attrs: dict,
**kwargs: Any,
) -> bool | None:
"""Test if state significantly changed."""
if old_state != new_state:
return True
if old_attrs... | 2a3f91923f187a601b80a28aa750060dc0760e65 | 3,649,079 |
import warnings
def array2string(a, max_line_width=None, precision=None,
suppress_small=None, separator=' ', prefix="",
style=np._NoValue, formatter=None, threshold=None,
edgeitems=None, sign=None):
"""
Return a string representation of an array.
Paramet... | ab40c565d058a6836fbc9778ae0d8ceb5c3d6a99 | 3,649,080 |
def registered_types():
""" list of registered types """
return list(Registry.types.get_all().keys()) | 50ed8fd4d586d660e2dc48e01e9cd462b346f47e | 3,649,081 |
from typing import Dict
def is_retain_bg_files(config: Dict[str, ConfigVO] = None) -> bool:
"""
在拉取新的壁纸前,是否保留旧的壁纸
"""
key = const.Key.Task.RETAIN_BGS.value
vo = config.get(key) if config else dao.get_config(key)
return vo and vo.value | 69fd845479c0afbc6d6b215d0680d7f6a9c35096 | 3,649,082 |
import pytz
def getAwareTime(tt):
"""
Generates timezone aware timestamp from timezone unaware timestamp
PARAMETERS
------------
:param tt: datatime
timezome unaware timestamp
RETURNS
------------
:return: datatime
timezone aware timestamp
... | 1b286c92c7f5d8f0ff48d77296489fbd358c14ce | 3,649,083 |
def xdfs(request, tmpdir, vol_name, dos_format):
"""return (xdf_file, xdf_size_spec, vol_name) for various disks"""
size = request.param
if size == "880K":
file_name = tmpdir / "disk.adf"
size = ""
else:
file_name = tmpdir / "disk-" + size + ".hdf"
size = "size=" + size
... | 0a9878ffe020ba1438844e000be5b9e4a8b2825a | 3,649,084 |
def nfvi_get_networks(paging, callback):
"""
Get a list of networks
"""
cmd_id = _network_plugin.invoke_plugin('get_networks', paging,
callback=callback)
return cmd_id | 432bd6a69e25cc7a80aa77b2a58fe99b0947b9a0 | 3,649,085 |
def get_fasta(uniprot_id):
"""Get the protein sequence for a UniProt ID as a string.
Args:
uniprot_id: Valid UniProt ID
Returns:
str: String of the protein (amino acid) sequence
"""
# Silencing the "Will be moved to Biokit" message
with ssbio.utils.suppress_stdout():
r... | 295a5bd30d3e0feaf99ecab7fa975c67f8b06248 | 3,649,086 |
def split_path(path, minsegs=1, maxsegs=None, rest_with_last=False):
"""
Validate and split the given HTTP request path.
**Examples**::
['a'] = split_path('/a')
['a', None] = split_path('/a', 1, 2)
['a', 'c'] = split_path('/a/c', 1, 2)
['a', 'c', 'o/r'] = split_path('/a/c/o... | d3824ebd63b784dadaf0a97e75049f79d1077ded | 3,649,087 |
def get_purchases_formset(n_forms=0):
"""
Helper method that returns a Django formset for a dynamic amount of Purchases. Initially `n_forms` empty
forms are shown.
"""
return modelformset_factory(Purchase, fields=('amount', 'fruit'), extra=n_forms) | b49ec71aef56eabb1781039af947ff510242925a | 3,649,088 |
async def git_pull():
"""
Pulls any changes down from github and returns the result of the command.
_> changed: str
"""
cmd = Popen(["git", "pull"], stdout=PIPE)
out, _ = cmd.communicate()
out = out.decode()
return out | ed32677a22b0f75c23af618f18833b5fc46bb3dc | 3,649,089 |
def inverse_word_map(word_map):
""" Create an inverse word mapping.
:param word_map: word mapping
"""
return {v: k for k, v in word_map.items()} | 4048a21ea1c75791a92d57ee0a440a6c9d31b6b9 | 3,649,090 |
def get_coalition_wins_sql_string_for_state(coalition_id,state_id):
"""
:type party_id: integer
"""
str = """ select
lr.candidate_id,
c.fullname as winning_candidate,
lr.constituency_id,
cons.name as constituency,
lr.party_id,
lr.max_votes,
(lr.max_vot... | 76fb0704779e20e8a53ca80dc17c969f1e455d20 | 3,649,091 |
import numpy
def computeAPLSF(data):
"""
Compute the LSF kernel for each chip
"""
index = 2047
## define lsf range and pixel centers
xlsf = numpy.linspace(-7.,7.,43)
xcenter = numpy.arange(0,4096)
## compute LSF profiles for each chip as a function of pixel
raw_out2_a = raw(xlsf,xcenter,data.lsfcoef... | 5cd46d9feec10dd0a4eff1a5fe44e241bfeed539 | 3,649,092 |
def login():
"""Log in a registered user by adding the user id to the session."""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
error = None
user = User.query.filter_by(name=username).first()
if user is None:
... | 067b202e81d947589c0fe2262372856084b28e35 | 3,649,093 |
def _timedeltaformat(value, include_ms=False):
"""Formats a timedelta in a sane way.
Ignores sub-second precision by default.
"""
if not value:
return NON_BREAKING_HYPHEN + NON_BREAKING_HYPHEN
total_seconds = value.total_seconds()
suffix = ''
if include_ms:
ms = int(round(total_seconds-int(total_... | 5c40caa1bd2e005746a44b1767eb4c3ed29b1603 | 3,649,094 |
def get_viame_src(url):
"""
Get image src from via.me API.
"""
END_POINT = 'http://via.me/api/v1/posts/'
tmp = url.split('/')
viame_id = tmp[-1][1:]
address = END_POINT + viame_id
result = httpget(address)['response']['post']
return result['thumb_300_url'] | 52b23fb64b30c97ef70b683e0176f88f8730e5c9 | 3,649,095 |
def Geom_BSplineCurve_MaxDegree(*args):
"""
* Returns the value of the maximum degree of the normalized B-spline basis functions in this package.
:rtype: int
"""
return _Geom.Geom_BSplineCurve_MaxDegree(*args) | 32729754ca89ce719b81f28fbf3f3c5ea5eb70eb | 3,649,096 |
import torch
def iou_score(pred_cls, true_cls, nclass, drop=(), mask=None):
"""
compute the intersection-over-union score
both inputs should be categorical (as opposed to one-hot)
"""
assert pred_cls.shape == true_cls.shape, 'Shape of predictions should match GT'
if mask is not None:
a... | d38871f339b2126d418a7fca53fbfd874e263aa2 | 3,649,097 |
def check_args(source_path, args):
"""Checks lengths of supplied args match or raise an error.
Lists can have only one element where they are automatically extended.
Args:
source_path(list(str)): List of source_paths supplied to turbiniactl.
args(list(list)): List of args (i.e. name, source, partitio... | 23d50e875ac908b0ee3afd4521b1a2660843ffc6 | 3,649,098 |
from datetime import datetime
import calendar
import warnings
import requests
import zipfile
def futures_dce_position_rank(date: str = "20160104") -> pd.DataFrame:
"""
大连商品交易日每日持仓排名-具体合约
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rcjccpm/index.html
:param date: 指定交易日; e.g., "20200511"
:t... | 3c4fa81a2fef317210be915f437c0885f5fcbbbd | 3,649,099 |
import queue
def task_checkqueue(storage):
"""
Task that watches a queue for messages and acts on them when received.
"""
# Get the queue object from the storage dictionary
thequeue = storage.get("queue")
try:
# Use a timeout so it blocks for at-most 0.5 seconds while waiting for a mes... | 3c7e8cfda53abb0551916894719e66b3d27886e9 | 3,649,103 |
import torch
def to_sparse(x):
""" converts dense tensor x to sparse format """
x_typename = torch.typename(x).split('.')[-1]
sparse_tensortype = getattr(torch.sparse, x_typename)
indices = torch.nonzero(x)
if len(indices.shape) == 0: # if all elements are zeros
return sparse_tensortype(... | b9af99c3c6e41e4f6a73ad213f58338110329dbc | 3,649,104 |
def get_top_article_categories():
"""
获取顶级文章分类列表
自定义模版标签
"""
return Category.objects.filter(level=1) | 88ed0aefe81b3190590974a38c9363f862b8db6c | 3,649,105 |
def filter_variants_top_k(log, k, parameters=None):
"""
Keeps the top-k variants of the log
Parameters
-------------
log
Event log
k
Number of variants that should be kept
parameters
Parameters
Returns
-------------
filtered_log
Filtered log
... | 20e273f5d3ac88e3bc9d0795566b2536c10b5703 | 3,649,106 |
def get_weighted_average(embedding, x, w):
"""
Compute the weighted average vectors
:param embedding: embedding[i,:] is the vector for word i
:param x: x[i, :] are the indices of the words in sentence i
:param w: w[i, :] are the weights for the words in sentence i
:return: emb[i, :] are the weig... | e5cd9984e49075530f981c8600c7e6d86de3c113 | 3,649,107 |
from glyphsLib import glyphdata # Expensive import
def _build_gdef(ufo):
"""Build a table GDEF statement for ligature carets."""
bases, ligatures, marks, carets = set(), set(), set(), {}
category_key = GLYPHLIB_PREFIX + 'category'
subCategory_key = GLYPHLIB_PREFIX + 'subCategory'
for glyph in uf... | 2163971557a8908cce5f142f2e9dfc7fe360f190 | 3,649,108 |
def winningRate2(r, s, X, Y):
"""
revised version, now we want to investigate how value of X and Y will affect.
r: int = remaining round of game
s: int = current score
X: int = points winning for X-head
Y: int = points wining for Y-head
(assuming X and Y are both fair, and we always assume Y... | d33b05aa429044cb76b33842e33b99c1d1d6de7f | 3,649,109 |
def DayOfWeek(year,month,day):
"""DayOfWeek returns the day of week 1-7, 1 being Monday for the given year, month
and day"""
num=year*365
num=num+year//4+1
num=num-(year//100+1)
num=num+year//400+1
if month<3 and LeapYear(year):
num=num-1
return (num+MONTH_OFFSETS[month-1]+day+4)%7+1 | 41c974e1342e65d553702d0610e8dc9c671538a6 | 3,649,111 |
def chef_execute_cli_commands(configuration):
"""
API to generate sonic cli commands with the provided configuration
:param configuration:
:return:
"""
if not configuration:
return False
commands = ""
action_run = "action:run"
for module in configuration:
if module ... | 439b7310015a9707ea6796ea3d24577a5dec069f | 3,649,113 |
def _normalize(vector):
"""Returns a normalized version of a numpy vector."""
return vector/np.sqrt(np.dot(vector, vector)); | 42942ea19af176f6c9fa0ad39b7e060dd518c086 | 3,649,114 |
def get_chol_factor(lower_tri_vals):
"""
Args:
lower_tri_vals: numpy array, shaped as the number of lower triangular
elements, number of observations.
The values ordered according to np.tril_indices(p)
where p is the dimension of t... | fa27afefb49a87bdeac8bceee9f95b34e6c01d3f | 3,649,116 |
def get_angles_gram_mask(gram, mask):
"""
Input: (gram) square numpy array, (mask) square numpy array where
1 = select, 0 = do not select
Output: (angles) numpy array or angles in mask in degrees
"""
angles = gram * mask
angles = angles[angles != 0]
angles = np.degrees(np.arccos(angles... | 3303e318f42b2a7c3a15b4d267f07b7618026b25 | 3,649,117 |
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None):
"""
Compute the expectation:
expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n)
- Ka_{.,.}, Kb_{.,.} :: Linear kernels
Ka and Kb as well as Z1 and Z2 can differ from each other, but this is supported
only if the Gaussian p is Diago... | 105a6445f1a37e2208c65c8bcbcfe76227516991 | 3,649,118 |
def rotX(angle):
"""
-----------------------------------------------------------------------
Purpose: Calculate the matrix that represents a 3d rotation
around the X axis.
Input: Rotation angle in degrees
Returns: A 3x3 matrix representing the rotation about angle around
X axis.
... | b1dd62497cf9db137edbd90f1ff4f6fdb36d54d5 | 3,649,119 |
import re
def LF_positive_MeshTerm(report):
"""
Looking for positive mesh terms
"""
for idx in range(1,len(categories)):
reg_pos = re.compile(categories[idx],re.IGNORECASE)
reg_neg = re.compile('(No|without|resolution)\\s([a-zA-Z0-9\-,_]*\\s){0,10}'+categories[idx],re.IGNORECASE)
... | 391d5775cf109c9f4b0d254162b93937882605ee | 3,649,121 |
def user_ratio_shuffle_split_with_targets(X,
train_ratio=0.8,
n_valid_users=1000,
n_test_users=1000,
minimum_interaction=3,
... | 0f6bc42e94caff49c0be29215b9a6ec4f2203ff7 | 3,649,122 |
import torch
def slice_core(core_tensor, inputs):
"""
Get matrix slices by indexing or contracting inputs, depending on input dtype
"""
assert isinstance(core_tensor, torch.Tensor)
assert isinstance(inputs, torch.Tensor)
if is_int_type(inputs):
return core_tensor[:, inputs, :]
else... | 01a70a678286977b3a36ca24a2f67dce4dbc01fe | 3,649,123 |
import math
def geo2xy(ff_lat_pto, ff_lng_pto, ff_lat_ref=cdf.M_REF_LAT, ff_lng_ref=cdf.M_REF_LNG):
"""
transforma coordenadas geográficas em coordenadas cartesianas
:param ff_lat_pto: latitude em graus
:param ff_lng_pto: longitude em graus
:param ff_lat_ref: latitude do ponto de referência
:... | 93dbe8a41aecb3029d5ac6fa3e68c740c625a486 | 3,649,125 |
def size(e):
"""
:rtype: Column
"""
return col(Size(parse(e))) | 06b904583dc25a9e40b97ca6655bb0e5dcb28304 | 3,649,126 |
def b64pad(b64data):
"""Pad base64 string with '=' to achieve a length that is a multiple of 4
"""
return b64data + '=' * (4 - (len(b64data) % 4)) | bdc14821bfbdbf220ff371fbe5e486d3e682337b | 3,649,127 |
def get_peak_electric_demand(points_on_line):
"""
Initialize Power Demand
:param points_on_line: information about every node in study case
:type points_on_line: GeoDataFrame
:returns:
- **dict_peak_el**: Value is the ELECTRIC peak demand depending on thermally connected or disconnected.
... | 015fe10835f49f060e24681335d77a79586e31ea | 3,649,128 |
def _GetDatabaseLookupFunction(filename, flaps, omega_hat, thrust_coeff):
"""Produces a lookup function from an aero database file."""
db = load_database.AeroDatabase(filename)
def _Lookup(alpha, beta, dflaps=None, domega=None):
if dflaps is None:
dflaps = np.zeros((system_types.kNumFlaps,))
if dome... | 5b1e7a4636aa824466e791b54dd7a67a4208962e | 3,649,129 |
def parse_copy_core_dump(raw_result):
"""
Parse the 'parse_copy_core_dump' command raw output.
:param str raw_result: copy core-dump raw result string.
:rtype: dict
:return: The parsed result of the copy core-dump to server:
::
{
0:{
'status': 'success'
... | 4ce168c9bc8c462ecc36beba889adb36cc64135d | 3,649,130 |
def _handle_requirements(hass, component, name):
"""Install the requirements for a component."""
if hass.config.skip_pip or not hasattr(component, 'REQUIREMENTS'):
return True
for req in component.REQUIREMENTS:
if not pkg_util.install_package(req, target=hass.config.path('lib')):
... | efa0c371150a9aee9f26136a17ad1e33b9760340 | 3,649,131 |
def ticket_id_url(workspace, number):
"""
The url for a specific ticket in a specific workspace
:param workspace: The workspace
:param number: The number of the ticket
:return: The url to fetch that specific ticket
"""
return basic_url + ' spaces/' + workspace + '/tickets/' + number + '.json... | a0ffeb53062c635f74feb011af793a2c00c361c4 | 3,649,132 |
def compute_lifting_parameter(lamb, lambda_plane_idxs, lambda_offset_idxs, cutoff):
"""One way to compute a per-particle "4D" offset in terms of an adjustable lamb and
constant per-particle parameters.
Notes
-----
(ytz): this initializes the 4th dimension to a fixed plane adjust by an offset
fo... | a9455ed67fcb21bcf1382fe66a77e0563f467421 | 3,649,134 |
import re
import json
def create_controller():
"""
1. Check the token
2. Call the worker method
"""
minimum_buffer_min = 3
if views.ds_token_ok(minimum_buffer_min):
# 2. Call the worker method
# More data validation would be a good idea here
# Strip anything other than ... | 1aa777b66f110d575ea16531ca4bd72e0117e0b0 | 3,649,135 |
def reproduce_load_profile(neural_model, simulation_model: CHPP_HWT, input_data, logger):
"""
Tries to follow a real load profile
"""
# make sure the random seeds are different in each process
#np.random.seed(int.from_bytes(os.urandom(4), byteorder='little'))
temperature, powers, heat_demand = ... | 078fa837c0c82ea17c42ca949ba9bb33cdaeaaa0 | 3,649,136 |
def session_pca(imgs, mask_img, parameters,
n_components=20,
confounds=None,
memory_level=0,
memory=Memory(cachedir=None),
verbose=0,
copy=True):
"""Filter, mask and compute PCA on Niimg-like objects
This is an help... | f175ac8d9c39e133c34a4db215b5e87288bdafd4 | 3,649,137 |
def numpy_napoleon(prnt_doc, child_doc):
"""Behaves identically to the 'numpy' style, but abides by the docstring sections
specified by the "Napoleon" standard.
For more info regarding the Napoleon standard, see:
http://sphinxcontrib-napoleon.readthedocs.io/en/latest/index.html#docstring-sections
... | 1795ddd1cfeeb8aee07cb17a369c6043b5fda52f | 3,649,138 |
def search_unique_identities_slice(db, term, offset, limit):
"""Look for unique identities using slicing.
This function returns those unique identities which match with the
given `term`. The term will be compared with name, email, username
and source values of each identity. When an empty term is given... | 1cfed05995eb90427a0f4a9475cfd8f7737d7e59 | 3,649,139 |
def get_change_description(req_sheet, row_num):
""" Accessor for Change Description
Args:
req_sheet: A variable holding an Excel Workbook sheet in memory.
row_num: A variable holding the row # of the data being accessed.
Returns:
A string value of the Change Description
"""
... | 7d3f286fb2586bf7bed64de8bb0cbf156e1ff954 | 3,649,140 |
def reduce_pca(data_df, n_components=None):
"""
Uses PCA to reduce dimension.
Parameters:
data_df (DataFrame): The input data in DataFrame format
n_components (float): The number of components or to reduce to. If the number if between 0 and 1, n_components is the % of
th... | b4b8db256b5996ddf3101a7737cb1396bc5abd06 | 3,649,141 |
def create_disjoint_intervals(draw,
dtype,
n_intervals=10,
dt=1,
time_range=(0, 100),
channel_range=(2000, 2119),
length_range=(1, 1), ):
... | 67ed49bd8d94067cb6647164fa44beb4f8d91314 | 3,649,142 |
def get_deleted_resources():
"""Get a list of resources that failed to be deleted in OVN.
Get a list of resources that have been deleted from neutron but not
in OVN. Once a resource is deleted in Neutron the ``standard_attr_id``
foreign key in the ovn_revision_numbers table will be set to NULL.
Up... | 6a37fd84933ceee3a2a537aee8a01315f5869200 | 3,649,143 |
def load_base_schema(base_schema=None, verbose=False):
"""Load base schema, schema contains base classes for
sub-classing in user schemas.
"""
_base = base_schema or BASE_SCHEMA or []
_base_schema = []
if "schema.org" in _base:
_base_schema.append(
load_schemaorg(verbose=v... | 18fe2b7045aa6d8e7382c37093be053b619ec216 | 3,649,144 |
def endgame_score_connectfour(board, is_current_player_maximizer) :
"""Given an endgame board, returns 1000 if the maximizer has won,
-1000 if the minimizer has won, or 0 in case of a tie."""
chains_1 = board.get_all_chains(current_player=is_current_player_maximizer)
chains_2 = board.get_all_chains(curr... | bcb37381a9633377cb3405fbae45123e2a391df9 | 3,649,146 |
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
"""Add a vertical color bar to an image plot.
Taken from https://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph
"""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.ax... | acb0b21139d10393c2605bc94671fc774ada3800 | 3,649,148 |
import time
def wait_procs(procs, timeout, callback=None):
"""Convenience function which waits for a list of processes to
terminate.
Return a (gone, alive) tuple indicating which processes
are gone and which ones are still alive.
The gone ones will have a new 'retcode' attribute indicating
p... | 624a6a1286a662a6f9e2d0680898e89b71585a7a | 3,649,149 |
def select(sel, truecase, falsecase):
""" Multiplexer returning falsecase for select==0, otherwise truecase.
:param WireVector sel: used as the select input to the multiplexer
:param WireVector falsecase: the WireVector selected if select==0
:param WireVector truecase: the WireVector selected if select... | 134e62fa84a16560e16f72294c9d01b3118c80e4 | 3,649,150 |
def fish_collision(sprite1, sprite2):
"""Algorithm for determining if there is a collision between the sprites."""
if sprite1 == sprite2:
return False
else:
return collide_circle(sprite1, sprite2) | 846024639f971c755b9ae88f8db43695d1e7c5e2 | 3,649,151 |
def normalizePeriodList(periods):
"""
Normalize the list of periods by merging overlapping or consecutive ranges
and sorting the list by each periods start.
@param list: a list of tuples of L{Period}. The list is changed in place.
"""
# First sort the list
def sortPeriods(p1, p2):
"... | d178123e8ef65b88e46130db24f96aa86b444b11 | 3,649,152 |
from typing import Callable
from typing import Optional
from typing import Any
import inspect
from typing import Dict
def assemble(the_type: Callable[..., TypeT],
profile: Optional[str] = None,
**kwargs: Any) -> TypeT:
"""Create an instance of a certain type,
using constructor inject... | e8a39d61ddcb8834daf45089f597754a2860a334 | 3,649,153 |
def coord_ijk_to_xyz(affine, coords):
"""
Converts voxel `coords` in cartesian space to `affine` space
Parameters
----------
affine : (4, 4) array-like
Affine matrix
coords : (N,) list of list
Image coordinate values, where each entry is a length three list of int
denoti... | c7099a588df3bd85a3a5a85451e15812564aae2f | 3,649,154 |
def _get_create_statement(server, temp_datadir,
frm_file, version,
options, quiet=False):
"""Get the CREATE statement for the .frm file
This method attempts to read the CREATE statement by copying the .frm file,
altering the storage engine in the .frm fil... | 953b97df9f7f01540d5f61ef8099282d4aab26d6 | 3,649,155 |
def delete_driver_vehicle(driver):
"""delete driver"""
try:
driver.vehicle = None
driver.save()
return driver, "success"
except Exception as err:
logger.error("deleteVehicleForDriverRecord@error")
logger.error(err)
return None, str(err) | e6de3c9d1ae0ce0ac2022fe8ce38c2eccbe3b8df | 3,649,156 |
def passivity(s: npy.ndarray) -> npy.ndarray:
"""
Passivity metric for a multi-port network.
A metric which is proportional to the amount of power lost in a
multiport network, depending on the excitation port. Specifically,
this returns a matrix who's diagonals are equal to the total
power rece... | 9b3629aae603d8de97982113333b87bb021972e4 | 3,649,157 |
def sample_distance(sampleA, sampleB, sigma):
"""
I know this isn't the best distance measure, alright.
"""
# RBF!
gamma = 1 / (2 * sigma**2)
similarity = np.exp(-gamma*(np.linalg.norm(sampleA - sampleB)**2))
distance = 1 - similarity
return distance | 1f1bb56d8e1876c9c9ab6b1d1db26ff549d86b81 | 3,649,158 |
from typing import Dict
from typing import Set
def get_filters(query_metadata: QueryMetadataTable) -> Dict[VertexPath, Set[FilterInfo]]:
"""Get the filters at each VertexPath."""
filters: Dict[VertexPath, Set[FilterInfo]] = {}
for location, _ in query_metadata.registered_locations:
filter_infos = ... | 79ef7accd1c8e1d100f48eb7086c842429a4a513 | 3,649,160 |
import numpy
def auxiliary_equations(*, F, T_degC, I_sc_A_0, I_rs_1_A_0, n_1_0, I_rs_2_0_A, n_2_0, R_s_Ohm_0, G_p_S_0, E_g_eV_0, N_s,
T_degC_0=T_degC_stc):
"""
Computes the auxiliary equations at F and T_degC for the 8-parameter DDM-G.
Inputs (any broadcast-compatible combination ... | 5bbb988a7e4415f59a56985c2c867ec1a0dc5df2 | 3,649,161 |
from typing import List
from typing import Dict
def get_highest_confidence_transcript_for_each_session(
transcripts: List[db_models.Transcript],
) -> List[db_models.Transcript]:
"""
Filter down a list transcript documents to just a single transcript
per session taking the highest confidence transcript... | fccf657c5c670d8b3e275641d411ede34af91e41 | 3,649,163 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.