content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def find_bad_frames(ds, reindex=True):
"""
Find the frames that have fewer cells than the previous frame.
Parameters
----------
ds : (S, T, ..., Y, X) DataSet
reindex : bool, default: True
Whether to reindex each frame as well.
Returns
-------
bad : list
With entrie... | 78ae0ff38834bf0bc29571e68b7cd1497e652fe9 | 48,770 |
def get_most_energetic_neutrino(particles):
"""Get most energetic neutrino.
Parameters
----------
particles : ndarray of dtype I3PARTICLE_T
Returns
-------
most_energetic_neutrino : shape () ndarray of dtype I3PARTICLE_T
"""
return get_best_filter(
particles=particles, fil... | 54add5340ba911a2e836b1386fd4ca6b5f72e9c8 | 48,772 |
def cria_coordenada(linha,coluna):
"""int x int -> tuple
Esta funcao recebe duas coordenadas do tipo inteiro, a primeira correspondente a linha e a segunda a coluna e devolve um elemento do tipo coordenada, ou seja, o tuplo (linha,coluna)"""
if 1<=linha<=4 and 1<=coluna<=4 and isinstance(linha,int) and isin... | b2d216a11706e4234cf9943525cfca72118a98f8 | 48,773 |
def identify_groups(ref_labels, pred_labels, return_overlaps=False):
"""Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_... | b7c6588946c005c6507b5f486930514dd6b91864 | 48,774 |
def commit_config(node, raid_controller, reboot=False, realtime=False):
"""Apply all pending changes on a RAID controller.
:param node: an ironic node object.
:param raid_controller: id of the RAID controller.
:param reboot: indicates whether a reboot job should be automatically
crea... | eead48d5a8eeb6591343d598e6c232ad7bb437f5 | 48,775 |
from typing import Tuple
from typing import Optional
def link(g: Graph, subject: Node, predicate: URIRef) -> Tuple[Optional[URIRef], Optional[URIRef]]:
"""
Return the link URI and link type for subject and predicate
:param g: graph context
:param subject: subject of linke
:param predicate: link pr... | 3a329697413ebe0d6218d388d74306643590f3e3 | 48,776 |
def list_pages(page_obj: Page) -> Page:
"""
Gets a paginator page item and returns it with a list of pages to display like:
[1, 2, "…", 17, 18, 19, "…" 41, 42]
Currently not in use, simpler pages lists are implemented.
"""
last_page_number = page_obj.paginator.num_pages
pages_list = [1, 2]
... | 40b225f45fe4868c7b3ef361a7cc9df432efaf78 | 48,777 |
from typing import List
import json
def compare_apache_profiles(baseline_file, test_file, threshold=0.5) -> List:
"""
Compare baseline Apache access log profile against test profile.
:param baseline_file: file containing baseline profile
:param test_file: file containing test profile
:param thresh... | 0b94ad318fcb61be559767cbdba51def1b6db61f | 48,778 |
def cyclic_sort(nums):
"""
0 1 2 3 4 5
[1, 2, 3, 4, 5]
^
[1, 2, 3, 4, 5, 6]
^
"""
for i in range(0, len(nums)):
while nums[i] != i + 1:
j = nums[i] - 1
nums[i], nums[j] = nums[j], nums[i]
return nums | fc9f7061121d4509b260e03df4edeee63c0eb6b9 | 48,780 |
def _build_section_path_map():
"""
Simple wrapper around Django's low level cache; stores and populates
a list of all section urls using the low-level caching framework.
"""
paths = {}
Section = app_settings.get_extending_model()
for section in Section.objects.all():
paths[section.f... | e89657ec68e4c1dab31f172e4d5aa8f98681aa5e | 48,781 |
def unfold_arrow(arrow):
"""Extract a list of types from an arrow type
:param arrow: A type, preferably an arrow type
:type arrow: :class:`discopy.closed.Ty`
:return: A list of the arrow's components, or of the original type
:rtype: list
"""
if isinstance(arrow, Under):
return [arr... | 365a35e87bdb0edcd81cba8e44c4151cf5cb701c | 48,782 |
def test_step(X, m_pre, m_fp):
""" Test step used for mini-search-validation """
X = tf.concat(X, axis=0)
feat = m_pre(X) # (nA+nP, F, T, 1)
m_fp.trainable = False
emb_f = m_fp.front_conv(feat) # (BSZ, Dim)
emb_f_postL2 = tf.math.l2_normalize(emb_f, axis=1)
emb_gf = m_fp.div_enc(emb_f)
... | c444a0935640f09122999efa3c382be15daab833 | 48,783 |
import json
def calc_sett_rewards(badger, periodStartBlock, endBlock, cycle, unclaimedRewards):
"""
Calculate rewards for each sett, and sum them
"""
# ratio = digg_btc_twap(periodStartBlock,endBlock)
# diggAllocation = calculate_digg_allocation(ratio)
rewardsBySett = {}
noRewards = ["nati... | 7fa93585fbe5b1f461b24dc6a9a7d655aca4f7a7 | 48,784 |
def get_detector_module_slices(detector):
"""
Helper function to read data_origin and data_size from the NXdetector_modules in a
NXdetector. Returns a list of lists, where each sublist is a list of slices in
slow to fast order.
Assumes slices are stored in NeXus in slow to fast order.
"""
#... | a23e797579c0925b48b802e0189ce17d3f5bf12c | 48,785 |
def main(**prepared_args):
"""
main conversion runner
:param prepared_args kwargs:
:return:
"""
conversion_result = None
if prepared_args['conversion_type'] == 'csv_to_parquet':
conversion_result = converter_csv_to_parquet(prepared_args['source_file_path'],
... | 6c79bbd453e1b229329b0bb91e8b0b81e0b7d4a2 | 48,786 |
def get_tm_session(session_factory: sessionmaker, transaction_manager: TransactionManager) -> Session:
"""
Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
This function will hook the session to the transaction manager which
will take care of committing any changes.
- When using ... | 80ae17addd6f519d55234c11707b3e0311329e22 | 48,788 |
import tarfile
import logging
def get_test_from_anaconda(url):
"""
Given the URL of an anaconda tarball, return tests
"""
try:
tarball = get_file_from_recipe_url(url)
except tarfile.ReadError:
return None
try:
metafile = tarball.extractfile('info/recipe/meta.yaml')
... | f9ad72251a450d7c24e7eedd84cd89bf670a6b6b | 48,789 |
import numpy
def calculate_reservoir_rate(var, surf_mask, surf_type=None):
"""Inputs are two maps (var and surf_mask). Whereas there may be scripts that
calculate the masked means, this calculates the volume flow rate (ie, not the
flux density, but the total flux. This is currently written to only ... | 41c89b6fbdfd7a3234ec7f555e3c7c48d8181641 | 48,790 |
def get_schedules(filter_params, dbinfo=None, fields=None):
"""
Helper function to get schedule data for a request.
:param filter_params: dict mapping constraint keys with values. Valid constraints are
defined in the global ``constraints`` dict.
:param dbinfo: optional. If provided, defines (connec... | 4043cfd9d05321af043ed32ec99524ca92318430 | 48,791 |
async def get_forge_godly_description(message_content: str, message: discord.Message) -> str:
"""Returns the embed description for the forge_godly event"""
user_name_string = 'exhausted'
user_name_start = message_content.find(user_name_string) + len(user_name_string) + 1
user_name_end = message_content.... | 2b12ff6c5b9ecbcce83b19cf3bde017cde0b9fee | 48,792 |
from userbot.modules.sql_helper.spam_mute_sql import unmute
async def unmoot(unmot):
""" For .unmute command, unmute the replied/tagged person """
# Admin or creator check
chat = await unmot.get_chat()
admin = chat.admin_rights
creator = chat.creator
# If not admin and not creator, return
... | 523b60270ccb26ed1c148e068c2ec8f84968addd | 48,793 |
def objective_value(x, w):
"""Compute the value of a cut.
Args:
x (numpy.ndarray): binary string as numpy array.
w (numpy.ndarray): adjacency matrix.
Returns:
float: value of the cut
"""
X = np.outer(x, (1-x))
w_01 = np.where(w != 0, 1, 0)
return np.sum(w_01 * X) | ed6963759cd8f9a77bc5fdfd42018fc32b8c0994 | 48,794 |
def setEncoding(encoding = None):
""" 라이브러리용 엔코딩 설정 함수
기본 엔코딩 정보를 설정한다
인자값 목록 (모든 변수가 반드시 필요):
encoding : 문자열 엔코딩 정보
결과값 : 현재 설정된 기본 엔코딩 정보
"""
global _default_encoding
try:
str("dummy", encoding)
except:
return _default_encoding
_default_encoding = encoding or _default_encoding
return _defau... | a1b0cbe83d5d08ad16274dafa4f0c4965aa938a1 | 48,795 |
def _create_v2_request_with_keyranges(
sql, new_binds, keyspace_name, tablet_type, keyranges, not_in_transaction):
"""Make a request dict from arguments.
Args:
sql: Str sql with format tokens.
new_binds: Dict of bind variables.
keyspace_name: Str keyspace name.
tablet_type: Str tablet_type.
... | af3f539fee6646a3d97bd531f57f9203eb6dee91 | 48,796 |
def generate_meme(image_path, meme_text):
"""
Generate meme with image and text
"""
pic = Image.open(image_path).convert("RGBA")
pic = pic.resize((600, 300), Image.LANCZOS)
background = Image.new("RGBA", (900, 700), "white")
Image.Image.paste(background, pic, (150, 200))
draw = ImageDr... | 873468f16813a9e35af87523cf6f9578dd57c434 | 48,797 |
def shuffle(images, labels):
"""
Return shuffled data.
"""
permutation = np.random.permutation(images.shape[0])
return images[permutation], labels[permutation] | 56b5fabd93b21f875976b236843e40a4a3136577 | 48,798 |
import math
def Linear(input_size, hidden_size, with_bias=True):
"""tbd"""
fan_in = input_size
bias_bound = 1.0 / math.sqrt(fan_in)
fc_bias_attr = paddle.ParamAttr(initializer=nn.initializer.Uniform(
low=-bias_bound, high=bias_bound))
negative_slope = math.sqrt(5)
gain = math.sqrt(2.0 / (1 +... | e5f387dcdabc174717f6e431ce7d4afb4a7e305d | 48,799 |
def uuid_mole_index(moles, mole_uuid):
"""Return the index of the first mole with the specified uuid."""
for i, mole in enumerate(moles):
if mole["uuid"] == mole_uuid:
return i
return None | 851877da59f6a6dd8c06b9bb2d462f6239d512e7 | 48,800 |
from typing import Optional
import random
import scipy
def edge_plate2(
plate: int = 384,
sigma: Optional[float] = None,
spread: Optional[float] = None,
invert: Optional[float] = None,
randomise_edges: bool = False,
) -> Plate:
"""
Create a plate with an edge effect.
Use a diffusion mo... | 8b2b487961943b264f388a3a02abfafba1cf9e0e | 48,801 |
from datetime import datetime
import logging
def check_if_sent(cursor, database, sensor, relaxation):
"""
Verify if the notification for given sensor was sent or not within the period specified by relaxation.
:param cursor: cursor to database connection
:param database: database connection
:param ... | abad352d3766bf5ce4993751d82670fef770c7be | 48,802 |
import requests
def cobjects(url='/display/DOCS/REST+Complex+Objects'):
"""Scrape Cobjects spec."""
print('==> Cobjects', end='')
degenerated = {}
u_types = set()
d_types = {}
for name, href in indexer(url):
print('.', end='')
page = bs(requests.get(BASE + href).text).select... | a6eb6f1181cfbe0c512d02c3a6d9f5fc68a754e8 | 48,804 |
def pearson_between_feature(X,threshold):
"""
Computes the Pearson Correlation between each feature and drops the higlhy correlated features
Keyword arguments:
X -- The feature vectors
y -- The target vector
threshold -- Threshold value used to decide which features to keep (above the threshold)
"""
if verbos... | fa2917780cdd6e79e02dea14b60074e8afda7a2f | 48,805 |
import torch
def bin_concrete_sample(a, temperature, hard = False, eps = 1e-8):
""""
Sample from the binary concrete distribution
"""
device = torch.device("cuda" if a.is_cuda else "cpu")
U = torch.rand(a.shape)
L = Variable(torch.log(U + eps) - torch.log(1. - U + eps)).to(device)
X = torch.sigmoid((L + a) / ... | c4aa4f0c3b200e90302ded19af4d717d6dd45f62 | 48,806 |
from typing import Dict
from typing import List
def check_procs(procs: Dict[int, Popen]) -> List[bool]:
"""Checks on the status of running jobs.
Args:
procs (Dict[int, Popen]): A dictionary where the keys are the worker
ids and the values are the process objects
... | bc1166764417cfcfaacd75ba66d194429e562800 | 48,808 |
from typing import List
def compute_permutation_distance(
distance_matrix: np.ndarray, permutation: List[int]
) -> float:
"""Compute the total route distance of a given permutation
Parameters
----------
distance_matrix
Distance matrix of shape (n x n) with the (i, j) entry indicating the
... | 953bed917e5284e43eb99016e54875a53ab384a4 | 48,809 |
def encrypt(text):
"""encrypt
"""
if text is None or not isinstance(text, str):
return None
return AESCipher.cipher.encrypt(text) | 552ce18cdafd5c0b73dc65e12f64aea504a85daf | 48,812 |
def fft_convolve(signal, kernel, conv_mode = CONV_MODE.DEFAULT):
"""
Non batched FFT Convolution.
This function performs n-dimensional convolution based on input dimensionality.
Parameters
-----------
signal: af.Array
- An n-dimensional array.
kernel: af.Array
- A... | 19994a93c0d6d5684a180b5c82933d42c5b2f8e8 | 48,813 |
def pick_frames(poses, is_train=True):
"""Pick valid frames, each ~GAP apart. Since some frames may have
invalid poses, we first extract the longest segment we can without a
gap larger than GAP (for 'train')
We then sample from this longest segment. For 'train', some sampled
frames might be invalid,... | 368ec0b2545796511b0d243a371e01402f7bd608 | 48,814 |
async def info(msg, mobj):
"""
Return current channel/guild information
"""
chan = mobj.channel
serv = mobj.guild
chan_name, serv_name = None, None
chan_id, serv_id = 0, 0
if hasattr(chan, 'name'): chan_name = chan.name
if hasattr(serv, 'name'): serv_name = serv.name
if hasattr(c... | e2ca3a3dad6b5b13305aa15d08809f8a73e61b42 | 48,815 |
import time
def run_graph(device, input_shape, axes, num_layers, py, scale, train,
num_iters):
"""Run the graph and print its execution time.
Args:
device: string, the device to run on.
input_shape: shape of the input tensor.
axes: axes that are to be normalized across.
num_layers: ... | c2b37e564fbb18fb12c89951fdedd7a1a4ed30ac | 48,816 |
import torch
def make_masked_coordinate_tensor(mask, dims=(28, 28, 28)):
"""Make a coordinate tensor."""
coordinate_tensor = [torch.linspace(-1, 1, dims[i]) for i in range(3)]
coordinate_tensor = torch.meshgrid(*coordinate_tensor)
coordinate_tensor = torch.stack(coordinate_tensor, dim=3)
coordina... | 521454567e38f63c315ad1db198bb632d8a56658 | 48,817 |
def atleast_2d_col(A):
"""
Return the input `A` as a 2d column array.
"""
return atleast_2d(A,'col') | 098c47d921d0390b68fdddee491139af68a98b56 | 48,818 |
def f_read_raw_mat_length(filename, data_format='f4'):
"""f_read_raw_mat_length(filename,data_format='float',end='l')
Read length of data
"""
f = open(filename,'rb')
tmp = f.seek(0, 2)
bytes_num = f.tell()
f.close()
if data_format == 'f4':
return int(bytes_num / 4)
else:
... | 07ad3d0c425fd01f3985c4f3daf5a762bf59f76c | 48,819 |
def automl_params_overwrite(params):
"""Overwrite some training options based on the selected automl mode"""
params_copy = params.copy()
if params_copy["forecasting_style"].startswith("auto"):
params_copy["season_length"] = get_seasonality(params_copy["frequency"], DEFAULT_SEASONALITIES)
par... | 47107601b935b645b75fe04afbfea04594a6b581 | 48,820 |
def parse_StatsReq(msg, packet):
"""
Parse StatReq messages
Args:
msg:
packet:
"""
# Get type = 16bits
# Get flags = 16bits
of_stat_req = packet[0:4]
ofstat = unpack('!HH', of_stat_req)
msg.stat_type = ofstat[0]
msg.flags = ofstat[1]
start = ... | 11b5ebd453a7b3554b003b2acfba4880834f810c | 48,821 |
def apply_feature(
context,
entity,
feature,
values,
country=None,
start_date=None,
end_date=None,
comment=None,
authority=None,
date_formats=[],
):
"""This is pretty specific to the needs of OFAC/CSL data."""
feature = feature.replace("Digital Currency Address - ", "")
... | 5e5a7c90f376253dd80818dd59ae27ecc146a5ef | 48,822 |
def plot_rolling_returns_multiple(returns_arr, factor_returns=None, logy=False, ax=None, names_arr=None, extra_bm=0):
"""
Plots cumulative rolling returns versus some benchmarks'.
This is based on https://github.com/quantopian/pyfolio/blob/master/pyfolio/plotting.py,
but modified to plot multiple rolli... | 9e47f9e6cd92c087d0f6a1bbf04005d93a0528af | 48,824 |
def _analyze_gens(gens):
"""Support for passing generators as `*gens` and `[gens]`. """
if len(gens) == 1 and hasattr(gens[0], '__iter__'):
return tuple(gens[0])
else:
return tuple(gens) | f32eb1faf7f1aae2f8d4eff72609732db8655899 | 48,825 |
def canonical_representation(a, d, DE):
"""
Canonical Representation.
Given a derivation D on k[t] and f = a/d in k(t), return (f_p, f_s,
f_n) in k[t] x k(t) x k(t) such that f = f_p + f_s + f_n is the
canonical representation of f (f_p is a polynomial, f_s is reduced
(has a special denominator... | 75397c72e8f78a4ad2fd81fec01d26652c406b9f | 48,826 |
def get_driver(worker_url=None):
"""
:rtype: dao.control.worker.provisioning.foreman.ForemanDriver
"""
module, obj = CONF.worker.provision_driver.rsplit('.', 1)
LOG.info('Load %s from %s', obj, module)
module = eventlet.import_patched(module)
return getattr(module, obj)(worker_url) | 398fb74fa7cf0bd72d629411409afa77268d503f | 48,828 |
def preparation_time_in_minutes(number_of_layers: int) -> int:
"""
Args:
number_of_layers (int): the number of layers you want to add to the lasagna.
Returns:
int: how many times you would spend making them.
"""
return 2 * number_of_layers | 90b6e6f518acbba514af5d3ab77dff2e5735535a | 48,829 |
def quicksort(x):
"""
Describe how you are sorting `x`
Goal:
First: Select a pivot point. In this case the first bin in the list.
Second: Put all of other items in the list ordered arround the pivot variable
Third: Recursively do the same to each side of the list
Fourth: If the list be... | a2c8d23331a694c31f5ab7974feecc3243145da8 | 48,830 |
from typing import Union
def gb_to_mib(gb: Union[int, float]) -> float:
"""
Gigabyte (Gb) to Mebibyte (MiB)
:param gb: Gigabytes (Gb)
:return: Mebibytes (MiB)
"""
return gb * 953.674 | 4a30792df2dbb0220223460f4f5cbe999a102b77 | 48,832 |
from typing import Iterator
from typing import Tuple
def walk_sources_from_command(command: instances.FilesRelatedCommand,
filesystem: Filesystem
) -> Iterator[Tuple[str, str, str]]:
"""Typical iteration by command settings."""
return walk(command.so... | 832909f1cafdf65cbaff999a2f9cca13969e17f5 | 48,834 |
def can_access_uri_part(context, request, uri_part):
"""Tell if current user can to access a URI part relative to context."""
assert uri_part is not None
traverser = zope.traversing.publicationtraverse.PublicationTraverser()
try:
view = traverser.traverseRelativeURL(request, context, uri_part)
... | c1f94f63336d08b49ea99ffda414bf36bf9ab61b | 48,835 |
def get_trainables():
"""Get all the trainable variables in the current default session."""
sess = tf.get_default_session()
result = {}
for tvar in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES):
result[tvar.name] = sess.run(tvar).tolist()
return result | 6ddba43186b1f2b56da4db65910db17a6330f89b | 48,836 |
def _encode_entity_id(entity_type, entity_id):
"""See xidCgiDelimiter = "?xid=" """
return "xid=%s.%s" % (entity_type, entity_id) | fc6e36a4027f7a63e05e8dfab7f40681b3e26585 | 48,837 |
def _create_pdb_atoms_from_cif(cif_atoms, cif_fields, identifier):
"""
Transform mmCIF atoms into pdb atoms.
Parameters
----------
cif_atoms : list of str
lines with atoms details in CIF format
cif_fields : dict (str : int)
key: field name
value: index where to look for s... | 7b4b693b8580a12ef5996aaa986acf3c671215dc | 48,839 |
def get_session():
"""获取当前用户session"""
return request.environ.get('beaker.session') | 4bfcbd73251e7b928624ae7b3e00353be9650dad | 48,841 |
def find_average_record(sen_set, voting_dict):
"""
Input: a set of last names, a voting dictionary
Output: a vector containing the average components of the voting records
of the senators in the input set
Example:
>>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Rav... | ef0c0aeb5a75c0335de57ae6cca1c013fe59b8b0 | 48,842 |
def HTTP_POST_flask_config_general():
"""This endpoint expects json of generalConfig.
Optional argument 'restart' may be passed.
When argument 'restart=true',
the device starts automatically with new configuration."""
try:
config = request.get_json()
dabing.postConfig(config... | c401a64e69655db4a559c158e967faeff6615c3a | 48,843 |
import re
def get_allparams_cleaned_mdl(mydata):
"""输入是被定位出来的含有出事model内容的mdl列表,称为mydata。输出被正则替换掉全部参数的mdl列表"""
# 这一段注释是测试代码,用于验证正则表达式
# pattern = re.compile(r"\'([-]*[0-9.E]*\-*\d*)[+-]*.*?\'") # 这是当初为钟灿写的正则,我现在也看不太懂了。
# for line in mydata:
# if "'" in line:
# print(line)
# print(pattern.finda... | e3af1dc0959a602367a28b67fb29e1d848db1d0d | 48,844 |
def transformer_ae_small():
"""Set of hyperparameters."""
hparams = transformer.transformer_small()
hparams.batch_size = 2048
hparams.learning_rate = 0.2
hparams.learning_rate_warmup_steps = 4000
hparams.num_hidden_layers = 3
hparams.hidden_size = 384
hparams.filter_size = 2048
hparams.add_hparam("com... | 3c7cfd4b71c8e3e9169101ecc4bd4177ae4dfd60 | 48,845 |
import warnings
def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=0,
spacing=None, multichannel=True, convert2lab=None,
enforce_connectivity=False, min_size_factor=0.5, max_size_factor=3,
slic_zero=False):
"""Segments image using k-means clustering in Color-(x,y,z) spa... | 2002c09b4a4a97ab9c5c7ae1349a9eff7aa83561 | 48,846 |
def str_ljust(x, width, fillchar=' '):
"""Fills the right side of string samples with a specified character such that the strings are right-hand justified.
:param int width: The minimal width of the strings.
:param str fillchar: The character used for filling.
:returns: an expression containing the fil... | 947c6413fdd331f962d2525784ef4f3eb05e3b2e | 48,848 |
from datetime import datetime
def partition_folder_path(file_path):
"""
This function provides the output path to which the data frame will be created
:param file_path: file path from config_utils for the value 'output_file_path'
:return: output file path with date partition
"""
file_path = fi... | 3974344ba77caa2f04f025d1d79b852a6171ded3 | 48,849 |
def index(request):
"""Loads main page containing a MapBox map and the weight sliders."""
return render(request, "map/index.html") | df1c347e6743f8c139796cb5cca72855c0c95703 | 48,850 |
def parse_move(s: str) -> int:
"""
:param s:
:return:
"""
try:
v = int(s)
except ValueError:
v = -1
return v | 5e450c0726ae2420aca41967c2e750ba6238a140 | 48,851 |
def exception_to_string(exc: Exception) -> str:
"""Convert exception to string stackrace"""
# Either use passed original exception or whatever we have
return TRACEBACK_HEADER + "".join(format_tb(exc.__traceback__)) + str(exc) | b383f257bbb2071966be21b259943ba1edaf7a57 | 48,852 |
def indice_x_norm(x_selected:float, x_norm:pd.Series):
"""
This function finds the indices for different values of the independent
variable (x). The script considers the selected x_fixed point
(for example: 0.15, 0.30, 0.45, 0.60, 0.75, 0.90). The output of the
function are the observed limits fo... | 731a68cb702a8d813312b703e072a9634c0d9489 | 48,853 |
def get_all_drives(session, start=None, limit=None, return_type=None,
**kwargs):
"""
Retrieves details for all drives for the VPSAOS.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type start: int
:param start: Th... | 1d5fe34be20725daa9eb07eab2c35b51f2523088 | 48,854 |
def cache(self, key, fn):
"""
:param self: the object that will hold the cached value
:param key: the key/attribute for the cached value
:param fn: the function returning the value to be cached
:return: the value returned by fn on first call
"""
if not hasattr(self, key):
value = fn... | 4d7c67d2e3892e4b2db57625075c4515ff89da99 | 48,855 |
def cursorColorForColormap(colormapName):
"""Get a color suitable for overlay over a colormap.
:param str colormapName: The name of the colormap.
:return: Name of the color.
:rtype: str
"""
return _COLORMAP_CURSOR_COLORS.get(colormapName, 'black') | ec418f2f3b26b900ff6c8d2e5bb8f05b4701743d | 48,856 |
import time
def alarm_to_time(alarm: str):
""" This function converts the time when the alarm is setted into seconds """
time_alarm = time.strptime(alarm + ":00", "%Y-%m-%dT%H:%M:%S")
return time.mktime(time_alarm) | 863dffc8832c5518bd24e9ba4524818835e724e5 | 48,857 |
def _compute_ious(dt, gt):
""" compute pairwise ious """
ious = np.zeros((len(dt), len(gt)))
for g_idx, g in enumerate(gt):
for d_idx, d in enumerate(dt):
ious[d_idx, g_idx] = _jaccard(d, g)
return ious | 8c3ceb268fcecc5beec246f9120b8e46e52d90ed | 48,858 |
def get_top_articles():
"""Most popular three articles of all time"""
sql = """SELECT articles.title, COUNT(*) AS views
FROM articles, log
WHERE log.path = '/article/' || articles.slug
GROUP BY articles.title
ORDER BY views DESC
LIM... | c1027e4b92263f3ce943fa74f6842bd4a601d6ce | 48,859 |
import copy
def overlap2(data):
"""
"""
# Make a copy of the data.
data2 = copy.copy(data)
# Extract the first and last year and month.
firstYear = int(data2[0][0][0 : 4])
firstMonth = int(data2[0][0][5 : 7])
lastYear = int(data2[-1][0][0 : 4])
lastMonth = int(data2[-1][0][5 : 7]... | 5787b9b796cf6de16ac1d363536bcf92f47a5c6d | 48,861 |
def meridional_curve(n_0, pitch, length, r_i, theta_i, npoints=40):
"""
Points on path of a ray passing through a grin lens.
Args:
n_0: index of refraction at center of grin lens [unitless]
pitch: pitch or period of the lens [unitless]
length: axial length of the lens [mm]
r... | 59a0de1cca1a1194d8b1c06b987606605bdce016 | 48,862 |
def restore_model(session, saver, path):
""" Initializes a model that has been previously trained and
returns global step
Args:
session: Tensorflow session
saver: Tensorflow saver
path: Path where model to be loaded is
Returns:
Global step variable
"""
logger.info... | 2322dd46641cefae51eec493f522854242195d50 | 48,863 |
import json
from datetime import datetime
def get_fake_users():
"""Restituisce una lista di utenti fake"""
with open('db/fake-data/users.json') as f:
data = json.load(f)
users = []
for row in data['results']:
user = {
'username': row['login']['username'],
... | d3aabc54a3c3fd643143ac1dec4c25619d2e5575 | 48,865 |
def spherical_to_cartesian(theta, phi, rho):
""" Converts spherical coordinates into cartesian. """
x = rho * np.sin(phi) * np.cos(theta)
y = rho * np.sin(phi) * np.sin(theta)
z = rho * np.cos(phi)
return x, y, z | 6348107f9616888aa5101a94e21f69f4a56f090f | 48,866 |
def insert(df: pd.DataFrame, col_name, col_value, allow_duplicates=False):
"""Adds a column to the end of the DataFrame
:param df: DataFrame
:param col_name: name of column to insert
:param col_value: value of column to insert
"""
return df.insert(len(df.columns), col_name, col_value, allow_dup... | bb7fb40cb4eb0ae8ecc78dffef587a1492d5869b | 48,867 |
def doChangePageSize(request, pageSize):
""" Changes page size in user preferences"""
try:
u = User.objects.get(user=request.user.id)
u.pagesize = pageSize
u.save()
return HttpResponse(_('saved pagesize %s') % pageSize)
except Exception, inst:
return HttpResp... | af97024e4b6160b6da9fefb65874c323e455eb12 | 48,868 |
def _solve_lagrange123_com_slow(i, q, xtol=1e-6):
"""
Solve for L1, L2, or L3 x position in the CoM frame in units of semi-major
axis *a*.
Parameters
----------
i : {1,2,3}
L point to solve for
q : float
Mass ratio m2/m1
xtol : float
Tolarance value for solver.
... | 1fd8f08aa48ecc2f1d6b8937b63bcb44c187e7df | 48,869 |
def is_abs_bpath(d):
"""Returns true if it's an absolute blaze path"""
return is_valid_bpath(d) and d.startswith('/') | d19714764754230afa7e4485268c6962483a9e2d | 48,870 |
import functools
def get_network_fn(name, num_classes, weight_decay=0.0, is_training=False):
"""Returns a network_fn such as `logits, end_points = network_fn(images)`.
Args:
name: The name of the network.
num_classes: The number of classes to use for classification.
weight_decay: The l2 coefficient f... | 8870afd081de02a087663021228956424684605d | 48,871 |
def job_product(job_name, pre_request=None):
"""Decorator to register a function as a job product handler.
Example::
@job_product('build-playlist-report')
def playlist_report_product(results):
csv_file = "\n".join(results['file_lines'])
response = HttpResponse(conte... | 666316fd58153ec06d957d21b1af62e05f7fb007 | 48,872 |
def blockplural(parser, token):
"""
Same as plural filter
Example:
{% blockplural amount %}{% trans "Book" %}{% endblockplural %}
"""
nodelist = parser.parse(('endblockplural',))
parser.delete_first_token()
tag_name, amount = token.split_contents()
return PluralNode(nodelist, am... | 09fbb2bca90157c229d29fc30ef04bbec62a1b5a | 48,873 |
import re
def preprocess_text(input: TextPreprocessingInput) -> TextProcessingOutput:
"""Clean up text data based on selected preprocessing steps."""
text = input.text
if PreprocessingStep.REMOVE_SPECIAL_CHARACTERS in input.preprocessing_steps:
text = re.sub(r"\W", " ", text)
if Preprocessi... | edf43ff51e01944dddb6bce4d9b66cdba8761bf1 | 48,874 |
def sdss_fits_url(plate, mjd, fiber):
"""Return the URL of the spectrum FITS file"""
return SDSS_URL % dict(plate=plate, mjd=mjd, fiber=fiber) | 1b212b52ab2403500a66470e5c0444749d4d8db3 | 48,875 |
import attr
def verbose(message):
"""Color format a message for verbose messages"""
if __use_colors():
return "%s%s%s" % (COLOR_VERB, message, attr(0))
else:
return message | 7fb97f110929a4003c5bb05a0d7787c4c92be09c | 48,876 |
import numpy
def dropout_constr(options, use_noise, trng, sampling):
"""This constructor takes care of the fact that we want different
behaviour in training and sampling, and keeps backward compatibility:
on older versions, activations need to be rescaled at test time;
on newer veresions, they are res... | 1a19d64f8fd106127c26be3ddc006280b70cc0a6 | 48,877 |
def to_inter_sets(lines):
"""Groups linked entities and interpretation set."""
group_by_qid = defaultdict(set)
for cols in lines:
group_by_qid[cols[0]].add(cols[2])
return group_by_qid | f8a513a53e674d38809980eafb8e14384bd12012 | 48,878 |
def gini_index(targets) -> float:
"""
Computes the gini index for a given target labels.
Arguments:
targets: A numpy array of shape (n_samples, )
Returns:
The gini index for the given target labels.
"""
label_count = np.bincount(targets)
return 1 - np.sum((label_count / len(t... | 5dbc2698c198fed96b970e54f570b5e299b0649b | 48,879 |
from hyperopt import hp, fmin, rand, Trials
import hyperopt.pyll.stochastic
def hyperopt_fit (model, X, Y, T, p0, **estimation_settings):
"""Calls Hyperopt.
Exists to make passing arguments to the objective function easier.
Arguments:
model, X, Y, T, p0, estimation_settings: Just like other
... | b4c17bed702e10637bb85bae8dbfbd7b1385dad7 | 48,881 |
from datetime import datetime
def get_type(data_field, derives=None):
"""
Parse type defined in <DataField> object and returns it.
Parameters
----------
data_field : eTree.Element
<DataField> or <DerivedField> XML element that describes a column.
derives : eTree.Element
<DataField> XML eleme... | a1699f0c300862acc01db525db967c15dba16e52 | 48,882 |
import mpmath
def matrix_product(m1, m2):
"""
Args:
m1 (mpmath.matrix or numpy.ndarray): first matrix
m2 (mpmath.matrix or numpy.ndarray): second matrix
Returns:
matrix product m1 * m2 with same data type as m1 and m2
"""
if isinstance(m1, mpmath.matrix) and isinstan... | 19716cd2829fb37904c60a2d47c7fb45c350eb8c | 48,883 |
import random
def random_points_and_masses(max_points=10, min_mass=0.5, max_mass=2.0,
max_coord=rbf_high, min_separation=0.5):
"""
returns:
-shape [N, 3] numpy array of points, where N is between 2 and max_points
-shape [N] numpy array of masses
"""
num_points = ra... | de4105f7f75001bf19669560f05aeb71a4116def | 48,885 |
import PIL
def imresize(image, factor, interp="nearest", mode=None):
"""
resize an image with a specified resizing factor, this factor can also be
the target shape of the resized image specified as tuple.
"""
interp_methods = {
"nearest": PIL.Image.NEAREST,
"bicubic": PIL.Image.BIC... | 866628560f5096c649a01de7a0d4f6116c992af6 | 48,886 |
def enum_class_getitem(context, builder, sig, args):
"""
Return an enum member by index name.
"""
enum_cls_typ, idx = sig.args
member = enum_cls_typ.instance_class[idx.literal_value]
return context.get_constant_generic(builder, enum_cls_typ.dtype,
member.v... | 554aee101408e072050134e2f6990f79780d516e | 48,887 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.