content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import ssl
import socket
import time
async def tls(q, where, timeout=None, port=853, source=None, source_port=0,
one_rr_per_rrset=False, ignore_trailing=False, sock=None,
backend=None, ssl_context=None, server_hostname=None):
"""Return the response obtained after sending a query via TL... | 9a2904719b338387721350d4ff0fe95cf0332cf4 | 3,628,800 |
def create_resource():
"""Users resource factory method"""
return wsgi.Resource(Controller()) | db9b827051463b0e629dab13602ccd731e8f718f | 3,628,801 |
import re
def validip(ip, defaultaddr="0.0.0.0", defaultport=8080):
"""
Returns `(ip_address, port)` from string `ip_addr_port`
>>> validip('1.2.3.4')
('1.2.3.4', 8080)
>>> validip('80')
('0.0.0.0', 80)
>>> validip('192.168.0.1:85')
('192.168.0.1', 85)
... | 5a353c8e8a008935f94905445ff12ba517b350d0 | 3,628,802 |
def get_rcs2body(el_deg=37.0, az_deg=0.0, side='left') -> isce3.core.Quaternion:
"""
Get quaternion for conversion from antenna to spacecraft ijk, a forward-
right-down body-fixed system. For details see section 8.1.2 of REE User's
Guide (JPL D-95653).
Parameters
----------
el_deg : float
... | 7f9d4470b3640daf6742e438225fc5f7faa59790 | 3,628,803 |
import urllib
def obtain_parse_wiki_stocks_sp500(url):
"""Download and parse the Wikipedia list of S&P500
constituents using requests and libxml.
Returns a list of tuples for to add to MySQL."""
# Get S&P500 website content
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
data... | 13f088ee4e84c9bb377daa0bfb989c06d82359c7 | 3,628,804 |
import calendar
def parseISO(s):
"""Parse ISO8601 (string) date into a floating point seconds since epoch UTC.
The string must be an ISO8601 date of the form
YYYY-MM-DDTHH:MM:SS[.fff...](Z|[+-]dd:dd)
If something doesn't parse, a DateFormatError will be raised.
The return value is floatin... | 05886cdbb90020a7331f70a708a970aff1bd1b61 | 3,628,805 |
import requests
import time
def _get_data(url, attempts=5):
""" Downloads data from a given url.
Parameters
----------
url : str
url to fetch data from
attempts : int
number of times to try to download the data in case of failure
R... | b58bf34b5abeada9fa1fa2fec37511d8500a6e12 | 3,628,806 |
def ldns_str2period(*args):
"""LDNS buffer."""
return _ldns.ldns_str2period(*args) | a8840efd7ec114c343bc389a776931db23095082 | 3,628,807 |
def create_doctor_image_upload_url():
"""Creates url for uploading image for doctor"""
return reverse('doctor:doctor-image-upload') | f403f80ed996d19c816fc074277976260b2f31e4 | 3,628,808 |
from pathlib import Path
def reformat_peer_data_csv(csv_file_path, time_step=0.005):
"""Reformat PEER motion records to column-wise, and save to csv.
Typically, PEER data is given in a plane text file, with data
disposed in horizontal consecutive arrays. This function serializes
it in a single column... | c9d4301f8b418e40195049bae742195339e8fd2d | 3,628,809 |
import six
def compute_eval_metrics(labels, predictions, retriever_correct,
reader_correct):
"""Compute eval metrics."""
# []
exact_match = tf.gather(
tf.gather(reader_correct, predictions["block_index"]),
predictions["candidate"])
def _official_exact_match(predicted_answ... | 66cffa3d3f7b44f9d6b92e386eea1528d0f970d0 | 3,628,810 |
def tf_lovasz_grad(gt_sorted):
"""
Code from Maxim Berman's GitHub repo for Lovasz.
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
gts = tf.reduce_sum(gt_sorted)
intersection = gts - tf.cumsum(gt_sorted)
union = gts + tf.cumsum(1. - gt_sorted)
... | 756ddd32382c5361ecb3c0e8fd89de4882650d62 | 3,628,811 |
def phone_setup_4g_for_subscription(log, ad, sub_id):
"""Setup Phone <sub_id> Data to 4G.
Args:
log: log object
ad: android device object
sub_id: subscription id
Returns:
True if success, False if fail.
"""
return phone_setup_data_for_subscription(log, ad, sub_id, G... | 07d91e295c7b007c0af6141a1fab94d473924243 | 3,628,812 |
import inspect
import gc
def empty(shape, dtype=np.float, order='c', description=None, verbose=None):
"""
Return a new aligned and contiguous array of given shape and type, without
initializing entries.
"""
shape = tointtuple(shape)
dtype = np.dtype(dtype)
if verbose is None:
verb... | 4e5c980d83394ebf72cd3559dbfcb716a1e22c55 | 3,628,813 |
def IDcorner(landmarks):
"""landmarks:检测的人脸5个特征点
"""
corner20 = twopointcor(landmarks[2, :], landmarks[0, :])
corner = np.mean([corner20])
return corner | 06eae06d6efe563e177dbbeb791cea561596f418 | 3,628,814 |
import torch
import os
import time
def train_controller(controller, config):
"""
Adversarial AutoAugment training scheme without image
1. Training TargetNetwork 1 epoch
2. Training Controller 1 step (Diversity)
"""
controller = controller.cuda()
# ori_aug = C.get()["aug"]
dataset = C.... | 88d5653e4a2af8746b9629c61f15deaa5662bc67 | 3,628,815 |
def QColorAlpha(*args):
"""Build a QColor with alpha in one call
This function allows to create a `QColor` and set its alpha channel value in a single call.
If one argument is provided and it is a string parsable as hex, it is parsed as `#RRGGBBAA`.
Else, the single argument is passed to QColor and thus alpha is ... | 62c73b3a01b8330b836289aba3d31db97c6a9735 | 3,628,816 |
def video_signatures_exist(files, pipeline: PipelineContext):
"""Check if all required signatures do exist."""
return not any(missing_video_signatures(files, pipeline)) | 22467a8e2d58990cb9d210293e49e3238c1925b8 | 3,628,817 |
def _run_gn_desc_list_dependencies(build_output_dir: str, target: str,
gn_path: str) -> str:
"""Runs gn desc to list all jars that a target depends on.
This includes direct and indirect dependencies."""
return subprocess_utils.run_command(
[gn_path, 'desc', '--all... | 0785bdff84b79649451d3413bce858d20d2bc52e | 3,628,818 |
def trainTfidfModel(tsvFile, wordIndex, ngram, dictionary):
""" Train tf-idf model"""
reader = DescriptionReader(tsvFile, wordIndex, ngram)
# construct the dictionary one query at a time
tfidf_model = models.tfidfmodel.TfidfModel( dictionary.doc2bow(d) for d in reader )
return tfidf_model | 6020f8ec3e3ebe5ad280dd6dc40ed38860e77f5c | 3,628,819 |
def IsUnion(sid):
"""
Is a structure a union?
@param sid: structure type ID
@return: 1: yes, this is a union id
0: no
@note: Unions are a special kind of structures
"""
s = idaapi.get_struc(sid)
if not s:
return 0
return s.is_union() | e94e3b3fedf234a5781ddbf577290a9f07fcc25f | 3,628,820 |
def import_atm_mass_info():
"""
Funtion to load dictionary storing atomic mass information by atom type.
dict
dictionary of atomic mass by atom name
"""
massdict = {'H': 1.00797,
'HE': 4.0026,
'LI': 6.941,
'BE': 9.01218,
... | c470495f30d77b41642bfd07f52a82b7a060ffb5 | 3,628,821 |
def defaults(group1):
""" Get globals for all model tests. """
values = Defaults()
values.account_attributes = {
'uid': "tux",
'uidNumber': 10,
'givenName': "Tux",
'sn': "Torvalds",
'cn': "Tux Torvalds",
'telephoneNumber': "000",
'mail': "tuz@example.... | ff82cb0f0f5177ffbc9d4c118b998e1e837ccac9 | 3,628,822 |
def get_move(state: State) -> State:
"""Get next move, check if it's legitimate.
If it's not, record the error or the quit choice.
Otherwise, update the board and determine if
there's a winner or a draw."""
new_move = input(f'Player {state.player}, what is your move? [q to quit]: ')
i... | 2c76f2b06f246fa121138241b6b5da9c5e7e9981 | 3,628,823 |
def _project_im_rois(im_rois, scales):
"""Project image RoIs into the image pyramid built by _get_image_blob.
Arguments:
im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
scales (list): scale factors as returned by _get_image_blob
Returns:
rois (ndarray): R x 4 ma... | 05c542fdfecd24d9578f26db6e0071e99cc9c2d1 | 3,628,824 |
def preprocess_recipe(
adata,
min_expr_level=None,
min_cells=None,
use_hvg=False,
scale=False,
n_top_genes=1500,
pseudo_count=1.0,
):
"""A simple preprocessing recipe for scRNA data
Args:
adata (sc.AnnData): Input annotated data object
min_expr_level (int, optional): ... | 0b4c68ec3db9857dce824080d3bc26bd01d93ed4 | 3,628,825 |
async def pympler_tracker_diff(request: web.Request) -> web.StreamResponse:
""" Get Pympler tracker diff: https://pympler.readthedocs.io/en/latest/
Example:
curl -v -X POST 'localhost:9999/pympler/tracker/diff'
curl -v -X POST 'localhost:9999/pympler/tracker/diff?print'
"""
global _tracker
... | 644e6dfd5bca455ab4058cab4982c1c4880a1b6e | 3,628,826 |
import time
def toggle_40g_local(module):
"""
Method to toggle 40g ports to 10g ports.
:param module: The Ansible module to fetch input parameters.
:return: The output messages for assignment.
"""
output = ''
cli = pn_cli(module)
clicopy = cli
cli += ' lldp-show format local-port n... | 836bce0a54e9cdcb571490d9de42b6cf292710f5 | 3,628,827 |
import re
import sys
def parse_aa_change(aa_change):
"""Parse an amino acid change to get aa before, position, and aa after
Amino acid changes are a concatenation of amino acid "before"
(or "from", matching reference), followed by codon position, finishing
with the amino acid "after" (or "to", desc... | 4de9913987a3cf3b5972ddbffa2a1c88d28b1489 | 3,628,828 |
def lazy_index(index):
"""Produces a lazy index
Returns a slice that can be used for indexing an array, if no slice can be
made index is returned as is.
"""
index = asarray(index)
assert index.ndim == 1
if index.dtype.kind == 'b':
index = index.nonzero()[0]
if len(index) == 1:
... | 907320c50921a66908154ed3475243d784effa9c | 3,628,829 |
import copy
def extreme_contrast(image: Image) -> Image:
"""
T081 Matthew Gray
Returns a copy of the image that has extreme contast, the RGB values for
each pixel are either 255 or 0.
>>> file = load_image(choose_file())
>>> red_image = red_filter(file)
>>> show(red_image)
... | d3ffd9c86dabb4994dd112627d3e6c2ef865e52b | 3,628,830 |
def remove_batch_from_layout(layout):
"""
The tf-mesh layout splits across batch size, remove it.
Useful for prediction steps, when you no longer want large batches.
:param layout: string describing tf-mesh layout
:return: layout minus batch dimension
"""
layout = layout.split(',')
ret_... | 44d032504055e1133a6dc97ea040ff44ea2ac327 | 3,628,831 |
import torch
def weighted_index(self, dim=None):
"""
Returns a tensor with entries that are one-hot along dimension `dim`.
These one-hot entries are set at random with weights given by the input
`self`.
Examples::
>>> encrypted_tensor = MPCTensor(torch.tensor([1., 6.]))
>>> index... | e2c702540228cedb25c1d53b98c398cf5c074b2c | 3,628,832 |
def _knapsack01_recur(val, wt, wt_cap, n):
"""0-1 Knapsack Problem by naive recursion.
Time complexity: O(2^n), where n is the number of items.
Space complexity: O(n).
"""
if n < 0 or wt_cap == 0:
return 0
if wt[n] > wt_cap:
# Cannot be put.
max_val = _knapsack01_re... | 88f73b2e2f577b5e17a4ba235699ad542dfc7f0d | 3,628,833 |
def pixel_to_map(geotransform, coordinates):
"""Apply a geographical transformation to return map coordinates from
pixel coordinates.
Parameters
----------
geotransform : :class:`numpy:numpy.ndarray`
geographical transformation vector:
- geotransform[0] = East/West location of ... | 8c8a8b8c84d9b47b6795782d36d8aefb53cc6cef | 3,628,834 |
def newest_bugs(amount):
"""Returns the newest bugs.
This method can be used to query the BTS for the n newest bugs.
Parameters
----------
amount : int
the number of desired bugs. E.g. if `amount` is 10 the method
will return the 10 latest bugs.
Returns
-------
bugs : ... | 8b5f8326993f806ad13a053b44e9d70cf927cd1d | 3,628,835 |
def matchElements(e1, e2, match):
"""
Test whether two elements have the same attributes. Used to check equality of elements
beyond the primary key (the first match option)
"""
isMatch = True
for matchCondition in match:
if(e1.attrib[matchCondition] != e2.attrib[matchCondition]):
... | 1aa57a3a9a3123445e0234efa506f95616f90ef8 | 3,628,836 |
def emoticons_tag(parser, token):
"""
Tag for rendering emoticons.
"""
exclude = ''
args = token.split_contents()
if len(args) == 2:
exclude = args[1]
elif len(args) > 2:
raise template.TemplateSyntaxError(
'emoticons tag has only one optional argument')
node... | 8ecec1b8c85207d47cda3dadac245d5ef81aaa78 | 3,628,837 |
def auc_step(X, Y):
"""Compute area under curve using step function (in 'post' mode)."""
if len(X) != len(Y):
raise ValueError(
"The length of X and Y should be equal but got " + "{} and {} !".format(len(X), len(Y))
)
area = 0
for i in range(len(X) - 1):
delta_X = X[i... | 886f410a35a49a7098c1f2dcd145b54d1b54d423 | 3,628,838 |
def apply_impulse_noise(x, severity=1, seed=None):
"""Apply ``impulse_noise`` from ``imagecorruptions``.
Supported dtypes
----------------
See :func:`~imgaug.augmenters.imgcorruptlike._call_imgcorrupt_func`.
Parameters
----------
x : ndarray
Image array.
Expected to have s... | 749cb96ad3166ec65f60918d6980cf2a2888f23e | 3,628,839 |
def get_username(org_id_prefix, first_name, last_name):
""" generiert aus Vor- und Nachnamen eine eindeutige Mitglied-ID """
first_name = check_name(first_name.strip().lower(), True)
last_name = check_name(last_name.strip().lower(), True)
n_len = len(first_name)
for n in xrange(n_len):
test_name = u'%s%s... | 800e209662c74c6c52068f6e4e25c647a1f42dac | 3,628,840 |
def drawn_anomaly_boundaries(erp_data, appRes, index):
"""
Function to drawn anomaly boundary
and return the anomaly with its boundaries
:param erp_data: erp profile
:type erp_data: array_like or list
:param appRes: resistivity value of minimum pk anomaly
:type appRes: float
... | 24976754e29726c8f46c9c23a27a43ed85c493ac | 3,628,841 |
def index(request):
"""
This index view/function will display the data that are stored in the database when a request is sent to it. The da
ta will be in the context argument and accessed in the template.
"""
context_data = Task.objects.all()
context = {
'data': context_data
}
re... | 965022e62342585ac5bb755db7b68be2b8fb6f79 | 3,628,842 |
def _send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
... | b108b8b26db18bdcd19c7f2694e4931ad5d19dff | 3,628,843 |
def get_all_marbles_combinations_correctly_aligned(board):
"""
The board is a 6*6 board.
To check if we have 5 marbles aligned, we only need to start checking from positions described below:
┌─────────+─────────┐
| x x x | x x x |
| x x x | x x x |
| x x ◯ ... | 5f39708d07e06a8f8720a980a4213c7e5f705272 | 3,628,844 |
def calculate_num_modules(slot_map):
"""
Reads the slot map and counts the number of modules we have in total
:param slot_map: The Slot map containing the number of modules.
:return: The number of modules counted in the config.
"""
return sum([len(v) for v in slot_map.values()]) | efbb82a54843f093a5527ebb6a1d4c4b75668ebb | 3,628,845 |
def get_team_training_data(training_issues, reporters_config):
"""
Extracts development team information from the training dataset.
:param training_issues: Dataframe with the issues for training
:return: A develoment team size generator, and another one for the bandwith.
"""
training_in_batche... | f68597f5efa69ff0d5c445402c976137663781fb | 3,628,846 |
def dice_coefficient(logits, labels, scope_name, padding_val=255):
"""
logits: [batch_size * img_height * img_width * num_classes]
labels: [batch_size * img_height * img_width]
"""
with tf.name_scope(scope_name, 'dice_coef', [logits, labels]) as scope:
sm = tf.nn.softmax(logits)
... | fd2d8e2fd4cd975be7722e5d465b6b8ebc3b0a46 | 3,628,847 |
def say_to(user, msg):
"""Sends a private message to another user."""
return say(user, msg) | e983f3accbebfeec7c23d8324179cab1b5f41b82 | 3,628,848 |
def depthload(filename):
"""Loads a depth image as a numpy array.
"""
if filename.split(".")[-1] == "txt":
x = np.loadtxt(filename)
else:
x = np.asarray(Image.open(filename))
x = (x * 1e-3).astype("float32")
return x | 2af33c9c1ee79eacc8993438025d31e2f3cf3f5f | 3,628,849 |
def pinit():
"""
Initialize the option parser and return it.
"""
usage = "usage: %prog [options] [xml_topology_filename]"
parser = OptionParser(usage)
parser.add_option(
"-b",
"--build_root",
dest="build_root_overwrite",
type="string",
help="Overwrite e... | 39cdd7446cedf83cb7007bc0ee3fa65406d1e016 | 3,628,850 |
def window(window_type: WindowType, tmax: int):
"""Window functions generator.
Creates a window of type window_type and duration tmax.
Currently, hanning (also known as Hann) and hamming windows are available.
Args:
window_type: str, type of window function (hanning, squared_hanning,
ham... | 65bd8bb071d1435809b3f6d3b4a339ac5474d830 | 3,628,851 |
def download_project(token):
"""
Download a .trk/.npz file from a DeepCell Label project.
"""
project = Project.get(token)
if not project:
return abort(404, description=f'project {token} not found')
exporter = exporters.Exporter(project)
filestream = exporter.export()
return se... | 70326bc321a80d69ab871fa45aa5c217b1779a51 | 3,628,852 |
def cross_check_fields(new_instance, old_instance):
"""Check for changed fields between new and old instances."""
action_id = STATUS_ACTION.updated
class_name = get_class_name(new_instance)
changed_fields = []
usergroup_permission_fields = {}
for field in LOG_MODELS.get(new_instance.__class__.... | 6735cc60b8e113b10db55683779da6ecbeeceb9e | 3,628,853 |
def derive_totals_analysis(df, portfolio_kpis, portfolio_group_by, claims_group_by):
""" Derives the totals amounts from a summary table
Arguments --> the dataframe, the kpis on which the total sums must be derived
the segmentation, i.e. on which features the analysis will be performed
... | e349af10687c8b26c509f95c834cc50eb411aba6 | 3,628,854 |
import os
def crop(folder_path, file):
"""Crop image to dimensions 224 x 224
Args:
folder_path (str): pathname of directory where file lives
file (str): filename with extension
Returns:
path where resized image is saved
"""
im = Image.open(os.path.join(folder_path, file))... | a11ac98bd2969c38e4105df6259ef1133e243047 | 3,628,855 |
def fit_nGaussians (num, q, ws, hy, hx):
"""heights are fitted"""
h = np.random.rand(num) * np.average(hy) # array of guesses for heights
guesses = np.array([q, ws, *h])
errfunc = lambda pa, x, y: (nGaussians(x, num, *pa) - y)**2
# loss="soft_l1" is bad!
return optimize.least_squares(err... | 801d167c868103de72a1449d9797b875d8feafda | 3,628,856 |
def build_preprocessors(md_instance):
""" Build the default set of preprocessors used by Markdown. """
preprocessors = odict.OrderedDict()
preprocessors['normalize_whitespace'] = NormalizeWhitespace(md_instance)
return preprocessors | 7fc6fe9e4c9862b1485b11e7a9fae4aee704b2f0 | 3,628,857 |
import copy
def odeCFL3(schemeFunc, tspan, y0, options, schemeData):
"""
odeCFL3: integrate a CFL constrained ODE (eg a PDE by method of lines).
[ t, y, schemeData ] = odeCFL3(schemeFunc, tspan, y0, options, schemeData)
Integrates a system forward in time by CFL constrained timesteps
using... | e611f319f4cfc618688e7ab717d59a51ca000280 | 3,628,858 |
import torch
def greedy_action(model, state, device="cpu"):
"""
TODO
"""
with torch.no_grad():
Q = model(torch.Tensor(state).unsqueeze(0).to(device))
return torch.argmax(Q).item() | eed90b3b4b507aa35cf391d8810c42a3f83cf135 | 3,628,859 |
def decode_lazy(rlp, sedes=None, **sedes_kwargs):
"""Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoi... | 56e4398ddfaadd587201c59330206443efc3a34e | 3,628,860 |
def slider_accel_constraint(env, safety_vars):
"""Slider acceleration should never go above threshold."""
slider_accel = safety_vars['slider_accel']
return np.less(slider_accel, env.limits['slider_accel_constraint'])[0] | 5d1a5dec8f2e3e04f85add0bc2acddb9e8eee1ef | 3,628,861 |
def calculate_component_overlap(matches, thresh_distance):
"""
Calculate how much each connected component is made redundant (percent of nodes that have a neighbor within some
threshold distance) by each of its candidates.
Args:
matches (dict): output from `nodewise_distance_connected_components... | d9a91c6c6964c710a076939838a234e5a81bc85a | 3,628,862 |
def binary_otsus(image, filter:int=1):
"""Binarize an image 0's and 255's using Otsu's Binarization"""
if len(image.shape) == 3:
gray_img = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
else:
gray_img = image
# Otsus Binarization
if filter != 0:
blur = cv.GaussianBlur(gray_img, (3,... | 1a7dda3538fb0c1282acd3d075ecabc6de03c811 | 3,628,863 |
def get_struct(str_type):
"""
>>> assert get_struct(type(1)) == 'h'
>>> assert get_struct(type(1.001)) == 'd'
"""
str_type = str(str_type)
return type_to_struct[str_type] | b8209b0b190e8a162df8c718f9ec9b5e84cd2bfd | 3,628,864 |
def dumps(obj, *transformers):
"""
Serializes Java primitive data and objects unmarshaled by load(s) before
into string.
:param obj: A Python primitive object, or one loaded using load(s)
:param transformers: Custom transformers to use
:return: The serialized data as a string
"""
marsha... | 3593334de52d178fb6dd196dd34579a9839b4fac | 3,628,865 |
from typing import Tuple
from typing import List
from typing import Dict
def extract_lineage(p_id: int, partial_tree_ds: Tuple[List[int], List[int],
List[int], List[Item]]) -> Dict[int, List]:
"""Extract comment lineage."""
ids, indents, sorted_indents, items = partial_tree_ds
comment_lineage = {}
... | 7b3b62901004d8bb49e9dc9495d6b0bf0cbf8f63 | 3,628,866 |
def get_or_import(value, default=None):
"""Try an import if value is an endpoint string, or return value itself."""
if isinstance(value, str):
return import_string(value)
elif value:
return value
return default | 4e4b155647309b3159f0fa02cccdf43e835ca874 | 3,628,867 |
def check_trails_in_db(trail_wikiloc_ids):
"""
Returns a list of tuples (wikiloc trail_id, database trail_id)
with every trail from trail_wikiloc_ids that is already in the database
return (wikiloc_trail_id,db_trail_id)
"""
try:
connection = get_connection()
with connection.curso... | 01a61688b718f6c9caf16c56b445935c144df985 | 3,628,868 |
from typing import List
import concurrent
def from_saved_tracks(
output_format: str = None,
use_youtube: bool = False,
lyrics_provider: str = None,
threads: int = 1,
) -> List[SongObject]:
"""
Create and return list containing SongObject for every song that user has saved
`str` `output_fo... | 1278201abe8621b7122ca0e56c4c0516497aa4d9 | 3,628,869 |
def df2dicts(df):
"""
df to dicts list
"""
dicts = []
for line in df.itertuples():
ll = list(df.columns)
dicts.append(dict(zip(ll, list(line)[1:])))
return dicts | f63520c22766a2454e52f17d539a876d1eea4fa5 | 3,628,870 |
def read_flash_hex(decode_hex=False, **kwargs):
"""Read data from the flash memory and return as a hex string.
Read as a number of bytes of the micro:bit flash from the given address.
Can return it in Intel Hex format or a pretty formatted and decoded hex
string.
:param address: Integer indicating... | 6013fb5efda759c61c45785c0ee5661ba6480601 | 3,628,871 |
def naify_extreme_values(x, n_iqr=3):
"""
Replace extreme values in a pd.Series with NAs.
:param pd.Series x: a pandas Series which potentially has extreme values
:param int n_iqr: the number of IQR used to define extreme values. Default is 3.
:return:
"""
Q1 = np.nanquantile(x, 0.25)
Q3 = np.nanquantile(x, 0.... | 8cbfe06e8532d9965b8dd3218e771d68551a40c5 | 3,628,872 |
def saha(
graph, initial_partition=None, is_integer_graph=False
) -> SahaPartition:
"""
Returns an instance of the class :class:`SahaPartition` which can be used
to recompute the maximum bisimulation incrementally.
:param graph: The initial graph.
:initial_partition: The initial partition, or l... | b33544ff68ad03bbf295617fe97a30cb0e5bf502 | 3,628,873 |
def load_model(LOAD_DIR):
"""
Load model from a given directory, LOAD_DIR.
Parameters
----------
LOAD_DIR : text
Path of load directory.
Returns
-------
inverse_mapping :numpy array (floats)
The {NUM_MODES x p} matrix transform that maps the image patches to
the... | a06190b28ffe095f34730e341c1bdecc34108ee8 | 3,628,874 |
import argparse
import sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train Repeat Buyer Prediction Model')
parser.add_argument('--model', dest='model_name',
help='model to use',
default='dnn', type=... | d0632063b8b6931ad2bd8dc61627dfac2345ff4c | 3,628,875 |
import filecmp
def files_differ(path_a, path_b):
"""
True if the files at `path_a` and `path_b` have different content.
"""
return not filecmp.cmp(path_a, path_b) | ea0382e619228cd0fc042a9003c34f33bd53f313 | 3,628,876 |
def classical_mds(d, ndim=2):
"""
Metric Unweighted Classical Multidimensional Scaling
Based on Forrest W. Young's notes on Torgerson's (1952) algorithm as
presented in http://forrest.psych.unc.edu/teaching/p230/Torgerson.pdf:
Step 0: Make data matrix symmetric with zeros on the diagonal
Step 1... | 8d36106df219eae6219c6ef0f4bcaaaf334e7aa6 | 3,628,877 |
import re
def get_room_occupation():
"""Parse room from query params and look up its occupation."""
room = request.args.get('room')
if room:
room_args = re.split('([0-9]+)', room)
room_args = [arg for arg in room_args if arg != '']
if len(room_args) == 2:
try:
... | a804365be44a4b92eb7dd94d0d3ce030e91cd5a8 | 3,628,878 |
import hashlib
import six
import hmac
def calculate_ts_mac(ts, credentials):
"""Calculates a message authorization code (MAC) for a timestamp."""
normalized = ('hawk.{hawk_ver}.ts\n{ts}\n'
.format(hawk_ver=HAWK_VER, ts=ts))
log.debug(u'normalized resource for ts mac calc: {norm}'
... | fd4ad60a8b1d2540e2288f107aca11525a2e0e9a | 3,628,879 |
def select_largest(evaluator, minNumber=None, tolerance=None):
""" Selector of integer variables or value having the largest evaluation according to a given evaluator.
This function returns a selector of value assignments to a variable that selects all values having the
largest evaluation according to the ... | aa678fbc31e479da1fd82ee28f6cff4ef118fad7 | 3,628,880 |
def plot_pendulum(trajs):
"""
Plot trajectory of inverted pendulum
"""
fig, ax = plt.subplots(figsize=(12, 8), nrows=2, ncols=2, sharex=True)
ax[0][0].set_title("Pendulum Plant")
plot_component(ax[0][0], trajs, "plant", "states", 0, "position (m)")
plot_component(ax[0][0], trajs, "maneuver",... | 0c658dd1b2307514b0805ebbf8ec51cda5793456 | 3,628,881 |
def m2(topic_srs, topic_vol, sharpe, ref_vol, cum=False, annual_factor=1):
"""Calcs m2 return which is a port to mkt vol adjusted return measure.
The Sharpe ratio can be difficult to interpret since it's a ratio, so M2
converts a Sharpe to a return number.
Args:
topic_srs (Pandas DataFram... | 8b05b0419db895d1de756cfb8751b9311cd43eca | 3,628,882 |
def model_dir_str(model_dir, hidden_units, logits, processor, activation,
uuid=None):
"""Returns a string for the model directory describing the network.
Note that it only stores the information that describes the layout of
the network - in particular it does not describe any trainin... | 15543f6d5e5bf5224beef9a2855aa9949399dcfc | 3,628,883 |
def parse_mets_with_metsrw(mets_file):
"""Load and Parse the METS.
Errors which we encounter at this point will be critical to the
caller and so an exception is returned when we can't do any better.
"""
try:
mets = metsrw.METSDocument.fromfile(mets_file)
except AttributeError as err:
... | 6c82004dd55720904b5aee207beac45511ca8765 | 3,628,884 |
import argparse
def default_argument_parser():
"""
Returns the argument parser with the default options.
Inspired by the implementation of FAIR's detectron2
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
... | 8b639b4091da59a8652f8ecf4c88c826def6e674 | 3,628,885 |
def has_gain_user_privileges(description, cvssv2, cpe_type):
"""
Function determines whether particular CVE has "Gain user privileges
on system" as its impact.
:param description: description of CVE
:param cvssv2: CVSS version 2
:param cpe_type: One of {'a', 'o', 'h'} = application, operating s... | 4807f231f5917935f005ead86cea68b8dd0d60c2 | 3,628,886 |
def __scores(clf, testset):
"""
"""
accuracy_ = accuracy(clf, testset)
precision_, recall_ = precision_recall(clf, testset)
f1score_ = f1score(precision_, recall_)
return accuracy_, precision_, recall_, f1score_ | 0010d3f6954c45bee6a5f1c285fb0de596f645ef | 3,628,887 |
from typing import List
from typing import Dict
def format_recipe_tree_components_data(
recipe_tree_components: List[Dict]
) -> Dict:
"""
Returns a dictionary containing total weight of recipe and
subrecipe details.
"""
net_weight = 0
gross_weight = 0
standalone_recipe_items = []
f... | 674ae126971864e5f686ad8f0bac1eaace5aafe8 | 3,628,888 |
def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if np.isnan(n):
return np.nan
else:
n = np.int64(n)
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
... | 1ac9887f4b250a47131b1545ec69cb01e638ece2 | 3,628,889 |
def uniform1(a, b):
"""One number in a uniform distribution between a and b."""
return np.random.random() * (b - a) + a | cb15edda5d33e49e5802d94189a6d47e461ce3cf | 3,628,890 |
def manage_admin():
""" 管理员资料页面路由 """
if 'adminname' in session:
the_result = manage_the_admin(db, Option, request.form)
return the_result
else:
abort(404) | 1a3f2cc7a3e9332b2fbf788a86cbf996228b1b4d | 3,628,891 |
import re
def fetch_map():
"""Method for generating folium map with custom event for clicking inside."""
home_m = folium.Map(location=[41.8902142, 12.4900369], zoom_start=5, width=550, height=350)
home_m.add_child(folium.LatLngPopup())
home_m = home_m.get_root().render()
home_p = [r.start() for r ... | 781d20a8a16c591d4c47738454dd659e69317078 | 3,628,892 |
def calc_residual_ver(list_ulines, xcenter, ycenter):
"""
Calculate the distances of unwarped dots (on each vertical line) to each
fitted straight line which is used to assess the straightness of unwarped
lines.
Parameters
----------
list_ulines : list of 2D arrays
List of the c... | 9e9febb7cacfa31eebf8ebb1ffdb5f81e2788e50 | 3,628,893 |
import json
def create_stop_feedback(request):
"""stop feedback api endpoint"""
# verify that the calling user has a valid secret key
secret = request.headers.get('Secret')
if secret is None:
return request_response(unAuthenticatedResponse, ErrorCodes.INVALID_CREDENTIALS,
... | 1e8799b37354c2889c1103d85075fe36a966c3b7 | 3,628,894 |
def private_with_master(message):
""" Is a private message from bot owner?"""
return is_from_master(message) and message.chat.type == 'private' | 08c53736a386c79c322e44c70b88dda2241d3c36 | 3,628,895 |
from pathlib import Path
def test_data_filename() -> str:
"""Return filename containing eveuniverse testdata."""
return Path(__file__).parent / "eveuniverse.json" | c1334bf36a4db006b2bd26c18a759b13d9daf9d7 | 3,628,896 |
def sample_run(df, window_size = 500, com = 12):
"""
This functions expects a dataframe df as mandatory argument.
The first column of the df should contain timestamps, the second machine IDs
Keyword arguments:
n_machines_test: the number of machines to include in the sample
ts_per_machine... | cf8bb3fc94bf8ecd4383cb9946ad1407e2502be6 | 3,628,897 |
import itertools
def MRBL (cases, layersize):
"""
* Maximal Rectangles Bottom Left *
Similar to the guilliotine, but every time a new case is placed, no cut is made, both
newly generated spaces are kept in memory. This introduce the necessity to make some
additional cont... | b7781de8d6d07e64360ff65f143ed0f574ca897e | 3,628,898 |
def zenodo_records_json():
"""Load JSON content from Zenodo records file."""
data = None
with open(join_path(TEST_DIR, 'data/zenodo_records.json'), 'r') as f:
data = f.read()
return data | 1de1a908e596f5c78c86ee1584abd491b84f5174 | 3,628,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.