content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 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 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 |
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 |
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 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 |
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 |
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 |
def set_season():
"""
Facilitates the user entering what season it is. Returns the appropriate
string.
"""
error = False
while True:
clear_screen()
options = ["Spring", "Summer", "Fall"]
print("What season is it?")
# Prints out the options array in a numbered fas... | 7be0a588460d165fd716bdf83f30b9175f58347f | 3,628,900 |
import http
def extract_rooms_or_global(req, admin=True):
"""
Extracts the rooms / global parameters from the request body checking them for validity and
expanding them as appropriate.
Throws a flask abort on failure, returns (rooms, global) which will be either ([list of Rooms],
None) for a room... | 7ebd6ba77462feb9465cc21e01854f365287a2d6 | 3,628,901 |
def info(msg):
"""
Informational logging statement
:param msg: the message to print
:returns: True -- to allow it as an #assert statement
"""
return log("info", msg, logger) | 2fb1dc02aaf703ffc87381bdd271460e299022c7 | 3,628,902 |
from typing import Counter
def error_correct_BC_or_UMI(records, key, threshold=1):
"""
:param records: should be list of records all from the same gene!
"""
assert key in ('BC', 'UMI')
merge_map = {}
bc_count = Counter()
for r in records: bc_count[r[key]] += 1
# most common BC, in dec... | 4d06243d18b11d2ed18e356882e57e9f6d6bbf81 | 3,628,903 |
def add_category():
"""
Create category for database.
Inject all form data to new category document on submit.
"""
all_plant_types = mongo.db.plant_types.find()
all_shade_tolerance = mongo.db.shade_tolerance.find()
return render_template('addcategory.html',
... | 60d512b1ee22f1b57ab4df5fad4d85a990b567ff | 3,628,904 |
def load_seed_from_file(seed_path):
"""Load urls seed from file"""
seed_urls = urls.load_urls_from_file(seed_path)
return seed_urls | 5161506657dd348a6119f2d97d95230ec9273d3c | 3,628,905 |
def loads(csvdoc, columns=None, cls=Row, delimiter=",", quotechar='"',
typetransfer=False, csv_size_max=None, newline="\n"):
"""Loads csv, but as a python string
Note: Due to way python's internal csv library works, identical headers will overwrite each other.
"""
return _loads(csvdoc, co... | 54373d743a515375e6040b4cdc518866838de610 | 3,628,906 |
import warnings
def cluster_association_test(res, y_col='cmember', method='fishers'):
"""Use output of cluster tallies to test for enrichment of traits within a cluster.
Use Fisher's exact test (test='fishers') to detect enrichment/association of the neighborhood
with one variable.
Tests the 2 x 2 t... | 13c6f5de6c3548eb396ba73128adbc8714a09b5f | 3,628,907 |
def parse_collection_page(wikitext):
"""Parse wikitext of a MediaWiki collection page created by the Collection
extension for MediaWiki.
@param wikitext: wikitext of a MediaWiki collection page
@type mwcollection: unicode
@returns: metabook.collection
@rtype: metabook.collection
""... | 5ed31d3a52d42e4496bc19f522bc1e223a0ed92d | 3,628,908 |
from typing import List
def _ensure_hms(inner_result: ParsedDate, remain_tokens: List[str]) -> ParsedDate:
"""
This function extract value of hour, minute, second
Parameters
----------
inner_result
already generated year, month, day value
remain_tokens
remained tokens used for ... | 5e24e2ec9a8ddd6b866aaaafce054d4e04adba8d | 3,628,910 |
from . import auth, tally
from .auth.models import User
from .tally.models import Bill, Category
def create_app(config=Config):
"""App factory."""
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
migrate.init_app(app, db)
bcrypt.init_app(app)
login_manager.init_app(ap... | 3a39f8ab497fa539ea6609a7e53195e441adce1f | 3,628,911 |
def helper(n, largest_digit):
"""
:param n: int, a number
:param largest_digit: int,
:return: int, the largest digit
"""
if n == 0: # base case
return largest_digit
else:
if n < 0: # convert negative n into positive if any
n = n * -1
if n % 10 > largest_digit:
largest_digit = n % 10
return help... | 557a6ce39a31f7edd2438bea43be9d8abfec47c5 | 3,628,912 |
def peak_compare_data(request, peak_compare_list):
"""
:param request: Request for the peak data for the Peak Explorer page
:return: The cached url of the ajax data for the peak data table.
"""
analysis = Analysis.objects.get(name='Tissue Comparisons')
if peak_compare_list == "All":
pe... | 2d78e803ea1643db24bf4c4695476d16ac254237 | 3,628,913 |
def _generic_filtering_element(F, Q, H, R, y):
"""
Equation 10 in "GPR in Logarithmic Time"
"""
S = H @ (Q @ H.T) + R
chol = cho_factor(S)
Kt = cho_solve(chol, H @ Q)
A = F - (Kt.T @ H) @ F
b= Kt.T @ y
C = Q - (Kt.T @ H) @ Q
HF = H @ F
eta = HF.T @ np.squeeze(cho_solve(ch... | a74f198fc1afcd65f4cc668f9b8aa54b48de1132 | 3,628,914 |
def getStrFromAngles(angles):
"""
Converts all angles of a JointState() to a printable string
:param angles (sensor_msgs.msg.JointState): JointState() angles to be converted
:return (string): string of the angles
"""
d=getDictFromAngles(angles)
return str( dict(d.items())) | a1680e20dc1c58e2f17e8086089a30b3717e2083 | 3,628,915 |
from typing import Callable
import types
def jit_user_function(func: Callable, nopython: bool, nogil: bool, parallel: bool):
"""
JIT the user's function given the configurable arguments.
"""
numba = import_optional_dependency("numba")
if isinstance(func, numba.targets.registry.CPUDispatcher):
... | 41b8551e19ac103e8bd50188a16bf3ca7abfa27b | 3,628,916 |
def aggregate_on_dns(ip_values, ip_fqdns, is_numeric=True):
"""
Aggregates the values in ip_values based on domains accessed from
ip_fqdns. Values from same ip_addresses same domain names are combines
Args:
ip_values (dictionary): maps ip address to some computed value
... | 036edc22544f9e566eb0d76280f59cf68d2bfb33 | 3,628,917 |
def get_users():
"""
Fetch a dictionary of username and their IDs from Slack
"""
slack_api_client = connect()
api_call = slack_api_client.api_call('users.list')
if api_call.get('ok'):
user_list = dict([(x['name'], x['id']) for x in api_call['members']])
return user_list
else:
print 'Error Fetching Users'
... | 7a962d9360f6195ab5185dfb449a2370f5ebc0e0 | 3,628,918 |
import random
def topological_sort(graph):
# type: Dict[str, List[str]] -> Optional[List[Tuple[Union[str, int]]]]
"""Return linear ordering of the vertices of a directed graph.
https://leetcode.com/problems/course-schedule (analogous)
"""
result = []
counter = len(graph)
# Select random ... | fc35bbb92cda977ce5183970844ee20207b3b896 | 3,628,919 |
def lower_bound(expressions):
"""Creates an `Expression` lower bounding the given expressions.
This function introduces a slack variable, and adds constraints forcing this
variable to lower bound all elements of the given expression list. It then
returns the slack variable.
If you're going to be lower-bound... | 948089321ac043254fde3da6d4c139676b7a533c | 3,628,920 |
import networkx
def do_to_networkx(do):
"""Return a networkx representation of do"""
terms = do.get_terms()
dox = networkx.MultiDiGraph()
dox.add_nodes_from(term for term in terms if not term.obsolete)
for term in dox:
for typedef, id_, name in term.relationships:
dox.add_edge(... | 97c27a5e6ec3c0467fe42f34325aac5b565f5be3 | 3,628,922 |
def _prepare_data(data):
"""Takes the raw data from the database and prepares it for a sklearn workflow"""
# Get the number of turbines
n_turb = data[0]["lat"].size
# Split the data into the prediction and learning sets
data_learn = [d for d in data if not np.isnan(d["power"])]
data_new = [d fo... | b1397ae90a725958242ac8257db8cccdf299a61f | 3,628,924 |
from .common import parse_gset_format as redirect_func
import warnings
def parse_gset_format(filename):
""" parse gset format """
# pylint: disable=import-outside-toplevel
warnings.warn("parse_gset_format function has been moved to "
"qiskit.optimization.ising.common, "
... | 55a8259720a4680027c345868e2f47e2296532f1 | 3,628,925 |
def find_largest(line: str) -> int:
"""Return the largest value in line, which is a whitespace-delimited string
of integers that each end with a '.'.
>>> find_largest('1. 3. 2. 5. 2.')
5
"""
# The largest value seen so far.
largest = -1
for value in line.split():
# Remove the tra... | 95ceb1e79812e9ef9c7338f393e9d22224eb5a03 | 3,628,926 |
def get_arch(bv):
"""Arch class that gives access to architecture-specific functionality."""
name = bv.arch.name
if name == "x86_64":
return AMD64Arch()
elif name == "x86":
return X86Arch()
elif name == "aarch64":
return AArch64Arch()
else:
raise UnhandledArchitec... | 3895e5a9b8874aea5bdd5a54f46d91a89eeaef7d | 3,628,927 |
def _volume_1_atm(_T, ranged=True):
"""m**3 / mol"""
return 1 / _ro_one_atm(_T, ranged) | 47d8b0f21f9e893c79b477b9edb5892bc74951dd | 3,628,929 |
def isAmdDevice(device):
""" Return whether the specified device is an AMD device or not
Parameters:
device -- DRM device identifier
"""
vid = getSysfsValue(device, 'vendor')
if vid == '0x1002':
return True
return False | 4eb44cafaef5d2251a8152613f185dba680b8501 | 3,628,930 |
def pre_sif_mean_inner(mat, freqs, a, dtype=None):
"""
From *A Simple but Tough-to-Beat Baseline for Sentence Embeddings*
https://openreview.net/forum?id=SyK00v5xx
https://github.com/PrincetonML/SIF
"""
# 1. Normalize
mat = normalize(mat)
# 2. Reweight
rows, cols = mat.shape
for ... | 4ba6f4b30ff4dd763b9cfe975daaaeae842ff866 | 3,628,931 |
import json
def v1() -> Response:
"""
Handle Endpoint: /a2j/v1/
:return: HTTP Response.
:rtype: Response
"""
return Response(json.dumps({
"endpoints": ["parse", "clean"]
}), mimetype="application/json") | 1aee5b7011841951bed21c669b5758bf5d4ef9ed | 3,628,932 |
def apply_phase(signal, phase, frequency, fs):
"""Apply phase fluctuations.
:param signal: Pressure signal.
:param phase: Phase fluctuations.
:param frequency: Frequency of tone.
:param fs: Sample frequency.
Phase fluctuations are applied through a resampling.
"""
delay = delay_fluctu... | 19256fc1bf932b1c064a09ab6feec1367b9b8467 | 3,628,933 |
def __load_aug_img__(path, img_size, img_aug):
"""
"""
img = image.img_to_array(image.load_img(path, target_size=img_size))
if img_aug is not None:
img = img_aug.random_transform(img)
return img | b2be41b76a6a6667ed3ee3f99189975083b931d5 | 3,628,934 |
def _shot_id_to_int(shot_id):
"""
Returns: shot id to integer
"""
tokens = shot_id.split(".")
return int(tokens[0]) | 59d0ecabf874841d616a72ebea1ebac6e6dc3947 | 3,628,935 |
import ctypes
def get_native_pointer_type(pointer_size: int):
"""
:return: A type that can represent a pointer.
"""
return {
ctypes.sizeof(ctypes.c_uint32): ctypes.c_uint32,
ctypes.sizeof(ctypes.c_uint64): ctypes.c_uint64,
}[pointer_size] | 2364bde2f7bfb7ce2b743d8958551156c847f847 | 3,628,936 |
def get_bootinfo():
"""build and return boot info"""
vmraid.set_user_lang(vmraid.session.user)
bootinfo = vmraid._dict()
hooks = vmraid.get_hooks()
doclist = []
# user
get_user(bootinfo)
# system info
bootinfo.sitename = vmraid.local.site
bootinfo.sysdefaults = vmraid.defaults.get_defaults()
bootinfo.serve... | 1eb4060aa184f351b42a3b8fcad4e38e91efab2e | 3,628,937 |
def monkey_all_handler():
"""
@api {get} /v1/monkey/all ๆฅ่ฏข Monkey ๆต่ฏๅ่กจ
@apiName GetMonkeyAll
@apiGroup ่ชๅจๅๆต่ฏ
@apiDescription ๆฅ่ฏข ๆๆ็ monkey ๆต่ฏไฟกๆฏ
@apiParam {int} [page_size] ๅ้กต-ๅ้กตๆฐ็ฎ
@apiParam {int} [page_index] ๅ้กต-้กตๆฐ
@apiParam {int} [user_id] ็จๆท ID๏ผ่ทๅๅฝๅ็จๆท ID ็ monkey ๆต่ฏไฟกๆฏ
@apiParam {in... | 212e41f66a363e7a325df8c6459cd7d8a418b78f | 3,628,938 |
from datetime import datetime
def get_all_schedules(db_cur, server_id, is_async):
"""Extract all candidate schedules for a server
+--------- minute (0 - 59)
| +--------- hour (0 - 23)
| | +--------- day of the month (1 - 31)
| | | +--------- month (1 - 12)
| | | | +--------- day of the week (0... | 781697a3d98a6d9bdcad50b7bbb10d42f0385149 | 3,628,939 |
def predicted_win(board: Board, draws: list[int]) -> Prediction:
"""
Goes through the drawn numbers and returns a Prediction, which is a tuple of
two numbers:
- the turn on which the board wins
- the score of the board at that moment
"""
lines = board_lines(board)
for i, draw in enumerat... | 5f45de9ef755eea432e9a80dd6a9109c6673b183 | 3,628,940 |
from typing import Union
from typing import Sequence
from typing import Optional
from typing import Iterable
from typing import Tuple
from typing import List
def quantity_data_frame(bundle: Union[InstanceBundle, Sequence[InstanceBundle]],
quantity_name: str,
us: Optiona... | 1b9787d25ce20bebd73dc9a08743153266e08d06 | 3,628,941 |
from typing import Union
from typing import List
def trim_name(names: Union[List[str], str]) -> Union[List[str], str]:
"""Trims the name from the web API, specifically from IFTTT (removes extra "the ")"""
# Single name
if isinstance(names, str):
trimmed_name = names.lower().replace("the", "").str... | ee0bf0dcb9353fcad1b4af5f50bf2ff208c1dbe2 | 3,628,942 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.