content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ldr_vartime_blockedby_pp_hat(arr_rate, pp_mean_svctime, pp_cap, pp_cv2_svctime):
"""
Approximate unconditional variance of time blocked in ldr waiting for a pp bed.
Modeling pp as an M/G/c queue and using approximation by Whitt.
"""
pp_svcrate = 1.0 / pp_mean_svctime
vartime = qng.ggm_qwait... | 4ec8a552473c07fb65a2b044fda906a01c7b7f1c | 34,689 |
def identify_crossing_events(df):
"""Identifies pore crossing events in data frame of domain indices.
Given a data frame of domain indices alongside time stamps and particle IDs,
this function identifies crossing events, i.e. a particle moving from one
side of the membrane to the other THROUGH THE PORE... | 583469263c319db59724e56a46c6f422486a230b | 34,690 |
from datetime import datetime
import calendar
import time
def timecode(acutime):
"""
Takes the time code produced by the ACU status stream and returns
a ctime.
Args:
acutime (float): The time recorded by the ACU status stream,
corresponding to the fractional day of th... | 41e5298777e1685041018e8aeee046a758ee4912 | 34,691 |
def calc_timedelta_in_years(start, end) -> float:
"""Computes timedelta between start and end dates, in years
To use this function, start and end dates should come
from a series of daily frequency.
Args:
start: start date
end: end date
Returns:
float: time delta in ... | 1833b69492b9c16a2b657da658f2f17dce2c3884 | 34,692 |
def listen(recognizer, mic, keywords, uses_google_api):
"""
Listens for a set of (keyword, priority) tuples and returns the response
:param recognizer: speech_recognition Recognizer object
:param mic: speech_recognition Microphone object
:param keywords: Iterable of (keyword, priority) tuples
:... | 1af6674edc6709da7a81e72cbfa84ec2df1eff64 | 34,694 |
from pynetio import Netio
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Netio platform."""
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
port = config.get(CONF_PORT)
if not DEVICES:
hass.htt... | 955a9b62f19eb4478c19339456cd74037f4ffdca | 34,695 |
def extract_username(message: Message) -> str:
"""
Extracts the appropriate username depending on whether
* it was mentioned in an Entity,
* it's accessible on message.author.id (discord)
* it's accessible on message.author (pyttman dev mode)
:param message:
:return: str
"""
... | 58a181abce89306b65228fd3f51c63925b5a467b | 34,696 |
def application(app_plan, custom_application, request, lifecycle_hooks):
"""
Creates an application with a application plan defined in the specified fixture
"""
application = custom_application(rawobj.Application(blame(request, "limited_app"), app_plan),
hooks=lifecy... | 6519af0a6aea26b4f4d7a39c325a06c9c993fda6 | 34,697 |
def reward_user_required(view_func):
"""
Decorator for views that checks that the user is logged in and can use
reward points.
"""
def check_user(user):
return can_reward_points_be_used_by(user)
return user_passes_test(check_user)(view_func) | aa499dc61d35537fc7e74404e0ead227da46a461 | 34,698 |
def dnv_registry_listing_soup(alphabetLetter, output_file_base):
"""
A method for collecting the list of ships that are in the DNV registry. From this list a list of available dnv-ids can be generated.
:param alphabetLetter: A capital letter of the alphabet
:param output_file_base: The base_name of the ... | 942404c074113b424f38a12af97619843b6109cb | 34,699 |
from corehq.apps.cloudcare import api
def get_cloudcare_app():
"""
Total hack function to get direct links to the cloud care application pages
"""
app = api.get_cloudcare_app(PACT_DOMAIN, PACT_CLOUD_APPNAME)
app_id = app['_id']
pact_cloudcare = [x for x in app['modules'] if x['name']['en'] ... | 3ff30de2549547902039df5bc5a0f140f3402954 | 34,700 |
from typing import Generator
def train_test_k_fold(n_folds: int, n_instances: int, rng: Generator = default_rng()) -> list:
""" Generate train and test indices at each fold.
Args:
n_folds (int): Number of folds
n_instances (int): Total number of instances
random_generator (np.random.G... | f3ce954ddf5ff83cd12b852d4e22e0ad7757301f | 34,701 |
def table_append(row, category='default'):
""" Take any number of string args and put them together as a
HTML table row.
"""
html_row = '</td><td>'.join(row)
html_row = f'<tr><td>{html_row}</td></tr>'
if category == 'header':
html_row = html_row.replace('td>', 'th>')
return html_row | cd0aa400c80ebc0ac8aad199439d5fc20d7a99a3 | 34,702 |
import six
def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, s... | 7354548bdd1da1d59ce4faac4cbc5a1b819a40e2 | 34,703 |
def _calculate_type_helper(primary_type, secondary_types):
"""
:type primary_type: :class:`mbdata.models.ReleaseGroupPrimaryType`
:type secondary_types: :class:`(mbdata.models.ReleaseGroupSecondaryType)`
"""
if primary_type.name == 'Album':
if secondary_types:
secondary_type_lis... | 24a973acd93b8c5d2cb1f2d2df14afc38c364a9d | 34,704 |
def detach_all_devices():
"""
Detaches all currently attached devices
"""
process = ractl.detach_all()
if process["status"]:
flash(_("Detached all SCSI devices"))
return redirect(url_for("index"))
flash(process["msg"], "error")
return redirect(url_for("index")) | c874441d9a64d30b2f706fcc8e49181378541f36 | 34,706 |
def md5sum(text):
"""Return the md5sum of a text string."""
return md5_constructor(text).hexdigest() | 29972c7bab3e7a6d2d78644b263bb058eb3677b6 | 34,709 |
def get_requests_to_user(user_id): #myrequests. Requests made to the user
"""
Returns the reviews for a listing given the listing id
"""
requests = ListingRequest.objects.filter(recipient__pk=user_id)
return requests | e4a6e74ebf8f153db4f1f2614a7e6b07c082c9c8 | 34,710 |
def descriptor(request):
"""
Replies with the XML Metadata SPSSODescriptor.
"""
acs_url = saml2sp_settings.SAML2SP_ACS_URL
entity_id = _get_entity_id(request)
pubkey = xml_signing.load_cert_data(saml2sp_settings.SAML2SP_CERTIFICATE_FILE)
tv = {
'acs_url': acs_url,
'entity_id'... | d739ca1b1792c5c059cbe0974e24229cb9f217dd | 34,711 |
def type_bframe(stage, bin, data=None):
"""BFrame"""
if data == None:
return 1
if stage == 1:
return (str(data),'')
try:
v = int(data)
if 0 > v or v > 255:
raise
except:
raise PyMSError('Parameter',"Invalid BFrame value '%s', it must be a number in the range 0 to 256" % data)
return v | 0ee1fe1d82f0f964899e70534989a035020763ab | 34,712 |
def last(data, ignore_nodata=UNSET) -> ProcessBuilder:
"""
Last element
:param data: An array with elements of any data type.
:param ignore_nodata: Indicates whether no-data values are ignored or not. Ignores them by default. Setting
this flag to `false` considers no-data values so that `null` ... | 97fdea2baf57e7efcc8aaf55b362852efe95ba60 | 34,714 |
def angle_wrap_pi(x):
"""wrap angle to [-pi, pi).
Arguments:
x -- angle to be wrapped
"""
return (x - np.pi) % (2 * np.pi) - np.pi | 8a6e4f5e3e9b467cae8afbda09fa35f6184f1247 | 34,715 |
def contains_end_of_message(message, end_sequence):
"""Función que dado un string message, verifica si es que end_sequence es un
substring de message.
Parameters:
message (str): Mensaje en el cual buscar la secuencia end_sequence.
end_sequence (str): Secuencia que buscar en el string message.
Returns:... | 3966e3e2ddf62843c2eb12cf6ae144e53408c360 | 34,716 |
import pandas
def decisionTree(dataFrame:pandas.DataFrame,predictors,outColumn,nFolds:int):
"""
Method for computing accuray and cross-validation using decision-tree
"""
if dataFrame is None:
return None
dataFrame=_encodeLabels(dataFrame)
model = DecisionTreeClassifier()
return cla... | 82f6c4e7f7956710cd613cc975aeb8fd6af6e7c1 | 34,717 |
def _cv2_show_tracks(img,
bboxes,
labels,
ids,
classes=None,
thickness=2,
font_scale=0.4,
show=False,
wait_time=0,
out_file=None):
... | 06c4b17c0bcd6bd4442637bff5542437c59562d1 | 34,718 |
def get_centers(bins):
"""Return the center of the provided bins.
Example:
>>> get_centers(bins=np.array([0.0, 1.0, 2.0]))
array([ 0.5, 1.5])
"""
bins = bins.astype(float)
return (bins[:-1] + bins[1:]) / 2 | 31047e21eea7c6d86ba713509fdac42b3b0c33cc | 34,719 |
def scale_by_yogi(
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-3,
eps_root: float = 0.0,
initial_accumulator_value: float = 1e-6
) -> base.GradientTransformation:
"""Rescale updates according to the Yogi algorithm.
Supports complex numbers, see
https://gist.github.com/wdphy16/118aef6f... | c65d1069741755bf5e5a5719b97c6553bfe525b7 | 34,720 |
def download(request):
"""
Serves patients full summary as a downloadable text file.
:param request: The request with user information
:return: Downloadable text file, in lieu of a conventional response
"""
Pat = Patient.objects.all().get(user=request.user)
content = MediInfoExport(Pat, re... | 8cae4bbe27853a19848059f0c6bc11c48865f151 | 34,721 |
def gradient_descent(F,x0,args=(),delta=1e-14,gamma0=1e-12,adapt=False,plot=False):
"""
Find a local minimum of a scalar-valued function of a vector (scalar field)
by the Gradient Descent method.
https://en.wikipedia.org/wiki/Gradient_descent
:param function F: Function to minimize. Initial use ca... | b710a768656a8bb0db16eafa87b88c91e83b38fd | 34,723 |
def superop2pauli_liouville(superop: np.ndarray):
"""
Converts a superoperator into a pauli_liouville matrix. This is achieved by a linear change of basis.
:param superop: a dim**2 by dim**2 superoperator
:return: dim**2 by dim**2 pauli-liouville matrix
"""
dim = int(np.sqrt(superop.shape[0]))
... | f7b9cd9a0dce0bf2f1e20c6f8024021acf85ef07 | 34,724 |
def utility_num2columnletters(num):
"""
Takes a column number and converts it to the equivalent excel column letters
:param int num: column number
:return str: excel column letters
"""
def pre_num2alpha(num):
if num % 26 != 0:
num = [num // 26, num % 26]
else:
... | 295b8c5391d5250f91781c2f6df1626a0acb8022 | 34,725 |
def binarize(query, mlb):
"""Transform a single query into binary representation
Parameters
----------
query : ndarray, shape = [n_samples, n_classes]
The tags.
n_samples : int
The number of samples in the training set.
Returns
-------
bin_query_vector : ndarray, shape ... | aafd2072569c0c740b034caa0f8591da231b5b6d | 34,727 |
from typing import Optional
from typing import Dict
def no_response_from_crawl(stats: Optional[Dict]) -> bool:
"""
Check that the stats dict has received an HTTP 200 response
:param stats: Crawl stats dictionary
:return: True if the dict exists and has no 200 response
"""
if not stats or not ... | 461d3deb9ec6a162dfd7f3f3c0ac73262090c35b | 34,728 |
def evaluate_surprisals_continuous(text, window_params, tot_params):
"""
Get the probability mass functions for each token's
semantic similarity using a beta distribution.
:param text: text to analyze; results are returned token-wise
Can be a string or a spaCy-parsed document.
:param params... | 7fe58fadc0fa9943a47aee1217b1246a8c0d9c13 | 34,730 |
def getUSBFile():
"""
Retrieves USB.ids database from the web.
"""
url = 'http://www.linux-usb.org/usb.ids'
return urllib2.urlopen(url) | 8199b9694db871ba9dcbd3b1338a416e8f4ac358 | 34,732 |
import time
import math
def get_local_time_zone():
"""Return the current local UTC offset in hours and minutes."""
utc_offset_seconds = -time.timezone
if time.localtime().tm_isdst == 1 and time.daylight:
utc_offset_seconds = -time.altzone
utc_offset_minutes = (utc_offset_seconds // 60) % 60
... | 4e90d0a0bf2e831aaf6629542451e75c0a1942a4 | 34,733 |
def connect_genes(t_trans_to_gene, t_trans_to_q_proj, q_proj_to_q_gene):
"""Create orthology relationships graph."""
o_graph = nx.Graph()
genes = set(t_trans_to_gene.values())
o_graph.add_nodes_from(genes)
q_genes_all = []
print(f"Added {len(genes)} reference genes on graph")
conn_count = 0
... | f062fd61dbe21472cca609b3f0b43a0663944cb7 | 34,734 |
def gbsGetSelectedBounds():
""" Get bonding box of features from selection
"""
clayer = iface.mapCanvas.currentLayer()
if not clayer or clayer.type() != QgsMapLayer.VectorLayer:
return None
box = clayer.boundingBoxOfSelected()
return box.toRectF() | 6e82fab64c2356f10b7e00d04a4a6b09ffbec499 | 34,735 |
from typing import Optional
def pixelmatch(
img1: ImageSequence,
img2: ImageSequence,
width: int,
height: int,
output: Optional[MutableImageSequence] = None,
threshold: float = 0.1,
includeAA: bool = False,
alpha: float = 0.1,
aa_color: RGBTuple = (255, 255, 0),
diff_color: RGB... | 95690f4584c7e90c63bb432418bb22068d3ab63e | 34,737 |
def binary_search(array, target):
""" Does a binary search on to find the index of an element in an array. WARNING - ARRAY HAS TO BE SORTED
Keyword arguments:
array - the array that contains the target
target - the target element for which its index will be returned
returns the index... | 6dfe09367e2dd7ae2e30f45009fa7059d0da0f18 | 34,738 |
import re
import ast
def _get_matrix_from_string(string):
"""Get a network connection matrix from a string.
Parameters
----------
string : str
String from which to read the matrix. It should have the format of a
string representation of a NumPy array.
Raises
------
Format... | 1d9a052e7506c379addd7f20ff2af5671f6a82ff | 34,739 |
import warnings
def classification_report(y_true, y_pred, labels=None, target_names=None,
sample_weight=None, digits=2, output_dict=False,
zero_division="warn"):
"""Build a text report showing the main classification metrics.
Read more in the :ref:`User Gui... | bf900670dee3ba3988ae987dd1a7067949bd224b | 34,741 |
def paralog_cn_str(paralog_cn, paralog_qual, min_qual_value=5):
"""
Returns
- paralog CN: string,
- paralog qual: tuple of integers,
- any_known: bool (any of the values over the threshold).
If paralog quality is less than min_qual_value, corresponding CN is replaced with '?' and qua... | 07012dd9b065622365798ba65024c316cdb8c0c7 | 34,742 |
def offbyK(s1,s2,k):
"""Input: two strings s1,s2, integer k
Process: if both strings are of same length, the function checks if the
number of dissimilar characters is less than or equal to k
Output: returns True when conditions are met otherwise False is returned"""
if len(s1)==len(s2):
flag... | a64c02b85acca64427852fc988ed2f769f750aa7 | 34,743 |
def calc_e_Gx(trainDataArr, trainLabelArr, n, div, rule, D):
"""计算分类错误率"""
e = 0 # 初始化误分类误差率为0
x = trainDataArr[:, n]
y = trainLabelArr
predict = []
if rule == 'LisOne':
L = 1
H = -1
else:
L = -1
H = 1
for i in range(trainDataArr.shape[0]):
if x... | 6b282e078746be5ba90944cfedfabf64e29fc1c6 | 34,744 |
from typing import Dict
from typing import List
from typing import Union
def compute_gap(
gold_mapping: Dict[str, int],
ranked_candidates: List[str],
) -> Union[float, None]:
"""
Method for computing GAP metric.
Args:
gold_mapping: Dictionary that maps gold word to its annotators number.
... | 1701679c313e96792596ffa6623cb0aec4d2ca2a | 34,745 |
def SmiNetDate(python_date):
"""
Date as a string in the format `YYYY-MM-DD`
Original xsd documentation: SmiNetLabExporters datumformat (ÅÅÅÅ-MM-DD).
"""
return python_date.strftime("%Y-%m-%d") | 8d43d99516fed915b344f42da8171689f8f9ef0b | 34,746 |
def get_node_with_children(node, model):
""" Return a short list of this top node and all its children.
Note, maximum depth of 10. """
if node is None:
return model
new_model = [node]
i = 0 # not really needed, but keep for ensuring an exit from while loop
new_model_changed = True
w... | 6ea214063f7937eacec5bbe5abd5c78c5b7badbd | 34,747 |
def correct_capitalization(s):
"""Capitalizes a string with various words, except for prepositions and articles.
:param s: The string to capitalize.
:return: A new, capitalized, string.
"""
toret = ""
if s:
always_upper = {"tic", "i", "ii", "iii", "iv", "v", "vs", "vs.", "2d",... | f49b3203bf7ea19b84ac707bcc506c2571082e39 | 34,748 |
def mockedservice(fake_service=None, fake_types=None,
address='unix:@test', name=None,
vendor='varlink', product='mock', version=1,
url='http://localhost'):
"""
Varlink mocking service
To mock a fake service and merely test your varlink client against.
... | b318f44b3091cf332922a59222795a61d2a0d48e | 34,749 |
def dsigmoid(x):
"""
return differential for sigmoid
"""
##
# D ( e^x ) = ( e^x ) - ( e^x )^2
# - --------- --------- ---------
# Dx (1 + e^x) (1 + e^x) (1 + e^x)^2
##
return x * (1 - x) | 685362146d7bfcaa3df47db8a10a04e6accb805d | 34,750 |
def get_filetype(location):
"""
LEGACY: Return the best filetype for location using multiple tools.
"""
T = get_type(location)
return T.filetype_file.lower() | 8fcb9f7fc77f4a50e5c20a5d46b7f6699520a314 | 34,751 |
def eps_r_op_2s_AA12(x, AA12, A3, A4, op):
"""Implements the right epsilon map with a non-trivial nearest-neighbour operator.
Uses a pre-multiplied tensor for the ket AA12[s, t] = A1[s].dot(A2[t]).
See eps_r_op_2s_A().
Parameters
----------
x : ndarray
The argument matrix.
... | 661528e04d56e78c399f7c0db7964f11eaba3441 | 34,752 |
def _bem_specify_coils(bem, coils, coord_frame, n_jobs):
"""Set up for computing the solution at a set of coils"""
# Compute the weighting factors to obtain the magnetic field
# in the linear potential approximation
coils, coord_frame = _check_coil_frame(coils, coord_frame, bem)
# leaving this in i... | b860dbaf3d844248d75c69d7c45aefabe76b28e9 | 34,753 |
def extract_plate_and_well_names(col_meta, plate_field=PLATE_FIELD, well_field=WELL_FIELD):
"""
Args:
col_meta (pandas df)
plate_field (string): metadata field for name of plate
well_field (string): metadata field for name of well
Returns:
plate_names (numpy array of string... | 0aa3a34a537183fca17e6575853df628f1204b62 | 34,754 |
import torch
from typing import List
from typing import Any
import itertools
def apply_masked_reduction_along_dim(op, input, *args, **kwargs):
"""Applies reduction op along given dimension to strided x
elements that are valid according to mask tensor.
The op is applied to each elementary slice of input w... | ccc1364404ca359732f85a470284310b852f4287 | 34,755 |
def index_gen(x):
"""Index generator.
"""
indices = np.arange(*x, dtype='int').tolist()
inditer = it.product(indices, indices)
return inditer | 1ef5cd55ea7a8627bc2a1a14425035a2c5f7172e | 34,756 |
def pad_xr_dims(input_xr, padded_dims=None):
"""Takes an xarray and pads it with dimensions of size 1 according to the supplied dims list
Inputs
input_xr: xarray to pad
padded_dims: ordered list of final dims; new dims will be added with size 1. If None,
defaults to standard naming ... | 73f558b010527360f47b6558350a929041557cce | 34,757 |
from datetime import datetime
def get_list_projects_xlsx(proposals):
"""
Excel export of proposals with sharelinks
:param proposals:
:return:
"""
wb = Workbook()
# grab the active worksheet
ws = wb.active
ws.title = "BEP Projects"
ws['A1'] = 'Projects from {}'.format(settin... | 668e70eb5d9d61ac879a270cdce54953fd7c2f5b | 34,758 |
import logging
def get(model=None, algorithm=None, trainer=None):
"""Get an instance of the server."""
if hasattr(Config().server, 'type'):
server_type = Config().server.type
else:
server_type = Config().algorithm.type
if server_type in registered_servers:
logging.info("Server... | e2c93998424ea381b8638408512181e5c50a2839 | 34,759 |
def par_impar(n):
"""
Par Impar
Admite un numero y evalua si es par
Parameters
-----------
n : int
Numero a evaluar
Returns
-------
bool
Resultado de evaluar si es par el numero
"""
if n%2 == 0 :
return Tr... | c81141b3fad9ed2cdb5537867a7414cd4e7ec03d | 34,760 |
import csv
def get_attacks_percent (a_data, a_index, dataset= None):
""" Return the % for each attack in a_index of the dataset """
percents = {}
attacks = {}
#for a, index in attacks_map.items():
#percents[a]= 0
for a, index in _attack_classes.items():
percents[a] = 0
total = ... | bd86b9ef507790aca4be8d7a8a371e8000253065 | 34,761 |
import requests
import json
import collections
def do_login(user, password):
"""Log-in and return auth token"""
login_payload = {
"login": {
"email": user,
"password": password
}
}
login_response = requests.post(URL_LOGIN, json=login_payload)
login_ans = j... | fe3a8158e7539f69eaa6c7f3daf4e9a5c3fa0770 | 34,762 |
def pow(x, y):
"""Return x raised to the power y.
:type x: numbers.Real
:type y: numbers.Real
:rtype: float
"""
return 0.0 | 618f0e03b7d6f476d7fbde8fcbeb699ce23d2a6c | 34,763 |
def make_secondary_variables():
"""Make secondary variables for modelling"""
secondary = read_secondary()
secondary_out = secondary.rename(columns={"geography_code": "geo_cd"})[
["geo_cd", "variable", "value"]
]
compl = make_complexity()
return pd.concat([secondary_out, compl]) | 0faaa916c1251fa61b3438f59b05c5ff21f8f253 | 34,764 |
def normalize_tuple(value, rank):
"""Repeat the value according to the rank."""
value = nest.flatten(value)
if len(value) > rank:
return (value[i] for i in range(rank))
else:
return tuple([value[i] for i in range(len(value))] +
[value[-1] for _ in range(len(value), r... | 1c1c105c50399770029e48c05ba998b921e8c834 | 34,765 |
def standard_Purge(*args):
"""
* Deallocates the storage retained on the free list and clears the list. Returns non-zero if some memory has been actually freed.
:rtype: int
"""
return _Standard.standard_Purge(*args) | 7accaa2d1686ef54a2e233f563ee47f962fa418a | 34,766 |
def metrics(label: np.ndarray, pred: np.ndarray, num_class: int):
"""
:param label: (h, w)
:param pred: (h, w)
:param num_class:
:return:
"""
label = label.astype(np.uint8)
pred = np.round(pred)
mat: np.ndarray = np.zeros((num_class, num_class))
[height, width] = label.shape
... | 26409f0645fa0f47b4241cbb2c9804299ed34f22 | 34,767 |
def is_transpositionally_related(set1, set2):
"""
Returns a tuple consisting of a boolean that tells
if the two sets are transpositionally related, the
transposition that maps set1 to set2, and the
transposition that maps set2 to set1. If the boolean
is False, the transpositions are None.
... | 4eb7375de84af2b531b330bf5a0aaa6d3b7825dc | 34,769 |
from typing import List
def find_dimension_coordinate_mismatch(
first_cube: Cube, second_cube: Cube, two_way_mismatch: bool = True
) -> List[str]:
"""Determine if there is a mismatch between the dimension coordinates in
two cubes.
Args:
first_cube:
First cube to compare.
s... | 64ffb776e652a68aee39ccfcb4b5dc718ca46b44 | 34,770 |
def patch_python(filename, dart=False, python='PYTHONJS', backend=None):
"""Rewrite the Python code"""
code = patch_assert(filename)
## a main function can not be simply injected like this for dart,
## because dart has special rules about what can be created outside
## of the main function at the m... | 20909844b686e9887aee893c9d7cb2759c64bb75 | 34,771 |
from typing import List
from typing import Union
def get_standard_binary_metrics() -> List[Union[AUC, str, BinaryMetric]]:
"""Return standard list of binary metrics.
The set of metrics includes accuracy, balanced accuracy, AUROC, AUPRC,
F1 Score, Recall, Specificity, Precision, Miss rate,
Fallout and... | 7f21eb48a84cda194343c75e9416deb6f7157081 | 34,772 |
def Xor(n):
"""Return a DataSet with n examples of 2-input xor."""
return Parity(2, n, name="xor") | 5f4682413eb21ecb05506762405347678f7ad699 | 34,773 |
def feature_selection(dataframe, method, missing_value_threshold=60, variance_threshold=0, correlation_threshold=0.75,
target_variable=None,
task=None, algorithm='RandomForest', n_features_to_select=5, scoring=None, cv=5, n_jobs=None):
"""
This function is used for se... | 1b1b760f39a8e679ab0a3ab5d22f55047c3a71ab | 34,774 |
import numpy
def shaped_reverse_arange(shape, xp=nlcpy, dtype=numpy.float32):
"""Returns an array filled with decreasing numbers.
Args:
shape(tuple of int): Shape of returned ndarray.
xp(numpy or nlcpy): Array module to use.
dtype(dtype): Dtype of returned ndarray.
Returns:
... | 3f2634e8299d52a54b2fe2baba41b25187b1c720 | 34,775 |
def then(value):
"""
Creates an action that ignores the passed state and returns the value.
>>> then(1)("whatever")
1
>>> then(1)("anything")
1
"""
return lambda _state: value | 5cf3f7b64b222a8329e961fa6c8c70f6c2c4cab0 | 34,776 |
def compute_cvm(predictions, masses, n_neighbours=200, step=50):
"""
Computing Cramer-von Mises (cvm) metric on background events: take average of cvms calculated for each mass bin.
In each mass bin global prediction's cdf is compared to prediction's cdf in mass bin.
:param predictions: array-like, pred... | cc34cb799211016d04d0431479252fb7fc77f186 | 34,777 |
import tqdm
def get_pmat(index_df:PandasDf, properties:dict) -> tuple((PandasDf, PandasDf)):
"""
Run Stft analysis on signals retrieved using rows of index_df.
Parameters
----------
index_df : PandasDf, experiment index
properties: Dict
Returns
-------
index_df: PandasDf, experim... | 79da78dc8c9e63e8f8aee1ac96a079a5d6c626ab | 34,778 |
def delete_upload_collection(upload_id: str) -> str:
"""Delete a multipart upload collection."""
uploads_db = uploads_database(readonly=False)
if not uploads_db.has_collection(upload_id):
raise UploadNotFound(upload_id)
uploads_db.delete_collection(upload_id)
return upload_id | c110ddf2d60e2f55a16b550f48abdfbc99c70975 | 34,779 |
import numpy
def setup_hull(domain,isDomainFinite,abcissae,hx,hpx,hxparams):
"""setup_hull: set up the upper and lower hull and everything that
comes with that
Input:
domain - [.,.] upper and lower limit to the domain
isDomainFinite - [.,.] is there a lower/upper limit to the doma... | 9848b9cd08724b4c830d7590cd48a2d3047422e7 | 34,780 |
def get_candidates(arrange_mode_attr):
"""
According current `arrange_mode` and `condition`, to find out
candidates data returns to caller
return candidates for displaying
Variables:
arrange_mode: Different mode has different method to select candidates
arrange_condition: The type_id list ... | 1be9737ec48804589c8a711f7ae1ae0c70523020 | 34,781 |
def img_to_array(model_input: any) -> any:
"""Converts the incoming image into an array."""
model_input = keras.preprocessing.image.img_to_array(model_input)
return model_input | bee59b1d6da102f2f11410f38c3e5587a28cf7b4 | 34,782 |
def add_word_vector_feature(dataset,
propositionSet,
parsedPropositions,
word2VecModel=None,
pad_no=35,
has_2=True,
):
"""Add word2vec feature to th... | d9708b61c1a7f16d3ee35f9dfa4ccc2d0b8c96b7 | 34,783 |
def clustering(vertice):
"""Calcula el coeficiente de clustering de un vertice.
Obs: Devuelve -1 si el coeficiente no es calculable.
Pre: EL vertice existe y es de clase Vertice.
"""
# Cuento las conexiones (por duplicado)
aristas_entre_vecinos = 0
for vecino in vertice.iter_de_adyacentes():
for segundo_vecino... | 0654ab7207174c47d9d0b626ca92894e6330612f | 34,784 |
import requests
def main(formato, full=False):
"""
Get dict of mains and dict of sides.
:formato: str (e.g.: "standard" or "modern")
:full: bool (True for scraping all decks from /full#paper and False for scraping only first decks from /#paper url)
:return:
"""
url_start = "https://www.m... | 2f5bdcb98185e11bafc1b5aba0df28962c6c4890 | 34,785 |
def pipeline(img, mtx, dist):
"""
The pipeline applies all image pre-processing steps to the image (or video frame).
1) Undistort the image using the given camera matrix and the distortion coefficients
2) Warp the image to a bird's-eye view
3) Apply color space conversion
:param img: Input image... | dd84f0296eb22cc41e0795c4e4c3821deb8e0896 | 34,786 |
def get_coverage_value(coverage_report):
"""
extract coverage from last line:
TOTAL 116 22 81%
"""
coverage_value = coverage_report.split()[-1].rstrip('%')
coverage_value = int(coverage_value)
return coverage_value | ffd47b6c4ecec4851aab65dcb208ef776d12e36f | 34,787 |
import textwrap
def collapse_single_path(digraph, path):
"""
:param digraph: networkx.DiGraph
:param path: list of nodes (simple path of digraph)
:return: networkx.DiGraph with only first and last nodes and one edge between them
The original graph is an attribute of the edge
"""
digraph_... | f65c98bdc29ffc2cc51f8570f545093fb4afa709 | 34,788 |
import random
def generate_data(train_test_split):
""" Generates the training and testing data from the splited data
:param train_test_split:
train_test_split - array[list[list]]: Contains k arrays of training and test data splices of dataset
Example: [[[0.23, 0.34, 0.33, 0.12, 0.45, 0.6... | 8de3cbab8b58be3ff7ff289d9aa8d3cd9e2581f8 | 34,789 |
import time
def process_roses(stations, ncpus, roses_fp, discard_obs_fp):
"""
For each station we need one trace for each direction.
Each direction has a data series containing the frequency
of winds within a certain range.
Columns:
sid - stationid
direction_class - number between 0 and... | 032e3f16dccd6361b036dcbd47ea41f1d723da0c | 34,790 |
from typing import Tuple
def find_tsm_marker(content: bytes, initial_key: bytes) -> Tuple[int, int]:
"""Search binary lua for an attribute start and end location."""
start = content.index(initial_key)
brack = 0
bracked = False
for _end, char in enumerate(content[start:].decode("ascii")):
... | 735bd61ed97654d9f78eee8dce055b06598ffb57 | 34,791 |
import torchvision
def create_fashion_mnist_dataset(train_transforms, valid_transforms):
""" Creates Fashion MNIST train dataset and a test dataset.
Args:
train_transforms: Transforms to be applied to train dataset.
test_transforms: Transforms to be applied to test dataset.
"""
# This code ... | 6d77907a715a9e7eabccb29dc62c4213f6748e10 | 34,792 |
def get_user_profile(request):
"""Method to get a user
Recieves: request, relevant email
Returns: httpresponse showing user
"""
if request.method != "POST":
return HttpResponse("only POST calls accepted", status=404)
#input validation
try:
user = User.objects.get(email=reque... | f3298ca1f671fe28600d122ca3ea1554c26107db | 34,793 |
async def read_product(
*, product_id: int, db_product: Product = Depends(get_product_or_404)
):
"""
Get the product type by id
"""
# Le righe commentate sotto, sostituite dalla nuova Depends
# Nota: il parametro product_id a get_product_or_404 è preso dal path
# p = session.get(Product, pro... | 8d31c7bd94959828a471bb3b521549db93b89ec3 | 34,794 |
def geometry_file_path(prefix, bath, pot):
""" geometry file path
"""
return GEOMETRY_FILE.path([prefix, bath, pot]) | 45afe3bfcb49ecfcae6876e0d1e1bb9f9e15bf80 | 34,795 |
def find_hessian_diag(point, vars=None, model=None):
"""
Returns Hessian of logp at the point passed.
Parameters
----------
model: Model (optional if in `with` context)
point: dict
vars: list
Variables for which Hessian is to be calculated.
"""
model = modelcontext(model)
... | 6998b6bf575babfec3fd97890bed315f26f21ac1 | 34,797 |
def apply_with_random_selector(x, func, num_cases):
"""Computes func(x, sel), with sel sampled from [0...num_cases-1].
Args:
x: input Tensor.
func: Python function to apply.
num_cases: Python int32, number of cases to sample sel from.
Returns:
The result of func(x, sel), wher... | 7dae42b240932fa90e3d6dabceba05375a024c56 | 34,798 |
def fitted_model(dates, spectra_obs, max_iter, avg_days_yr, num_coefficients):
"""Create a fully fitted lasso model.
Args:
dates: list or ordinal observation dates
spectra_obs: list of values corresponding to the observation dates for
a single spectral band
num_coefficients:... | 4754cafc79edfc52f47f925b909e3221c6b16f86 | 34,799 |
def example_bytes(values):
"""Input must be float32 np.array"""
return tf.train.Example(
features=tf.train.Features(
feature={'dosages': _bytes_feature(values.tobytes())}
)
) | 1db2de7db6b93e414e7636107a40c510dda1cadd | 34,800 |
def _build_extension_download_url(
extension_name: str, publisher_name: str, version: str
) -> str:
"""
Build the download url for the given parameters.
Just a shortcut for the string formatting.
:param extension_name: Desired extension name.
:type extension_name: str
:param publisher_name:... | 884ad99bb7e2d1c7d4fe7cc53f277962eb47414d | 34,802 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.