content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def isrest(peak):
"""Determine whether the first 512 bytes are written in reST."""
try:
a, b = re.match('^(.+?)\n((?:-|=|#)+)', peak).groups()
except (ValueError, AttributeError):
return False
return len(b) >= len(a) | 2ba2f65611118e8de19542f10a8a9668cd1b03a3 | 34,095 |
def load_raw(stream):
""" Load a schism YAML
"""
# First round to get environmental variables
loader = RawLoader(stream)
try:
data = loader.get_single_data()
finally:
loader.dispose()
stream.seek(0)
# Second round with substitution
env = {}
for key in substitute_... | ab150dfac1d557b96f5e8e1b4ad6e186d786a6a9 | 34,096 |
def compare_time_stats(grouped, ref_grouped):
"""Given two nested dictionaries generated by get_dict_from_json, after running
calculate_time_stats on both, compare the performance of the given run to a reference
run.
A string will be returned with instances where there is a significant performance
difference... | cb6512533ca64c1f59af4a02a4f53f3996e95b0c | 34,097 |
from typing import Tuple
from typing import Type
from typing import Dict
from typing import Any
def task_name_to_model_class(name: str) -> Tuple[Type[GraphTaskModel], Dict[str, Any]]:
"""
Map task name to a model class and default hyperparameters for that class.
"""
task_info = TASK_NAME_TO_DATASET_AN... | ba7e391de5510c06fbb72abb2d0891931dce1ffd | 34,098 |
def compute_pairwise_similarities(string_series_1: pd.Series,
string_series_2: pd.Series,
**kwargs) -> pd.Series:
"""
Computes the similarity scores between two Series of strings row-wise.
:param string_series_1: pandas.Series. The input S... | 79a12c261f4b687689ab4747fcb04500a6b7258d | 34,099 |
def blur(img):
"""
:param img: the original image
:return: img, the blurred image
This function make image blurred
"""
old_image = img
blurred = SimpleImage.blank(old_image.width, old_image.height)
for y in range(old_image.height):
for x in range(old_image.width):
cou... | 6ddd8dd896b419d0d776aa36f249af93e5049a73 | 34,100 |
def _validator(record_type, ref):
"""
Create a DataValidator instance.
"""
if record_type == mds.STATUS_CHANGES:
return mds.DataValidator.status_changes(ref=ref)
elif record_type == mds.TRIPS:
return mds.DataValidator.trips(ref=ref)
else:
raise ValueError(f"Invalid record... | 5e5eb3288304ba9a3fa7635d698370e041a731bd | 34,102 |
def create_gif(pictures: list, watermark: str,
user_id: int, private=0) -> BytesIO:
"""
Creates gif with watermark from list of PIL images and adds it to database.
Returns BytesIO object
:param pictures: list of PIL.Image objects
:param watermark: watermark text, takes from user name
... | ff5fd0aeaf9e0b02ee99e7f75624d2a1340c0272 | 34,103 |
def ret_comb_index(bi_tot, get_indices=False, isotope=None):
"""
:param bi_tot:
:return:
"""
bi_1 = int(str(bi_tot)[-2:])
bi_2 = int(str(bi_tot)[0:-2])
if get_indices:
return (bi_1, bi_2 - 1, isotope)
else:
return (bi_1, bi_2 - 1) | 5647b273d4807aa876f6cd3bd28d287f60cf6296 | 34,106 |
def run_list(arg):
"""
Convert a :class:`~list` to a `RUN` instruction.
:param arg: List that represents instruction arguments.
:return: Fully-qualified `RUN` instruction.
"""
indent = len(run_list.instruction_name) + 1
return formatting.list_with_conditional_command_line_breaks(arg, indent... | a2652abed5df8ec5bcdc0df678a57b6d2425fe49 | 34,107 |
def count_loops(G):
"""
Count the loop edges in a graph.
Parameters
----------
G : NetworkX graph
"""
loops = get_loops(G)
return len(loops) | 58fdcf8aac09fa7a52d59f9fbbcba170313408ab | 34,108 |
async def post_projectversion_toggle_ci(request):
"""
Toggles the ci enabled flag on a projectversion.
---
description: Toggles the ci enabled flag on a projectversion.
tags:
- ProjectVersions
consumes:
- application/x-www-form-urlencoded
parameters:
- name: projectv... | f9c50607e90f0f910503b6557bd324ad3adba43e | 34,109 |
def edit_item(category, item):
"""App route function to edit an item."""
# Verify user login. If not, redirect to login page.
login_status = None
if 'email' in login_session:
login_status = True
else:
flash('Please log in.')
return redirect(url_for('home'))
# Query databa... | e8300e083da286544d58c5e4aaa59cdc126414ac | 34,110 |
def sanity_check_gcon():
"""Sanity check gcon."""
cmd = gcon_py + " --help"
errmsg = gcon_py + " is not installed."
execute(cmd=cmd, errmsg=errmsg)
return gcon_py | 11585da8701edc482ab2d0588f1d983d32b5e1c4 | 34,111 |
import requests
import json
def get_Cust_Bookings_Hours(request, *args, **kwargs):
"""Request Chart Points per Themes"""
bookings_H_tmp = requests.get('http://127.0.0.1:5000/customer/bookings/hours').text
bookings_Hours_list = json.loads(bookings_H_tmp)
bookings_Hours = [
['Heures', 'Nombre de... | 9463cb31da46f751014a14d6daeb28df3d0c8cfe | 34,113 |
def judo_turnier():
"""Show participants for judo turnier."""
participants = Participant.query.filter_by(user_id=current_user.id,
event=EVENT_JUDO_TURNIER).all()
form = ParticipantDeleteForm(request.form)
return render_template('events/judo-turnier.html', ... | 78614761f183d1280eeb80e08e17500fed62d25a | 34,116 |
def preprocess_mapper(features, params, lookup_table):
"""Model-specific preprocessing of features from the dataset."""
features["question_inputs"] = text_utils.build_text_inputs(
text=features["question"],
length=params["question_length"],
lookup_table=lookup_table)
features["context_inputs"] ... | 5454cf1149982ddc3314fb9793123b16e70e1381 | 34,118 |
import logging
def get_user_playlists():
"""Return all of the user's playlists"""
logging.info("fetching user playlists")
url = "https://api.spotify.com/v1/me/playlists"
return get_all_pages(url) | 17d96f81ccf78cc0d9210968deb6a9550f82f34c | 34,119 |
def set_circuit_ic_mrucc(n_qubits, v_n, a_n, c_n, DS, theta_list, ndim1, a2a):
"""
"""
circuit = QuantumCircuit(n_qubits)
if DS:
circuit = icmr_ucc_singles(circuit,v_n, a_n, c_n, theta_list, 0)
circuit = icmr_ucc_doubles(circuit,v_n, a_n, c_n, theta_list, ndim1, a2a)
else:
c... | 7a3fc8474f07b926b49980b467cbb8c19a24d8b8 | 34,120 |
def dct2spatial(image):
"""
Rearrange DCT image from [H//8, W//8, 64] to [H,W]
"""
assert image.shape[2] == 64
block_view = (image.shape[0], image.shape[1], 8, 8)
image_shape = (image.shape[0] * 8, image.shape[1] * 8)
block_permute = 0, 2, 1, 3
result = image.reshape(block_view).transp... | a1052b2f851a59eabb28c672f01547b5c4797bbc | 34,121 |
def theta2rotx(theta: np.ndarray) -> np.ndarray:
"""
Rx = [[1, 0, 0],
[0, c(t), -s(t)],
[0, s(t), c(t)]]
:param theta: angle(s) in degrees, positive is counterclockwise
:return: rotation_matrices
"""
theta = np.deg2rad(np.asarray(theta).reshape(-1))
rotation_matrices = np... | 48aaa4a84b49495f2106fba7dc70749865001811 | 34,122 |
from datetime import datetime
def json_serializer(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
# Serialize datetime as the ISO formatted string
serial = obj.isoformat()
return serial
raise TypeError("Type not serializa... | dfc2ebf9f254cd9f3723144b4d97839159a428f7 | 34,124 |
def leaves_f(prog, typ):
"""Doc."""
return list(filter(lambda it: type(it), leaves(prog))) | 4119e92c2bd5c910b5a9b5badca69fd09dedc429 | 34,126 |
def imshow_xy(axes, coord, data,
xy_limits=None, xy_pad=0.02, add_lines=False,
step_kw=None, line_kw=None, **kwargs):
""" Show data as an image in ax, with slices at x and y in
the subplots axy and axx.
img = ax.imshow(data)
step_x = axx.step(data[coord[1], :... | e8727c5a7c3dd114e6beda1c171156f636e08b28 | 34,127 |
import re
def create_endpoint(project_id: str, region: str, endpoint_name: str) -> str:
"""
Create an endpoint on Vertex AI
:param project_id:
:param region:
:param endpoint_name:
:return:
"""
try:
endpoint = aiplatform.Endpoint.create(display_name=endpoint_name, project=proje... | 383fb8961050e31270f5f4c9b68008864ce34ae9 | 34,128 |
import logging
def get_warning_logger() -> logging.Logger:
"""
Set up a logger to capture warnings and log them
"""
logging.captureWarnings(True)
warning_logger = logging.getLogger('py.warnings')
if warning_logger.handlers: warning_logger.handlers = []
return warning_logger | 5cdf76ff66963851715b3302c02681340d2f6a72 | 34,129 |
def check_type_match(actual_val, expected_val) -> bool:
"""Check actual_val matches type of expected_val
The exception here is that expected_val can be
float, and in that case actual_val can be either
int or float
Args:
actual_val (Any): Actual type
expected_val (Any): Expe... | 90f74b1978deb0c55b65a4faa2569f54fe6bceee | 34,130 |
from typing import Callable
from typing import Tuple
def _single_step_smart_generalized_leapfrog(
grad_log_posterior: Callable,
metric: Callable,
grad_metric: Callable,
grad_log_posterior_and_metric_and_grad_metric: Callable,
zo: Tuple[np.ndarray],
step_size: float,
... | f091280bcda175ec0b1b399825a484e5d725c82a | 34,131 |
def real_sph_harm(l, zero_m_only=True, spherical_coordinates=True):
"""
Computes formula strings of the the real part of the spherical harmonics up to order l (excluded).
Variables are either cartesian coordinates x,y,z on the unit sphere or spherical coordinates phi and theta.
"""
if not zero_m_onl... | cff7053e02600934f8b00a4d74fffeb6223fc1d3 | 34,132 |
def drsky(x, ecc, omega, inc):
"""Function whose roots we wish to find to obtain time of secondary
(and primary) eclipse(s)
When one takes the derivative of equation (5) in Winn
(2010; https://arxiv.org/abs/1001.2010v5), and equates that to zero
(to find the minimum/maximum of said function), one g... | 03238e267760e081f4f69367e7e37f46877072cf | 34,133 |
from typing import List
import types
from typing import Iterator
from typing import Tuple
from typing import Dict
from typing import Any
def ComputeQueryBasedMetrics( # pylint: disable=invalid-name
extracts: beam.pvalue.PCollection,
prediction_key: str,
query_id: str,
combine_fns: List[beam.CombineFn... | ee3907109a8ff0c67f02e5d9b2296c3955bd501f | 34,134 |
def get_brier_scores(at_time_intervals, censored_indicator=1.0):
"""Construct Brier score metrics for survival probability predictions."""
metrics = []
for t in at_time_intervals:
metric = partial(
brier_score, t=t, censored_indicator=censored_indicator)
metric.__name__ = 'bs_at_... | 58a23d2c7706761a68bfd375b20400dc075a4c96 | 34,135 |
def create_id_maps(session):
"""
Create a large universal map of maps that carries common items like
"Allegiance" or "Government" onto the id expected to be inserted into the db.
Returns: A adict of dicts that ultimately points to integer ids in the db.
"""
maps = {
'Allegiance': {x.edd... | ae5f30fc4338c61b26087b3d6d5f30d87e7b97cd | 34,136 |
def _box_without_row_and_column_of(row, col, width, height):
"""Return some coordinates in the square of (col, row) as a list.
The coordinates in the same row and column are removed.
This is an internal function and should not be used
outside of the coordinates module.
"""
grid_x = col - (col ... | e7dc91611788fb5e22a70d30edcda5708f751085 | 34,137 |
def fieldtype(field):
"""Get the type of a django form field (thus helps you know what class to apply to it)"""
return field.field.widget.__class__.__name__ | e2d68cbdd72219de1a23095100c054a46c6c191b | 34,138 |
def fitToIntervals(areas: list, num_of_bins: int):
"""
fitting the area of each contour to the suitable interval.
:param areas: a list of contour areas.
:param num_of_bins: the number of intervals.
:return: a list containing each suitable interval for a given area.
"""
intervals = findInter... | aa731e7ed298c55649242923a774e07da308b757 | 34,140 |
def get_team_repo(remote_url):
"""
Takes remote URL (e.g., `git@github.com:mozilla/fireplace.git`) and
returns team/repo pair (e.g., `mozilla/fireplace`).
"""
if ':' not in remote_url:
return remote_url
return remote_url.split(':')[1].replace('.git', '') | 5e0120881557e9d95b697ab194fd7a8e8a84c68d | 34,144 |
def ajax_request(func):
"""
If view returned serializable dict, returns JSONResponse with this dict as content.
example:
@ajax_request
def my_view(request):
news = News.objects.all()
news_titles = [entry.title for entry in news]
return {'news_tit... | a672e3164af2c282fa301d351434ce863e7b2204 | 34,145 |
def load_collection_from_file(resource, filename, content_type=None):
"""
Creates a new collection for the registered resource and calls
`load_into_collection_from_file` with it.
"""
coll = create_staging_collection(resource)
load_into_collection_from_file(coll, filename,
... | c85eb82ee3633c69bef5ceb8b2954ea0fd700798 | 34,146 |
import requests
import time
def get_fxa_token(*, code=None, refresh_token=None, config=None):
"""Given an FxA access code or refresh token, return dict from FxA /token endpoint
(https://git.io/JJZww). Should at least contain `access_token` and
`id_token` keys.
"""
assert config, 'config dict must ... | d0e0b70fd4b6adc7f944b68eb0788b82eed6344d | 34,148 |
def merge_connected_components(conn_components, ingoing, outgoing):
"""
Merge the unconnected connected components
Parameters
-------------
conn_components
Connected components
ingoing
Ingoing dictionary
outgoing
Outgoing dictionary
Returns
-------------
... | 15dda42103aab964a9a67ca763e17ba63d552457 | 34,149 |
def create_doc_index(ui_mat_rdd,
export=False):
"""
Indexes the docs and saves the index in a dictionary. The indexes are
then saved to disk. The indexing allows us to use internal integer IDs
for the users and documents instead of real IDs. The internal IDs are used
to index the different model matrices efficie... | 97874b0effaa93b35760330abaa1fc23628389d6 | 34,151 |
def read_markers_from_file(filepath, ext=None):
"""
Read a cell marker file from accepted file formats.
Currently supported: csv, tsv.
See doc for formatting.
"""
# Get extension
if ext is None:
ext = filepath.split('.')[-1]
dict_format = {"csv":read_markers_csv, "tsv":read_marke... | 5c2a34bf3d568d1b0f9e81c23d23eba315059ee3 | 34,152 |
def get_user_id_from_email(email):
""" Pulls the user from the MDB (or dies trying). Returns its email. """
u = utils.mdb.users.find_one({'login': email.lower().strip()})
if u is None:
raise AttributeError("Could not find user data for %s" % email)
return u['_id'] | c81d9d62bc3ecd9d37afef3f38b5735b5bb0215b | 34,153 |
def _object_exists(key):
"""Verify if a given key (path) exists, using the S3 API."""
try:
app.s3.head_object(Bucket=app.config.get("AWS_S3_BUCKET_NAME"),
Key=key)
except ClientError as e:
if e.response["Error"]["Code"] == "404":
return False
ra... | 65ca7932412f988518f40a6830d512049e40fe31 | 34,154 |
def dpgmm_predict(data:pd.DataFrame,
code=None,
indices:pd.DataFrame=None,) -> np.ndarray:
"""
(假设)我们对这条行情的走势一无所知,使用机器学习可以快速的识别出走势,划分出波浪。
DPGMM聚类 将整条行情大致分块,这个随着时间变化会有轻微抖动。
所以不适合做精确买卖点控制。但是作为趋势判断已经足够了。
"""
sub_offest = 0
nextsub_first = sub_first = 0
... | b12365f50a498d2ece6be65a0a284aad9c235274 | 34,155 |
from typing import List
def list_ep(server: Server, path: str, r_type: OT = OT.DOMAIN, scope: EPScope = None) -> List[str]:
"""
List elements under an object fitting a type.
:param Server server: server object
:param str path: path to object
:param OT r_type: type of ep to return (default is doma... | ccf90a435b72e4e822ef2c580304c889bc4f4136 | 34,156 |
import re
def check_if_partial(comments):
"""
Checks if comments contain info about Dat being a part of a series of dats (i.e. two part entropy scans where first
part is wide and second part is narrow with more repeats)
Args:
comments (string): Sweeplogs comments (where info on part#of# shoul... | 6f565bae6fe1cf5da4a11e0d511a25daa07aadd1 | 34,157 |
def cardChunk(key, chunk):
"""
Parse Card Chunk Method
"""
for line in chunk:
values = []
sline = line.strip().split()
for idx in range(1, len(sline)):
values.append(sline[idx])
return {'card': sline[0],
'values': values} | 84b8a12f701078f2ebcf19a5c1902b1e370b16e6 | 34,159 |
def update_outline(outline, filename=None, message=None):
"""
Updates the the outline from active instances in the workspace
"""
if not message:
message = "Automated update via presalytics.lib.tools.workflows.update_outline()"
update_components(filename=filename)
for p in range(0, ... | 3582d47b641c4e554f2b2f0e38110fd98343476c | 34,160 |
def slave_hub_factory(config, comm_class, comm_config):
"""Factory of management bus slave hub instances
Args:
config (dict): management bus master config
comm_class (string): communication backend.
Unused, ZMQRedis is always used
comm_config (dict): config of the communicat... | b421c065158aa3e7fd07fc28ccdd72ffc24045ec | 34,161 |
def rgb565_to_rgb(arr, out=None):
"""
Convert a numpy :class:`~numpy.ndarray` in RGB565 format (unsigned 16-bit
values with 5 bits for red and blue, and 6 bits for green laid out
RRRRRGGGGGGBBBBB) to RGB format (structured floating-point type with 3
values each between 0 and 1).
"""
check_r... | 5c660169cdfd47a0d513a833356c82557ff636bb | 34,162 |
def run_highstate_tests(saltenv="base"):
"""
Lookup top files for minion, pass results to wrapped run_state_tests for copy and run
"""
top_states = __salt__["state.show_top"]().get(saltenv)
state_string = ",".join(top_states)
ret = run_state_tests(state_string, saltenv)
return ret | 3e12d102a44e8233eb539c1636f19eebb23da266 | 34,163 |
def varianceOfLaplacian(img):
""" Compute the Laplacian of the image and then return the focus measure,
which is simply the variance of the Laplacian.
Source: A.Rosebrock, https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/
"""
return cv2.Laplacian(img, cv2.CV_64F).var() | 8a80c40f24c1a282ae7a46c521e4cb3a975451ee | 34,164 |
def show(tournament, participant_id, **params):
"""Retrieve a single participant record for a tournament."""
return api.fetch_and_parse(
"GET", "tournaments/%s/participants/%s" % (tournament, participant_id), **params
) | bf1e43ab2b071343405a09659580d5d8311d0dff | 34,166 |
def logsubexp(A, B):
"""
Numerically stable log(exp(A) - exp(B))
"""
# Just adding an epsilon here does not work: the optimizer moves it out
result = A + tt.log(1 - tt.clip(tt.exp(B - A), epsilon, 1-epsilon))
return result | 0bd07fec6cfe3247e7dffd0af1794306f34601f1 | 34,167 |
import collections
def sort_dict(d: dict, by: str = 'key',
allow_duplicates: bool = True) -> collections.OrderedDict:
"""
Sort a dictionary by key or value.
The function relies on
https://docs.python.org/3/library/collections.html#collections.OrderedDict .
The dulicated are determin... | 59ea66e44b9a41161e38e243f49e5a20df20093f | 34,168 |
def read_file_info(filename):
"""
Read an info file.
Parameters
----------
filename : string
The name of file with cross-sectional area and length information.
Returns
-------
info : dict
The values of cross-sectional area and length of the specimens,
"""
fd = o... | c3f8c106126b45845c1202b34b19cad2ce2ae036 | 34,169 |
def search_to_new_ids(index, query, k):
"""
this function maps the result ids to the ones ordered by the ivf clusters
to be used along with a re-ordered metadata
"""
distances, indices = index.search(query, k)
opq2 = faiss.downcast_VectorTransform(index.chain.at(0))
xq = opq2.apply(query)
... | 62fc04b67bfa3aaf6ceed5a5f8bd65e1e7783cc9 | 34,170 |
import itertools
def build_simplex_lattice(factor_count, model_order = ModelOrder.quadratic):
"""Builds a Simplex Lattice mixture design.
This design can be used for 2 to 30 components. A simplex-lattice mixture
design of degree m consists of m+1 points of equally spaced values between
0 and 1 for ea... | 9a6861a211b6829b971cf76ab8f1bbcb2bb668ae | 34,171 |
def position_specializations(position_block):
"""
:param bs4.Tag position_block: position block
:return: list
"""
position_block = position_block.find("div", {"class": "bloko-gap bloko-gap_bottom"})
profarea_name = position_block.find("span", {"data-qa": "resume-block-specialization-category"})... | c37a43b2c139780d0bcb0db2cb758165d155a526 | 34,172 |
def GetElement(layers, locations):
"""
Return the node(s) at the location(s) in the given layer(s).
This function works for fixed grid layers only.
* If layers contains a single GID and locations is a single 2-element
array giving a grid location, return a list of GIDs of layer elements
at... | 6fecffa20aa9d4722153c50572c9ded26035c1f3 | 34,173 |
def create_sampling_strategy(param_variation_model,
sampling_strategy_configuration):
"""
A factory method that creates a
memosampler.strategies.SamplingStrategy object from a
memosampler.sampler.ParameterVariationModel and a
memomodel.SamplingStrategy configuration obje... | f93451eb1b3739ac2985bd4a2b8bb84ed0b6f9f5 | 34,174 |
def json_to_hps(dct):
"""Translate the params dict to HyperparameterSpace object.
:param dict dct: params dict.
:return: HyperparameterSpace.
:rtype: HyperparameterSpace or None
"""
if "hyperparameters" in dct:
hps = HyperparameterSpace()
for hp_dict in dct["hyperparameters"]:
... | 0f80da7d4fb5d3d548cc23edf7761976db727654 | 34,175 |
def phone_number(update: Update, context: CallbackContext):
"""Добавляет номер телефона в контекст пользователя и предлагает ввести ИНН"""
logger.info(f"User with chat_id {update.effective_user.id} sent phone number [{update.message.text}]")
context.user_data[State.PHONE_NUMBER] = update.message.text
... | b41cebc8b47e9e3ef729ddd7ebea560f143be071 | 34,176 |
from typing import Optional
from typing import Union
def downsample_adata(adata: AnnData,
mode: str = 'total',
n_cells: Optional[int] = None,
by: Optional[str] = None,
balance_cell_type: bool = False,
random_state... | d1de9ac6c347750ed4ebfb1b8f870b8bc613f20d | 34,178 |
def parse_blob(value, offset=0, **kwargs):
"""Return a blob from offset in value."""
size = calcsize('>i')
length = unpack_from('>i', value, offset)[0]
data = unpack_from('>%iQ' % length, value, offset + size)
return data, padded(length, 8) | 855b55394d8fbe5a3e05e98997185d87051b56a2 | 34,179 |
from datetime import datetime
def _get_now(utc: bool = False) -> datetime.datetime: # pragma: nocover
"""Workaround over datetime C module to be able to mock & patch in tests.
"""
if utc:
return datetime.datetime.utcnow()
return datetime.datetime.now() | 7b71266bf46d464bb8515d5552752f2b7739262e | 34,180 |
def dilation(image, selem, out=None, shift_x=False, shift_y=False):
"""Return greyscale morphological dilation of an image.
Morphological dilation sets a pixel at (i,j) to the maximum over all pixels
in the neighborhood centered at (i,j). Dilation enlarges bright regions
and shrinks dark regions.
... | 2485ddf865f4476dc0c46f89bc789948d9c47153 | 34,181 |
def nice_layer_name(weight_key):
"""Takes a tuple like ('weights', 2) and returns a nice string like "2nd layer weights"
for use in plots and legends."""
return "Layer {num} {name}".format(num=weight_key[1] + 1, name=weight_key[0]) | c88dd554c2a3cf35e6d6e96131833738c19766ac | 34,183 |
def categories(request, structure_slug, structure):
"""
Retrieves structure categories list
:type structure_slug: String
:type structure: OrganizationalStructure (from @is_manager)
:param structure_slug: structure slug
:param structure: structure object (from @is_manager)
:return: render
... | c322b754de2ed36e98088a1d494f807589d1fbc2 | 34,184 |
def do_quantize_training_on_graphdef(input_graph, num_bits):
"""A general quantization scheme is being developed in `tf.contrib.quantize`.
Consider using that instead, though since it is in the tf.contrib namespace,
it is not subject to backward compatibility guarantees.
Args:
input_graph: A `GraphDef`.
... | 868a2c67d7c69270039af69e82110951a987480c | 34,186 |
from typing import List
from typing import Tuple
def get_session_triplets(
sessions: List[int], match_types: List[int]
) -> Tuple[List[int], List[int], List[int]]:
"""Generate all possible triplets for each session.
:param sessions: A list of integers denoting session label
:param match_types: A list... | 39992557bc788f4b8bb5248cd66f56bf4276d99c | 34,187 |
def _rotation_matrix_hme_to_hee(hmeframe):
"""
Return the rotation matrix from HME to HEE at the same observation time
"""
# Get the Sun-Earth vector
sun_earth = HCRS(_sun_earth_icrf(hmeframe.obstime), obstime=hmeframe.obstime)
sun_earth_hme = sun_earth.transform_to(hmeframe).cartesian
# Ro... | 157378316058b4898b9ecccb8acf673c4170c03b | 34,188 |
def get_image(microscopy_collection, series):
"""Return microscopy image."""
image = microscopy_collection.image(s=series)
image = image[:, :, 0]
return image | d95b213c8db49e89d2bcaa3f7b69c0f4d546ac1c | 34,189 |
def process_aa_snvs(aa_snv_dict, name, defs):
"""
Parameters
----------
aa_snv_dict: dict
name: str
defs: pandas.DataFrame
- genes or proteins dataframe from genes_and_proteins.py
"""
aa_snv = (
pd.DataFrame.from_dict(aa_snv_dict, orient="index", columns=["id"])
.... | f9dbf499bc7baf311e2c1063167e40570f40d218 | 34,191 |
def use_file(filename):
""" Return a decorator which will parse a kicad file
before running the test. """
def decorator(test_method):
""" Add params to decorator function. """
@wraps(test_method)
def wrapper(self):
""" Parse file then run test. """
self.desi... | c381fa417ae3226f7a4a5bac3fa907821dd76876 | 34,192 |
def create_autoscaler(gce, mig, params):
"""
Create a new Autoscaler for a MIG.
:param gce: An initialized GCE driver object.
:type gce: :class: `GCENodeDriver`
:param mig: An initialized GCEInstanceGroupManager.
:type mig: :class: `GCEInstanceGroupManager`
:param params: Dictionary of ... | 1be818388aa48b70f4252937a4db44671d03581e | 34,193 |
from typing import List
def chromium_all(*, min_major_version: int = 90, min_minor_version: int = 40) -> List[str]:
"""get chrome versions"""
resp = Request.get(CHROME_REP_URL)
versions = RE_CHROMIUM.findall(resp)
versions = [v for v in versions if len(v.split(".")) > 2 and (int(v.split(".")[-1]) >= m... | 900e4b24417e3c778218614c65787931631d2fbd | 34,194 |
def setup(hass, config):
"""Setup platfrom"""
async def async_auto_scale(call):
"""Call auto scale service handler."""
await async_handle_auto_scale_service(hass, call)
hass.services.register(
DOMAIN,
SERVICE_AUTO_SCALE,
async_auto_scale,
schema=AUTO_SCALE_S... | 61cc3d2b0461bb78a745a53dee1dc5bfb1a4a75f | 34,195 |
from re import X
from datetime import datetime
def train_linear_clf(n_fits):
"""Called by the `/train` HTTP GET method in `logic.py` module.
Parameters
----------
n_fits : int
Number of partial fits applied to the linear estimator.
Returns
-------
dict
measured_accuracy : float
Accuracy ... | 8430edf945d03e6c68ca1fe5944ed6957d4e3857 | 34,197 |
def list_joysticks():
"""return list of all joystick names"""
joysticks = get_all_joysticks()
return [joy.get_name() for joy in joysticks] | a04e584fe5d35b21cde1b44274bb725ea95260bc | 34,198 |
def kurtosis(inlist):
"""
Returns the kurtosis of a distribution, as defined in Numerical
Recipies (alternate defn in CRC Standard Probability and Statistics, p.6.)
Usage: lkurtosis(inlist)
"""
return moment(inlist, 4) / pow(moment(inlist, 2), 2.0) | e5df631d9d5d81ca9e2df8d7b7723eb723c696db | 34,199 |
def compute_iou(box, boxes):
"""Calculates IoU of the given box with the array of the given boxes.
box: a polygon
boxes: a vector of polygons
Note: the areas are passed in rather than calculated here for
efficiency. Calculate once in the caller to avoid duplicate work.
"""
# Calculate inters... | 169cb66f025c7a3f6161a406bd6b0636a35816d3 | 34,200 |
def far(scores, labels, frr_op):
"""
Calculates FAR from FRR operating point.
Parameters
----------
scores: np array
It holds the score information for all samples (genuine and impostor).
It is expected that impostor (negative) scores are, at least by design, greater than genuine (... | 9873f854887982e6aa393eb4fa0b915f31dbd15f | 34,201 |
def iso_to_plotly_time_string(iso_string):
"""Remove timezone info and replace 'T' delimeter with ' ' (ws)."""
# make sure we don't send timezone info to plotly
if (iso_string.split("-")[:3] == "00:00") or (iso_string.split("+")[0] == "00:00"):
raise Exception(
"Plotly won't accept times... | 2a8f8dede7a50d07e283897bf6028fbfdcaa90d6 | 34,202 |
def mk_vis_txt_pair_datalist(anno_path, data_ratio=1.0,
vis_id_key="coco_id", txt_key="caption"):
"""
Args:
anno_path: str, path to .jsonl file, each line is a dict
data_ratio: float, (0, 1], when < 1, use part of the data.
vis_id_key: str, image/video file i... | 3c36ff18f447e0ce5977d39c0bdc14bda94e3a64 | 34,203 |
def index_greater(array, prec=1e-8):
"""
Purpose:
Function for finding first item in an array that has a value greater than the first element in that array
If no element is found, returns None
Precision:
1e-8
Return:
int or None
"""
item=array[0]
for idx, val ... | 43f9401dc37426b1514ff1eb9dda79c39e347a7a | 34,204 |
import torch
def get_ssl_sampler(labels, valid_num_per_class, annotated_num_per_class, num_classes):
"""
:param labels: torch.array(int tensor)
:param valid_num_per_class: the number of validation for each class
:param annotated_num_per_class: the number of annotation we use for each classes
:para... | 05d7aa1700c096bc7a8250251cc73969c46ddabf | 34,205 |
import copy
def load_parse_dict():
"""Dicts for parsing Arc line lists from NIST
Rejected lines are in the rejected_lines.yaml file
"""
dict_parse = dict(min_intensity=0., min_Aki=0., min_wave=0.)
arcline_parse = {}
# ArI
arcline_parse['ArI'] = copy.deepcopy(dict_parse)
arcline_parse[... | b02ae8446b9cc198ac1908dbbbe2bec78088178b | 34,206 |
def is_test(method) -> bool:
"""
Checks if the given method is a test method.
:param method: The method to check.
:return: True if the method is a test method,
False if not.
"""
return getattr(method, _constants.IS_TEST_ATTRIBUTE, False) | 23b5dc04b29b029ca5c44dc57df59f63087d61a6 | 34,207 |
def data_transform(array, array2=np.asarray((None)),type='z_score_norm', means=None, stds=None):
"""
Transforms data in the given array according to the type
array :an nd numpy array.
array2 :an nd numpy array(optional-for multidimensional datasets)
type :'z_score_norm' = implements z score n... | f851bce2f0a88717873544506361bd6ef7c73813 | 34,208 |
import re
def load_items(reader):
"""Load items from HDF5 file:
* reader: :py:class:`guidata.hdf5io.HDF5Reader` object"""
with reader.group("plot_items"):
names = reader.read_sequence()
items = []
for name in names:
klass_name = re.match(
r"([A-Z]+[A-Za-z0-9\_]*)\_(... | ba473b9aa8c5af2beba8e22c68646a3204179c3d | 34,209 |
def zmatrix(file_prefix):
""" generate zmatrix JSONObject
:param file_prefix: path to file
:type file_prefix: str
:param json_prefix: top level keys
ex: ('energy', ['gaussian', 'b3lyp', 'cc-pvdz', 'RR'])
:type json_prefix: tuple
:return: instance of JSONObject class
:rtype: JSONObje... | 9f22e8f4480fe21b853101a4cfb58c641207a0c1 | 34,210 |
def sequence_nd(
seq,
maxlen=None,
padding: str = 'post',
pad_val=0.0,
dim: int = 1,
return_len=False,
):
"""
padding sequence of nd to become (n+1)d array.
Parameters
----------
seq: list of nd array
maxlen: int, optional (default=None)
If None, will calculate m... | 83ec761d679b2c91592e000e1ee832341645a8e9 | 34,211 |
def random_dists(filename):
"""
Given a Excel filename with a row for each variable and columns for the
minimum and maximum, create a dictionary of Uniform distributions for
each variable.
Parameters
----------
filename : string
Number of parameter settings to generate
... | d49229064979deb671fcade3518d260450718130 | 34,212 |
import re
def is_changed(event, old_event):
"""
Compares two events and discerns if it has changes that should trigger a push
:param event:
:param old_event:
:return: bool
"""
# Simple changes
if any(
event.get(field) != old_event.get(field) for field in ["severity", "certaint... | a0c403caf71fb5547a4b4c7a52d3fcdcef4c4b34 | 34,213 |
def view(self, view_id):
"""Get a particular view belonging to a case group by providing view id
Arguments:
id(int): view id
Returns:
List of :class:`rips.generated.generated_classes.EclipseView`
"""
views = self.views()
for view_object in views:
if view_object.id == v... | 0dadbe53c326d2d324e11222b2a751a09750bc82 | 34,214 |
from typing import Tuple
def enu2geodetic(
e: ndarray,
n: ndarray,
u: ndarray,
lat0: ndarray,
lon0: ndarray,
h0: ndarray,
ell: Ellipsoid = None,
deg: bool = True,
) -> Tuple[ndarray, ndarray, ndarray]:
"""
East, North, Up to target to geodetic coordinates
Parameters
---... | d552b072a428042435703f453a0f90bb9a1fded5 | 34,215 |
def Standard_GUID_HashCode(*args):
"""
* H method used by collections.
:param aguid:
:type aguid: Standard_GUID &
:param Upper:
:type Upper: int
:rtype: int
"""
return _Standard.Standard_GUID_HashCode(*args) | 951ed1db9f0bc7c33345969e0b234bf31aaf463b | 34,216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.