content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from functools import reduce
import operator
def concatenate(trajectories):
"""Return the concatenation of a sequence of trajectories.
Parameters
----------
trajectories : sequence of sequences
A sequence of trajectories.
Returns
-------
sequence
The concatenation of `tra... | dee2e64b579d07adea0842eb375c543453e9eede | 3,633,673 |
def dlonlat_at_grid_center(ctr_lat, ctr_lon, dx=4.0e3, dy=4.0e3,
x_bnd = (-100e3, 100e3), y_bnd = (-100e3, 100e3),
proj_datum = 'WGS84', proj_ellipse = 'WGS84'):
"""
Utility function useful for producing a regular grid of lat/lon data,
where an approximate spacing (dx, dy) and total span of t... | a64fefbad5593e33af4dde3fb362aec54c0d6225 | 3,633,674 |
def attribute_test_service(request):
"""
Displays a list of all :model:`rr.Attribute` and values
found from environment variables.
**Context**
``object_list``
List of dictionaries containing attribute values and metadata.
``logout_url``
Logout URL.
**Template:**
:temp... | 79e7e4b861e74ab6739ccd3c2ea226d01d4bbe02 | 3,633,675 |
import re
import threading
import uuid
from datetime import datetime
import json
def create_foundation_entity_instance(entity):
"""Create an instance of a Foundation SDK Entity"""
# Get an SDK class and use the configuration generation behaviour to pass in parameters
sdk_instance = SDK(**(request.get_json... | 78d3bfcf4baa922213feedde1420112a9db7bf04 | 3,633,676 |
def guided_alignment_cost(
attention_probs, gold_alignment, sequence_length=None, cost_type="ce", weight=1
):
"""Computes the guided alignment cost.
Args:
attention_probs: The attention probabilities, a float ``tf.Tensor`` of shape
:math:`[B, T_t, T_s]`.
gold_alignment: The true alignme... | b1acea456d0f17ff3e0917a071cc84d69b7893ad | 3,633,677 |
def _log_object_event(
ctx,
dbOperationsEvent=None,
event_status_id=None,
dbAcmeAccount=None,
dbAcmeAccountKey=None,
dbAcmeDnsServer=None,
dbAcmeOrder=None,
dbCertificateCA=None,
dbCertificateCAChain=None,
dbCertificateRequest=None,
dbCoverageAssuranceEvent=None,
dbDomain... | 91e395e6dd9c512b93531c292056c2e324084622 | 3,633,678 |
def dismiss_message_url(course):
"""
Returns the URL for the dismiss message endpoint.
"""
return reverse(
'openedx.course_experience.dismiss_welcome_message',
kwargs={
'course_id': str(course.id),
}
) | aeabf651b2576f280634d7562d31e52fb7e0748f | 3,633,680 |
def cllr(lrs, y, weights=(1, 1)):
"""
Calculates a log likelihood ratio cost (C_llr) for a series of likelihood
ratios.
Nico Brümmer and Johan du Preez, Application-independent evaluation of speaker detection, In: Computer Speech and
Language 20(2-3), 2006.
Parameters
----------
lrs : ... | 31b7e022de94aec36efd570318e930d665349169 | 3,633,681 |
import torch
def heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> torch.Tensor:
"""
Extract predicted keypoint locations from heatmaps.
Args:
maps (Tensor): (#ROIs, #keypoints, POOL_H, POOL_W). The predicted heatmap of logits for
each ROI and each keypoint.
roi... | 1755ebd45ab741ef267b17f1d24a658143e5f6c5 | 3,633,682 |
def add_user_input_to_scene(scene, user_input, keep_space_around_bodies=True):
"""Converts user input to objects in the scene.
Args:
scene: scene_if.Scene.
user_input: scene_if.UserInput or a triple (points, rectangulars, balls).
keep_space_around_bodies: bool, if True extra empty space... | 4020253049b3615d81d2cbca829433c211c3f9c1 | 3,633,685 |
def language_add():
"""Return the page to add a language."""
is_user_logged_in = True if 'username' in login_session else False
context = {'is_user_logged_in': is_user_logged_in}
if request.method == 'POST':
if not is_user_logged_in:
flash('You have to log in to add a language.')
... | 8098ce3c3e6e8f8930790a636405ae69ce95cdd8 | 3,633,686 |
def pyramid_sum(lower, upper, margin = 0):
"""Returns the sum of the numbers from lower to upper,
and outputs a trace of the arguments and return values
on each call."""
blanks = " " * margin
print(blanks, lower, upper) # Print the arguments
if lower > upper:
print(blanks, 0) # Print th... | 751facb309f362c35257aab2b239a37b39a98a04 | 3,633,687 |
def grad_qform_1_ZV(a,f_vals,X_grad,ind,n,alpha):
"""
Gradient for quadratic form in ZV-1 method
"""
Y = f_vals[:,ind] + X_grad @ a
return 2./(n-1) * (X_grad*(Y - np.mean(Y)).reshape((n,1))).sum(axis=0) + 2*alpha*a | aab2ac9cc79a4cf43e4391872ebf905e849ba7d9 | 3,633,688 |
def is_learner(user, program):
"""
Returns true if user is a learner
Args:
user (django.contrib.auth.models.User): A user
program (courses.models.Program): Program object
"""
return (
not Role.objects.filter(user=user, role__in=Role.NON_LEARNERS, program=program).exists()
... | 4773a6ebcc2b892a5306614a1bde699d0e17f191 | 3,633,690 |
import warnings
import math
def calculate_rupture_rates(
nhm_df: pd.DataFrame,
rup_name: str = "rupture_name",
annual_rec_prob_name: str = "annual_rec_prob",
mag_name: str = "mag_name",
) -> pd.DataFrame:
"""Takes in a list of background ruptures and
calculates the rupture rates for the given ... | a58e656980454de2f53fb1db2f5b0ec37fec9334 | 3,633,691 |
def checkScriptParses(scriptVersion, script):
"""
checkScriptParses returns None when the script parses without error.
Args:
scriptVersion (int): The script version.
script (ByteArray): The script.
Returns:
None or Exception: None on success. Exception is returned, not raised.
... | da49e2ca94fe38ef93e92eac27acc4eafd02f3e9 | 3,633,692 |
import unicodedata
def normalize_caseless(text):
"""Normalize a string as lowercase unicode KD form.
The normal form KD (NFKD) will apply the compatibility decomposition,
i.e. replace all compatibility characters with their equivalents.
"""
return unicodedata.normalize("NFKD", text.casefold()) | c26f8470ea6312cce7a97930999d489ee30eb692 | 3,633,693 |
def select_device_mirrored(device, structured):
"""Specialize a nest of regular & mirrored values for one device."""
def _get_mirrored(x):
if isinstance(x, DistributedValues):
if not isinstance(x, Mirrored):
raise TypeError(
"Expected value to be mirrored across replicas: %s in %s." %
... | 5b69c9464e1d8a4597f5661d85c056e90deb70bf | 3,633,694 |
from typing import Dict
from typing import Any
from typing import Counter
def default_base_builder(individual: "Individual", frame: Frame, **kwargs) -> Dict[str, Any]:
"""Get base stats of the frame"""
v = dict()
# nodes
nodes = individual.nodes(frame_selector=frame, data=True)
v['nodes'] = list(... | de0c3ea0120bef893d29e6917ec6cc0e19e451b9 | 3,633,695 |
def calculate_maximum_potential_edge_counts(channel_composition, N, max_ble_span):
"""Computes the maximum number of possible occurrences per potential edge type.
Parameters
----------
channel_composition : Dict[str, int]
Channel composition description.
N : int
Number of BLEs in th... | 55f891631bd109066735e9997cbb3dc35de8d21a | 3,633,696 |
def generic_document_type_formatter(view, context, model, name):
"""Return AdminLog.document field wrapped in URL to its list view."""
_document_model = model.get('document').document_type
url = _document_model.get_admin_list_url()
return Markup('<a href="%s">%s</a>' % (url, _document_model.__name__)) | c00934e8778c5232092427e2b507785ef429570d | 3,633,697 |
def string_to_bool(value):
"""
boolean string to boolean converter
"""
if value == "true":
return True
else:
return False | 0796b21c98d09592d8d3a6ae1dfc5b98564aec7f | 3,633,698 |
def g_logv(s):
"""read a logical variable
:param str s:
:return bool:
"""
return s == '1' or s.lower() == 'yes' or s.lower() == 'true' | e9984eced79cccc09a465b07bfac5185db72a604 | 3,633,699 |
def get_number_of_engine_threads():
"""
Returns the number of engine threads.
"""
command = 'ps aux | grep "./build/engine" | grep -v "grep" | wc -l'
n_threads = int(common.run_local_cmd(command, get_output = True))
return n_threads | 843bec78af34d97f73b42447180636b5fe171d17 | 3,633,701 |
def metadata_repr_as_list(metadata_list):
"""
Turn a list of metadata into a list of printable representations
"""
output = []
for metadata_dict in metadata_list:
try:
output.append('%s - %s' % (MetadataType.objects.get(
pk=metadata_dict['id']), metadata_dict.get(... | ef6cae970f98311b150fde019b7479b5fd35a573 | 3,633,702 |
def dip_reconstructor(dataset='ellipses', name=None):
"""
:param dataset: Can be 'ellipses' or 'lodopab'
:return: The Deep Image Prior (DIP) method for the specified dataset
"""
try:
standard_dataset = load_standard_dataset(dataset)
params = Params.load('{}_dip'.format(dataset))
... | dcd34307b9d69ed5ad4cbbf8ee61063c02c8d592 | 3,633,703 |
def convert_listofrollouts(paths):
"""
Take a list of rollout dictionaries
and return separate arrays,
where each array is a concatenation of that array from across the rollouts
"""
observations = np.concatenate([path["observation"] for path in paths])
actions = np.concatenate([p... | f3cc52fa56f26985c1cb69c991bc28ff4f19b118 | 3,633,704 |
def get_iex_corporate_actions(start=None, **kwargs):
"""
Top-level function to retrieve IEX Corporate Actions from the ref-data
endpoints
Parameters
----------
start: datetime.datetime, default None, optional
A month to use for retrieval (a datetime object)
kwargs: Additional Reques... | c355f70ff84f5be7a808dccad02bd644f21edc5f | 3,633,705 |
import math
def mc_generation_costs(df_ren, h2_demand, year_diff, capex_extra, capex_h2, lifetime_hours, electrolyser_efficiency,
elec_opex,
other_capex_elec, water_cost,
capex_wind, opex_wind, capex_solar, opex_factor_solar,
... | 6ba407ecda6619293b811c7cab6c71a95284c2bc | 3,633,706 |
def relax(u, f, nu):
"""
Weighted Jacobi
"""
n = len(u)
Dinv = 1.0 / (2.0 * ((n+1)**2))
omega = 2.0 / 3.0
unew = u.copy()
for steps in range(nu):
unew = unew + omega * Dinv * residual(unew, f)
return unew | 5216744a04e93ad5dc22d5f01f47bc3c5c2ccbe1 | 3,633,707 |
def forward_influence_centrality(graph, weight=None):
"""Returns the forward influence centrality of the nodes in a network as an array.
Parameters
----------
graph : Graph, array
A NetworkX graph or numpy/sparse array
weight : string or None
If you have weighted edges i... | 684b6342b96b1807ec5dd841b23a476703813298 | 3,633,709 |
import json
def try_to_replace_line_json(line, json_type, new_json, json_prefix=""):
"""Attempts to replace a JSON declaration if it's on the line.
Parameters
----------
line: str
A line from a JavaScript code file. It's assumed that, if it declares
a JSON, this declaration will only ta... | 602897349b52be3f10a41cf90d211ad70a6d4cc2 | 3,633,710 |
def createInvoice(request):
"""
Invoice Generator page it will have Functionality to create new invoices,
this will be protected view, only admin has the authority to read and make
changes here.
"""
heading_message = 'Formset Demo'
if request.method == 'GET':
formset = LineItemForms... | e759be0c0f270ab3979d2dc2303f838dee9b58a4 | 3,633,711 |
def GetTopLevelParent(*args, **kwargs):
"""GetTopLevelParent(Window win) -> Window"""
return _misc_.GetTopLevelParent(*args, **kwargs) | cf4bdbf694b45935af96f3e6432b38a7da6ca283 | 3,633,712 |
def slotnick(x, k):
"""
Relation between velocity and depth
Parameters
----------
x : 1-d ndarray
Depth to convert
k : scalar
velocity gradient
Notes
-----
typical values of velocity gradient k falls in the range 0.6-1.0s-1
References
----------
.. [1] ... | 25b068919edea9226e071ad4ae948463384a71c9 | 3,633,713 |
def NodeEvolution(tensor, directed=False):
"""Temporal evolution of all nodes' input and output communicability or flow.
Parameters
----------
tensor : ndarray of rank-3
Temporal evolution of the network's dynamic communicability. A tensor
of shape timesteps x n_nodes x n_nodes, where n... | cd05e84d136047997723c92f1e68d84d96c9d023 | 3,633,714 |
def transform_symbol(ctx, name):
"""Transform the symbol NAME using the renaming rules specified
with --symbol-transform. Return the transformed symbol name."""
for (pattern, replacement) in ctx.symbol_transforms:
newname = pattern.sub(replacement, name)
if newname != name:
print " symbol '%s' t... | d4dfb7a2875b4ee20b5a9476578c0ae65afb297c | 3,633,715 |
def get_active_resources_in_grid(grid):
"""Get active resources in grid.
:param powersimdata.input.grid.Grid grid: a Grid instance.
:return: (*set*) -- name of active resources in grid.
"""
_check_grid_type(grid)
active_resources = set(grid.plant.loc[grid.plant["Pmax"] > 0].type.unique())
r... | b5d621577fb9cf99451efc41d32ee59530e6ecab | 3,633,716 |
def getReflectionandTransmission(
sig1,
sig2,
f,
theta_i,
eps1=epsilon_0,
eps2=epsilon_0,
mu1=mu_0,
mu2=mu_0,
dtype="TE",
):
"""
Compute reflection and refraction coefficient of plane waves
"""
theta_i = np.deg2rad(theta_i)
omega = 2 * np.pi * f
k1 = np.sqrt(... | 6b04fc7e90c8baf8c78342d1e1afe2a6c65f489b | 3,633,717 |
import math
def tile(lng, lat, zoom, truncate=False):
"""Get the tile containing a longitude and latitude
Parameters
----------
lng, lat : float
A longitude and latitude pair in decimal degrees.
zoom : int
The web mercator zoom level.
truncate : bool, optional
Whether ... | 4c5ad0ee802a61b1fe091a431d6cb53667a68d9c | 3,633,718 |
def read(file_path, lines=False):
"""Returns contents of file either as a string or list of lines."""
with open(file_path, 'r') as fp:
if lines:
return fp.readlines()
return fp.read() | 86b36dbc2792ac70bd9a71c74486643b3cdef690 | 3,633,719 |
from typing import Union
from typing import Tuple
from typing import List
def diff(tv: vs.VideoNode, bd: vs.VideoNode,
thr: float = 72,
height: int = 288,
return_array: bool = False,
return_frames: bool = False) -> Union[vs.VideoNode, Tuple[vs.VideoNode, List[in... | 73509e85f1134179a71170496c64ca17f0239b15 | 3,633,720 |
from typing import List
def random_choice(choices: List[float]) -> float:
"""Selects a random choice within a list."""
return choices[np.random.choice(len(choices), size=1)[0]] | 69d1f25b830e295d81666e3c29c7b16bf53e76ba | 3,633,722 |
def UnescapeUnderscores(s: str):
"""Reverses EscapeWithUnderscores."""
i = 0
r = ''
while i < len(s):
if s[i] == '_':
j = s.find('_', i + 1)
if j == -1:
raise ValueError('Not a valid string escaped with `_`')
ss = s[i + 1:j]
if not ... | c793666527b37ee66f832e650e6c6aac47bc8a82 | 3,633,723 |
def login(base_config):
"""
返回登录后的
:return:
"""
username = base_config.get("username")
password = base_config.get("password")
base_url = base_config.get("base_url")
company_id = base_config.get("company_id")
app_id = base_config.get("app_id")
app_secret = base_config.get("app_sec... | d17c9d300ac233a845e7439bd9abd9528a4e9041 | 3,633,724 |
def filter_(stream_spec, filter_name, *args, **kwargs):
"""Alternate name for ``filter``, so as to not collide with the
built-in python ``filter`` operator.
"""
return filter(stream_spec, filter_name, *args, **kwargs) | 0e55c8c6093fafed58ced08c757e6a489fcefa17 | 3,633,725 |
def angle_normalization_0_2pi(angle):
"""Automatically normalize angle value(s) to the range of 0-2pi.
This function relies on modular arithmetic.
Parameters
----------
angle : array_like
The angles to be converted
Returns
-------
normalized_angles : ndarray
The angles... | ceef5b57ad18fc01ee7faf71d51c303621170674 | 3,633,726 |
def config_resolve_context(cookie, in_context, in_size):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("ConfigResolveContext")
method.cookie = cookie
method.in_context = str(in_context)
method.in_size = str(in_size)
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
... | deea2ff376318f49102d1c0eeceb58a0dfb1e9d8 | 3,633,727 |
def bots_endpoint(page=1):
"""
Return bots from the BotList.
Use the url parameters `url` or `username` to perform a search on the BotList.
The @-character in usernames can be omitted.
:param page: The page to display
:return: All bots (paginated) or the search result if url parameters were us... | 86686626a46817c85c9cdbc188b27bb4a2e59d6b | 3,633,728 |
from typing import List
from typing import Dict
def parse_secrets(raw: List[str]) -> Dict[str, str]:
"""Parses secrets"""
result: Dict[str, str] = {}
for raw_secret in raw:
keyval = raw_secret.split('=', 1)
if len(keyval) != 2:
raise ValueError(f'Invalid secret "{raw_secret}"')... | d209c954c75353c17f0bca561c3ad94fc26a9ad0 | 3,633,730 |
async def detect_custom(model: str = Form(...), image: UploadFile = File(...)):
"""
Performs a prediction for a specified image using one of the available models.
:param model: Model name or model hash
:param image: Image file
:return: Model's Bounding boxes
"""
draw_boxes = False
predict_batch = False
try:
... | f6a2eefa7ac855899bec9fd86399f8704e24f3d6 | 3,633,731 |
def ensure_databases_alive(max_retries: int = 100,
retry_timeout: int = 5,
exit_on_failure: bool = True) -> bool:
"""
Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries``
attempts to reach any backend ar... | e583d3b1cceca43e66c246fa4fea8eb58727ef6c | 3,633,732 |
def __maxCrossingSubArr(seq, low, mid, high):
"""
寻找seq[low..high]跨越了中点mid的最大子数组
总循环次数为high-low+1,线性的
"""
leftSum = float('-Inf')
sumTemp = 0
for i in range(mid, low - 1, -1):
sumTemp += seq[i]
if sumTemp > leftSum:
leftSum = sumTemp
maxLeft = i
ri... | 542f07214438297623518046c51974cf461b3aa5 | 3,633,733 |
def transition_matrix(embeddings, word_net=False, first_order=False, sym=False, trans=False, **kwargs):
"""
Build a probabilistic transition matrix from word embeddings.
"""
if word_net:
L = wordnet_similarity_matrix(embeddings)
elif not first_order:
L = similarity_matrix(embeddings... | c4181b5ad61f32429d289c207eb9bb5282f8fa99 | 3,633,734 |
def gen_review_vecs(reviews, model, num_features):
"""
Function which generates a m-by-n numpy array from all reviews,
where m is len(reviews), and n is num_feature
Input:
reviews: a list of lists.
Inner lists are words from each review.
Outer lists... | b8ce4489aaa03f45727e3340c361f185bf2f77dd | 3,633,736 |
def ott(high, low, close, length=None,_shift=None, multiplier=None, **kwargs):
"""Indicator: Supertrend"""
# Validate Arguments
high = verify_series(high)
low = verify_series(low)
close = verify_series(close)
length = int(length) if length and length > 0 else 7
shift = int(_shift) if _shift ... | dd9f1010a4db9c45ce8d81d78a562ae656980d10 | 3,633,737 |
def lambda_cut_series(x, mfx, n):
"""
Determines a series of lambda-cuts in a sweep from 0+ to 1.0 in n steps.
Parameters
----------
x : 1d array
Universe function for fuzzy membership function mfx.
mfx : 1d array
Fuzzy membership function for x.
n : int
Number of st... | 60d25561b0fb637ab33407a6ea627da6ef553192 | 3,633,738 |
def validate_schema(request, schema_instance):
""" A decorator function that validates schema againt request payload """
def decorator(func):
@wraps(func)
def wrapper_function(*args, **kwargs):
json_payload = request.get_json()
schema_instance.load_json_into_schema(json_... | 841e60779887fc076cdf5af4dc1fc054b72799c2 | 3,633,739 |
def has_inference_based_loaders(cfg: CfgNode) -> bool:
"""
Returns True, if at least one inferense-based loader must
be instantiated for training
"""
return len(cfg.BOOTSTRAP_DATASETS) > 0 | 6a8677edfe2074902a6f0327636cfa177577f862 | 3,633,740 |
def get_terrain_for_coord(x, y):
"""Get the terrain type for a coordinate.
:param int x: The x coordinate
:param int y: The y coordinate
:returns tuple(Terrain, bool): The terrain type and whether it is diverse
"""
elevation, moisture, temperature, diversity = _render_map_data(
1, 1, (... | 0f25ecd3e70d3a1d45b3b4d08a064d40c57e2284 | 3,633,741 |
def read_Image8(Object, Channel, iFlags=0):
"""
read_Image8(Object, Channel, iFlags=0) -> bool
read_Image8(Object, Channel) -> bool
"""
return _Channel.read_Image8(Object, Channel, iFlags) | 4a3265d9a3ba0ce486d968156a5a35e6b61ec7de | 3,633,742 |
import math
def Linear(in_features, out_features, dropout=0):
"""Weight-normalized Linear layer (input: N x T x C)"""
m = nn.Linear(in_features, out_features)
m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))
m.bias.data.zero_()
return nn.utils.weight_norm(m) | de26db37469b6e0d4fbd92545982b1deaef997c6 | 3,633,743 |
def get_state(initial, input_value=None):
"""Get new state, filling initial and optional input_value."""
return {
'last_position': None,
'initial': [initial],
'input': [input_value] if input_value is not None else [],
'output': [],
} | 7520341debf6b7287a445be1a44e51bd5675472f | 3,633,744 |
import operator
def predictkNNLabels(closest_neighbors, y_train):
"""This function predicts the label of a individual point
in X_test based on the labels of the nearest neighbour(s).
And sums up the total of appearences of the labels and
returns the label that occurs the most """
labelPrediction ... | aa7ce9383253230f2c0535e3e27e2f2442dec043 | 3,633,745 |
def fetch_dataset(filename):
"""
Useful util function for fetching records
"""
buffer_size = 32 * 1024 * 1024 # 32 MiB per file
dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)
return dataset | 594a2298b6d72cea2982ec91476d6c0f78aaae65 | 3,633,746 |
def get_alma_project(ra,de, radius_arcsec=10/3600):
"""Return ALMA project IDs (if exists) given coordinates."""
# set up connection
cnx = db.get_cnx(cfg.mysql['user'], cfg.mysql['passwd'],
cfg.mysql['host'], cfg.mysql['db_sdb'])
if cnx is None:
return
cursor = cnx.curs... | 8e1ac1b1bd979f5386d388aecef7f85ccff92492 | 3,633,747 |
from typing import Optional
def read_certification_data(reader: PdfFileReader) -> Optional[DocMDPInfo]:
"""
Read the certification information for a PDF document, if present.
:param reader:
Reader representing the input document.
:return:
A :class:`.DocMDPInfo` object containing the r... | f26f09e7b3c835e5d029d824257053fa4fdcb97d | 3,633,748 |
from re import T
def from_independent_matroid(matroid: tuple[set[T], list[set[T]]]) -> list[set[T]]:
"""Construct circuits from a matroid defined by independent sets.
Args:
matroid (tuple[set[T], list[set[T]]]): A matroid defined by independent sets.
Returns:
list[set[T]]: The circuits o... | a5b8a278147b3926904cfc4d0bc23249a1669857 | 3,633,749 |
from .ir import ModularIndexing
import sympy
def join_dimensions(expr: sympy.Expr) -> sympy.Expr:
"""
ModularIndexing(i0, 1, 32) + 32 * ModularIndexing(i0, 32, 4)
becomes
ModularIndexing(i0, 1, 128)
This type of pattern can come from view operations
"""
if not isinstance(expr, sympy.Add)... | 72528ce5630f5e8ddcfcb42ddbc2b45cc194b9d4 | 3,633,750 |
def evolve(model, mutator, population, tournament_size=4):
"""
Performs crossover and mutation and doubles population size
:param model: Instance of Model
:param mutator: Instance of Mutator
:param population: List of points
:param tournament_size: Size of tournament
:return: List of population + List of ... | 0bf6629601ee6f8a3be1a9491d85944fb817bd38 | 3,633,752 |
def cell_snippet(x, is_date=False):
"""create the proper cell snippet depending on the value type"""
if type(x) == int:
return {
'userEnteredValue': {'numberValue': x},
'userEnteredFormat': {
'numberFormat': {
'type': 'NUMBER',
... | bc91279e5e9b4e9e6b853badf28081e0e4746549 | 3,633,753 |
import io
def load_image(image_path: str) -> np.ndarray:
"""
Read image from disk.
:param image_path: Path to input image.
:return: uint8 numpy array sized H x W.
"""
# load image
img = io.imread(image_path)
# assert img dtype
assert img.dtype == 'uint8'
return img | f524b5be404541ece8807455f4c0f450a9aa9fc1 | 3,633,754 |
def lowerUserList(inputList):
"""Lowercase user inputLists in case there are misspellings. (e.g. 3-6KB)"""
# clean list
loweredList = []
for item in inputList:
loweredItem = item.lower()
loweredList.append(loweredItem)
return loweredList | e5d55a39a98b741758c8b1e8306a4ee486c7a29d | 3,633,755 |
def na_cmp():
"""Binary operator for comparing NA values.
Should return a function of two arguments that returns
True if both arguments are (scalar) NA for your type.
By default, uses ``operator.or``
"""
return lambda x, y: x is None and y is None | 27c6324219af507d30d2ef763e731f2f6b525820 | 3,633,756 |
def get_list_files(initializer):
""" """
# get settings for find
roots, listOfExtension, ignoreLists, ignoreLists, ignoreLists = initializer()
resultArgv = ''
for pathes in roots:
for at in listOfExtension:
listSlice = list()
listSlice.append(at)
... | 23b19c3ceb6cb266a5e9bf1f9881917eab319b5b | 3,633,757 |
def constant(name, shape, value, dtype=tf.float32):
""" Creates a variable which is initiated to a constant value.
:param name: The name of the variable.
:param shape: The shape of the variable.
:param value: The constant value of the tensor.
:param dtype: The data type.
:return: A constant-ini... | 6878afa7dbd6485dd0373f6cd67fb0377f9957e1 | 3,633,758 |
def _cat_blob(repo, obj, bad_ok=False):
"""Call `git cat-file blob OBJ`.
Parameters
----------
repo : GitRepo
obj : str
Blob object.
bad_ok : boolean, optional
Don't fail if `obj` doesn't name a known blob.
Returns
-------
Blob's content (str) or None if `obj` is no... | 81a092d85b18106b7acb8c0df951267d56d07e40 | 3,633,759 |
import torch
def get_disp_samples(max_dis, feature_map, stage_id=0, disprity_map=None, step=1, samp_num=9, sample_spa_size=None) :
"""function: get the sampled disparities
args:
max_dis: the maximum disparity;
feature map: left or right feature map, N*C*H*W;
disprity_map: if it is not ... | d07bc06e69b0015f9604a91fe4455ef61bb3c505 | 3,633,760 |
def load_data(database_filepath):
"""
Load cleaned data from database_filepath
INPUT
database_filepath --filepath to csv dataset
OUTPUT
X - message column to predict Y values
Y - list of columns to be predicted
category_names - name of Y column names
"""
# load data from ... | a4e4eb2acbbe1bbc7f338b4dcfe1c19ff81dd968 | 3,633,761 |
def sigma_clip(array, flags=None, sigma=4.0, axis=0, min_N=4):
"""
one-iteration robust sigma clipping algorithm. returns clip_flags array.
Warning: this function will directly replace flagged and clipped data in array with
a np.nan, so as to not make a copy of array.
Parameters:
-----------
... | 9ce1ec8f261e0b548ae8feb3d6f5769f3994f64f | 3,633,762 |
from genrl.core import get_actor_critic_from_name
from genrl.core import get_value_from_name
from genrl.core import get_policy_from_name
from typing import Union
def get_model(type_: str, name_: str) -> Union:
"""
Utility to get the class of required function
:param type_: "ac" for Actor Critic, ... | 13e29ab4065425a1c68bfead5c8d6811b24234f3 | 3,633,763 |
def short_comment(x):
"""Ham comments are often short, such as 'cool video!'"""
return len(x.text.split()) < 5 | f8d91feb4549219275dd5bace104cd8d89b96748 | 3,633,765 |
def xxyy_basis_rotation(pairs, clean_xxyy=False):
"""Generate the measurement circuits."""
all_ops = []
for a, b in pairs:
if clean_xxyy:
all_ops += [
cirq.rz(-np.pi * 0.25).on(a),
cirq.rz(np.pi * 0.25).on(b),
cirq.ISWAP.on(a, b)**0.5
... | 4d5e5bfeb0b6ec6276fc8b640c600e3d2b8dc488 | 3,633,766 |
def partitions_class_attribute(data_points, attr_index):
"""Partitions data points using a given class attribute. Data points
with the same class label are combined into a partition.
:param data_points: List of tuples representing the data points.
:param attr_index: Index of the attribute inside the tup... | 848cce86bfbe052098caefb83bd0f27ca9703c74 | 3,633,767 |
def set_crop_to_volume(volume, bb_min, bb_max, sub_volume):
"""
set a subregion to an nd image.
:param volume: volume image
:param bb_min: box region minimum
:param bb_max: box region maximum
:
"""
dim = len(bb_min)
out = volume
if(dim == 2):
out[np.ix_(range(bb_min[0], b... | 54be20a0f1b9f85187adba68a2f5a9a3dec85d1c | 3,633,768 |
def display_image_grid(bounding_pts,image,skip_dilate=True,size = 2.5):
"""
construct a grid from the padded images and create the entire grid
displays the image
returns an image and list of all the digit images
"""
if not skip_dilate:
list_digits = [draw_block(i[0],i[1],image.copy(),ski... | fb539d899410b6c7824ce57fb21292a746abe464 | 3,633,769 |
import random
import string
def generate_random_name():
"""Generate a random name to use as a handle for a job."""
return "".join(random.choice(string.ascii_lowercase) for j in range(8)) | c793c77289e7813cfd679b23613a9b1cd38af941 | 3,633,770 |
def import_skymodel_from_hdf5(filename):
"""Import a Skymodel from HDF5 format
:param filename:
:return: SkyModel
"""
with h5py.File(filename, 'r') as f:
ncomponents = f.attrs['number_skycomponents']
components = [convert_hdf_to_skycomponent(f['skycomponent%d' % i])
... | b57e8ce7af13f303e6985690c45d1b99fb3b1755 | 3,633,773 |
import numpy
def grabocka_params_to_shapelet_size_dict(n_ts, ts_sz, n_classes, l, r):
"""Compute number and length of shapelets.
This function uses the heuristic from [1]_.
Parameters
----------
n_ts: int
Number of time series in the dataset
ts_sz: int
Length of time series ... | bc1016e57487374762d801de64059c4b5a5acd07 | 3,633,775 |
from typing import List
def precision_recall(
similarity_melted_df: pd.DataFrame, replicate_groups: List[str], k: int,
) -> pd.DataFrame:
"""
Determine the precision and recall at k for all unique replicate groups
based on a predefined similarity metric (see cytominer_eval.transform.metric_melt)
... | 518e667597d3b85683d3b49dd0426a514ef9997f | 3,633,777 |
def validate_index(n: int, ind: int, command: str):
"""
Simple function to validate existence of index within in the model repository.
Args:
n (int): length of indices
ind (int): selected index
command (str): name of command for "tailored" help message
"""
# ensure index e... | 3aef711caef041d2f4aa1dfdf0b5135d9f626b3c | 3,633,778 |
import requests
def search_page(request):
"""Page with search results."""
def _articles_filter(name):
"""Delete articles in product names
Arguments:
name {str} -- Name or generic name of product
"""
exclude = ("de", "des", "au", "aux", 'en', "le",
... | a41143e49cd1e94aa3341f6e30b3dc1d98b22882 | 3,633,779 |
def calculate_sa_expected_feature_counts(pi, mdp, epsilon=0.0001):
"""return dictionary of feature counts associated with each (s,a) pair"""
sa_fcounts = dict()
#compute feature expectations per state
fcounts = calculate_expected_feature_counts(pi, mdp, epsilon)
#(s,a) feature expectations are \phi(... | 19ebd9da4b722078d1f961da0774573176017742 | 3,633,780 |
def xmlToTag(tag):
"""The opposite of tagToXML()"""
if tag == "OS_2":
return "OS/2"
if len(tag) == 8:
return identifierToTag(tag)
else:
return tag + " " * (4 - len(tag))
return tag | 4c6e26f429e273f9b25adc25d262a523fda6467c | 3,633,781 |
def translate(num_list, transl_dict):
""" Translates integer list to number word list (no error handling!)
Args:
num_list: list with interger items.
transl_dict: dictionary with integer keys and number word values.
Returns:
list of strings which are the translated numbers into word... | dec1b25d64acf99dc04885f773ea42a55865bf8d | 3,633,782 |
def _1d_overlap_filter(x, n_h, n_edge, phase, cuda_dict, pad, n_fft):
"""Do one-dimensional overlap-add FFT FIR filtering."""
# pad to reduce ringing
x_ext = _smart_pad(x, (n_edge, n_edge), pad)
n_x = len(x_ext)
x_filtered = np.zeros_like(x_ext)
n_seg = n_fft - n_h + 1
n_segments = int(np.c... | 4c6825a2df425415d546e47f0c2ba24166e0bf2c | 3,633,783 |
def LED(state):
"""this is the arduino function that controls how the LED bulb with respect to what the webserver says"""
if state == True:
arduino.write(b'1')
print('the arduino is in the ON state')
return True
else:
arduino.write(b'0')
print('the arduino is in the O... | bcdc9bbc315215631af8ca0ef5bc48eb3b0b3b03 | 3,633,784 |
def noise_mean(corr, scale_factor = 1., mode = "corr"):
"""Computes the scalled mean noise from the correlation data estimator.
This is the delta parameter for weighted normalization.
Parameters
----------
corr: (ndarray,)
Correlation function (or difference function) model.
... | e94f04664888f981131fd406a1f55e404dcb1581 | 3,633,785 |
def get_python(uid):
"""Returns location of virtualenv python binary given UID"""
return get_venv_folder(uid) + '/bin/python' | b8e73ff14df2151915a55d11c1aaba9457dac4c3 | 3,633,786 |
def login():
"""View of login to the backstage"""
if current_user.is_authenticated:
return redirect(url_for('admin.index'))
form = LoginForm()
if form.validate_on_submit():
admin = Administrator.query \
.filter_by(name=form.name.data).first()
if admin is not None and... | e653f078c9f31477d13cc773db25a9bb2bb16ceb | 3,633,787 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.