content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def complex_to_real(X):
"""
WRITEME
Parameters
----------
X : list of complex vectors
Notes
-----
This function assumes X as 2D
"""
new_X = []
for i in range(len(X)):
x = X[i]
new_x = np.concatenate([np.real(x), np.imag(x)])
new_X.append(new_x)
ret... | 33394d089776487e8944b140789624f15fd0df70 | 66,451 |
def num_particles(fs):
"""Mean-field occupation."""
return np.sum(n * fs[n] * fs[n] for n in range(len(fs))) | 91abf67da32b81b36b6d3e9468b87f4516c58538 | 66,453 |
from pathlib import Path
def find_files(base_root: Path):
"""
Search the given base directory for the actual dataset root.
This makes it a little easier for the dataset manager
:param base_root:
:return:
"""
# These are folders we expect within the dataset folder structure. If we hit them,... | d54ab18fb1bc7b49a7bf486b11d020a5d17e3cdb | 66,454 |
def mean_abs_percentage_error(y_true, y_pred):
"""
This function calculates MAPE
:param y_true: list of real numbers, true values
:param y_pred: list of real numbers, predicted values
:return: mean absolute percentage error
"""
# initialize error at 0
error = 0
# loop over all sample... | 7f08e717600e2d1301e951765524b95d3240368d | 66,455 |
def cpuprofile(func):
"""Decorator - profile cpu usage
"""
def wrapper(*args, **kwargs):
if PROFILE:
profiler = Profiler()
profiler.start()
func(*args, **kwargs)
if PROFILE:
profiler.stop()
print(profiler.output_text(unicode=False, colo... | aba4a5703484bbd7e69066336a91df9c8b89492d | 66,456 |
def asdict(inst, recurse=True, filter=None, dict_factory=dict):
"""
Return the ``attrs`` attribute values of *i* as a dict. Optionally recurse
into other ``attrs``-decorated classes.
:param inst: Instance of a ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
... | f79aaaf4cf34fb21521c2d1e35186dfbe63fc67d | 66,457 |
def summult(list1, list2):
"""
Multiplies elements in list1 and list2, element by element, and
returns the sum of all resulting multiplications. Must provide equal
length lists.
Usage: lsummult(list1,list2)
"""
if len(list1) != len(list2):
raise ValueError("Lists not equal length in summult.")
s... | 2b1c4543867998c8edf372c2388df13ce07df910 | 66,458 |
import logging
def insert_into_staging_table(**kwargs):
"""
reads teh temp file and inserts into postgres using
python for better error handling.
"""
# connect to db
connection_id = "postgres_default" # this is the name in airflow variables
dbhook = PostgresHook(postgres_conn_id=connectio... | 162231f1e18c437865dc017e28efbaf480886519 | 66,459 |
def nwchem_psivar_list():
"""Return a dict with keys of most NWChem methods and values of dicts
with the PSI Variables returned by those methods. Used by cbs()
wrapper to avoid unnecessary computations in compound methods.
Result is appended to ``VARH``.
"""
VARH = {}
VARH['nwc-scf'... | a2baf3e98c10363722e162a7d82a86bc57ea397a | 66,460 |
def CRPS_compute(CRPS):
"""Compute the averaged values from the given CRPS object.
Parameters
----------
CRPS : dict
A CRPS object created with CRPS_init.
Returns
-------
out : float
The computed CRPS.
"""
return 1.0*CRPS["CRPS_sum"] / CRPS["n"] | 378dee32c7a9c7a88784438c228f21ae3b6f24f3 | 66,462 |
def cim_to_glm_name(prefix, cim_name):
"""Helper to manage the fact that we need to prefix our object names
to make them match what's in the GridLAB-D model.
Also, if the given name is NOT surrounded by quotes, it will be.
It would appear that all the 'name' attributes in the GridLAB-D
models from ... | aedf44eccff2237b99458a59f2de3b1f2775c80b | 66,463 |
import html
def side_navbar(links):
"""A navigation bar for switching between dashboards."""
return html.Nav(
html.Ul(links, className="moj-side-navigation__list", id="navigation-items"),
className="moj-side-navigation",
role="navigation",
) | 93f6e2036f09b4f4dcfc44cfd3956d3c62eb5e82 | 66,466 |
def tz_syntax(string):
""" returns 'good' and clean reply if reply to adjust the current time zone is fine """
signs = ['+','-']
cond = all(len(s) <= 2 for s in string[1:].replace(',','.').split('.'))
if string[0] in signs and cond == True or string == '0':
return 'good', string.replace(',','.').strip()
else:
... | b727cc1459999410c91adc8dce5683e2fb583db3 | 66,467 |
def GPR_MODEL(Params,Lambda_Inv,Xtrain,Ytrain,alpha_,Xtest):
""" Implementation of a GP mean (mu) predictor
mu = Ktrans \dot alpha_
inputs:
* Params, Lambda_Inv: Trained kernel parameters.
* alpha_: Precomputed product of (Kself+\sigma*I)^{-1} \dot Ytrain.
... | 56a94ab52f4f335e70cf4f952aeacf784c332ce1 | 66,468 |
def dispatch_to_container(containers, current_highlight, key):
"""Dispatch the key to container and handle highlighting.
If the LEFT or RIGHT key is pressed, we switch the highlighting
to the next container.
"""
if key in [KEY_RIGHT]:
next_true = False
UpdateHeuristics.force_unupda... | d4e2782fe190e43bb306ffcd1fd615c020653e37 | 66,469 |
def make_cct_embedded(image_db=None, bbox_db=None):
"""
Takes in path to the COCO Camera Trap format jsons for images (species labels) and/or
bboxes (animal/human/vehicle) labels and embed the class names and annotations into the image entries.
Since IndexedJsonDb() can take either a path or a loaded j... | 53863e200e444b01ee70b697995baadb2a270840 | 66,470 |
def generate_typedef(typedef: Typedef, typenames: TypeNameMap, readlevel: UserLevel, writelevel: UserLevel, ul: UserLevel, use_async: bool) -> str:
"""Generates a Python class for a system model typedef.
Args:
typedef (Typedef): A DeCoP typedef.
typenames (TypeNameMap): A list of type name subs... | 38617088edbdb5dcde0d0f5e0c743b4b4da635c6 | 66,471 |
def parse_html_table(table):
"""
Parse table and filter out rows having child elements ('div') having a class attribute 'pCellBodyR' containing data
"""
trs = table.find_all('tr')
print(len(trs))
my_table = []
for tr in trs:
testRow = etree.HTML(str(tr))
# Catch row containi... | 336676bc0af2542d4777f3d4769a18e76165fd14 | 66,472 |
def cm2inch(*tupl):
"""Converts inches into mm for figures.
"""
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl) | f787126814b60e2215fc92cb78f0bc8d8400c601 | 66,473 |
def form_or_dict_value(context, dict, key_name):
"""Outputs the value of the dict[key_name] unless request.POST contains the data
for the item which then overrides the dictionary's value.
This both fixes problems with normal django templating which will not retrieve
any keys starting with an underscore and it... | 74c6a05e9d12ffdb25ba045dc32de4d0df08a0c5 | 66,475 |
def edge(u :int, v :int, g :Graph) -> tuple:
"""
Retrieve the edge from a vertex u to vertex v.
Args:
u: The source of the edge.
v: The target of the edge.
g: The Graph.
Returns:
(e, True) if it exists a single edge from u to v,
(None, False) otherwise.
"""
... | 48bb2453b039008d4ec7d758af0e047166ca2679 | 66,477 |
def fun_dfun(obj, space, d):
"""
Computes the posterior predictive and posterior predictive gradients of the
provided GPyOpt object.
Parameters
----------
obj: GPyOpt object
The GPyOpt object with a surrogate probabilistic model.
space: GPyOpt space
A GPyOpt object that cont... | 14c39d96dc810d8078ff2dd602fc6216214e8d3f | 66,478 |
from operator import matmul
def get_hidden_at(known_T, known_A, known_B, LAYER, x, prior=True):
"""
Get the hidden value for an input using the known transform and known A.
This function IS NOT CHEATING.
"""
if prior:
which_activation = [y for x in known_T.get_hidden_layers(x) for y in x]
... | aa901c156b457442ae812074e775961f87b62d5c | 66,479 |
def get_bases():
"""Returns an ordered queryset of Airstrips which are bases"""
return Airstrip.objects.filter(is_base=True).order_by('ident') | 89bb8e090b034dfe3291a71d242e3acc8078abd0 | 66,480 |
def fidelity_promo(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0 | 62d8010a59a26a86c190b231568eb5b164380ada | 66,481 |
import scipy
def get_normalized_dispersion(mat_mean, mat_var, nbins=20):
""" Calculates the normalized dispersion. The dispersion is calculated for each feature
and then normalized to see how its dispersion compares to samples that had a
similar mean value.
"""
# See equation in https://a... | e7ad0883d13044e0627e84851a8cfb04a197982e | 66,482 |
def deflection(xyz1, xyz2, xyz3):
"""
Calculate deflection angle(alpha)
"""
v1 = xyz1 - xyz2
v2 = xyz3 - xyz2
alpha = np.arccos(np.dot(v1, v2) / (np.sqrt(v1[0]**2 + v1[1]**2 + v1[2]**2) * (
np.sqrt(v2[0]**2 + v2[1]**2 + v2[2]**2)))) * 180 / np.pi
return alpha | bee601e353529a56a11ebc73a788dc063aade4e7 | 66,483 |
def wave_filter(x, wavelet = 'haar', maxsize = 2**14, minsize = 2**1):
"""
Filter a time series by applying a orthogonal wavelet transform
and removing all scales with more than maxsize coeffs, or less than minsize coeffs
"""
WT = pywt.wavedec(x, wavelet=wavelet)
sizes = [len(x) for x in WT]
... | 446d1031b266db97c20c34565bdfda642b814eac | 66,484 |
def parse_lines(parameters):
"""
Separates the parameters from their tied/fixed/special
characters.
Parameters
----------
parameters : list
A list of rows (each a tuple) containing the line parameters from an
f26 file.
Returns
-------
lines : `astropy.table.Table`
... | 26046c9e732640ebc687f42440cf2b28869e68c0 | 66,485 |
def sliver_overall_score_for_one_couple(score):
"""
Computes overall score:
"""
score_list = list(score.values())
overall_score = np.average(np.array(score_list))
return overall_score | e64b10c8180e21ab718b52c4fd1dc60144e504b2 | 66,486 |
def partition_opm_license_list(df):
"""This function partitions the OPM Granted Licenses list by license type, storing the result in a Python dictionary.
Parameters
----------
df (DataFrame): OPM Granted Licenses list
Returns
-------
license_list_dict (dict): OPM Granted Licenses list part... | 4f9bab49385e23732e5e56e3f0dbf8762eb05438 | 66,487 |
import json
async def processing_request(web, request, token, post=False):
"""Функция "processing_request" - обрабатывает текущий запрос на Веб-сервер от клиента."""
route_path = request.path
headers = request.headers
query_args = request.rel_url.query
if route_path is not None or route_path != '... | 061463aae84add2c52561ef4ab2eb38a050b15ed | 66,489 |
def ShowTaskIPC(cmd_args=None):
""" Routine to print IPC summary of given task
Usage: showtaskipc <address of task>
"""
if not cmd_args:
print "No arguments passed"
print ShowTaskIPC.__doc__
return False
tval = kern.GetValueFromAddress(cmd_args[0], 'task *')
if not ... | c3eaf43c5f0184231465df6efc188fb49bbdeda7 | 66,490 |
def retrive_var(scopes):
"""
Retrieves variables from different scopes in the graph
:param scopes: the scopes to search in
:return: list of variables
"""
var = []
for scope in scopes:
var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,
scope=sc... | dc7a209e81598e1869ce9862342f68b99562c9eb | 66,491 |
def intToIp(ip, version):
"""Transform an integer string into an IP address."""
# just to be sure and hoping for Python 2.2
ip = int(ip)
if ip < 0:
raise ValueError("IPs can't be negative: %d" % (ip))
ret = ""
if version == 4:
if ip > MAX_IPV4_ADDRESS:
raise ValueE... | e5709eae93546b18630582caa8a056555867817b | 66,492 |
from typing import Tuple
def _find_model_temperature_range(model_type: str) -> Tuple[float, float]:
"""Returns temperature range around 0C for given model type."""
if "gdas1" in model_type.lower():
return -8, 6
return -4, 3 | bebfc0b440b2c13640047dc1ecb8b94d765f63f9 | 66,493 |
import requests
def vagrantup_check(os_name: str, version: str) -> bool:
"""
Checks whether an OS is on version :version on the vagrantup box.
Returns:
(bool): is OS updated?
"""
# Fetch url & parse HTML
r = requests.get(VAGRANTUP_BOX_URL)
document = lxml.html.fromstring(r.text)
... | 7802fbcc614da4539558f6c47178fb0e075613d9 | 66,494 |
import sqlite3
def get_data_from_db():
"""Returns a list of article strings and their
corresponding labels as two arrays.
Connects to the article sqlite db, who's path
is specified at the top of the program with
ARTICLE_TEXT_DB_PATH.
Labels are the "right-score" of the article.
... | eab20135ebddf22e349ba15d601fe220f03ea6c2 | 66,495 |
def getClampDeviceNames(protoDH):
"""
get the Clamp devices used in the current protocol
:param protoDH: handle to current protocol
:return clampDeviceNames: The names of the clamp devices used in this protocol, or None if no devices
"""
if protoDH.name()[-8:] == 'DS_Store': ## OS X filesystem ... | 0df7ffbebe7262eba7c9d8396015a2e396ebe304 | 66,496 |
def _get_event_result(query):
"""
Perform the get_event query and return the serialized results. This is
its own function to enable caching to work.
Returns: (string, found)
"""
db = get_db()
event = db['events'].find_one(
query,
{'_id': 0, 'coordinates': 0, 'categorymainsub'... | a362ed569995f26b451fd0ebc1a1a4c975acb396 | 66,497 |
def logs():
"""
Copy over logs
"""
stack_uuid = request.args['uuid']
to_dir = request.args['dir']
return docker.copy_logs(stack_uuid, to_dir) | a08fb83b0f2cbcfa2cc8ab0fd88a3e5b0186e477 | 66,498 |
def image_distortion_loss(y, y_hat):
""" MSE (per image pair) """
return tf.reduce_mean(tf.math.pow(y - y_hat, 2), axis=[1, 2, 3]) | 56ae39c7a5beb1ba3b65cfdd58269bb03e8e40b5 | 66,499 |
from typing import Union
def calculate_annual_interest_rate(base_salary: Union[int, float], rpi: float, max_interest_cap: float = None) -> float:
"""
Calculates the annual interest rate based on the RPI and salary earned.
The interest rate charged is normally the Retail Price Index plus up to 3%, dependin... | ef805e69bbbe1838ae89cdf976907636e63d9548 | 66,500 |
def get_upload_commands(system, release, package):
"""Returns the required package_cloud commands to upload this package"""
repos = ["datawireio/stable", "datawireio/telepresence"]
res = []
for repo in repos:
res.append(
"package_cloud push {}/{}/{} {}".format(
repo, ... | db3fccb3302657367be121f4bb64affcd4879180 | 66,501 |
def vanity_about(request):
"""
The /about view, displays marketing mumbo jumbo.
"""
# # Redir https
# if request.headers.get('X-Forwarded-Proto') is not None:
# if request.headers['X-Forwarded-Proto'] != 'https':
# return HTTPMovedPermanently(location="https://%s%s" % (
# ... | 0969e6b3cc73bac994a434bb053152d04a2ea1bd | 66,502 |
def organisation_update_profile(request,organisation_id, *args, **kwargs):
"""
:param request:
:param organisation_id:
:return:
"""
return HttpResponse('') | ef2d5d635b89b7700be6f585244722a27785dec2 | 66,503 |
def get_attached_policy(client, policy_arn):
""" Get the policy document of an attached policy. """
try:
policy = client.get_policy(
PolicyArn=policy_arn
)['Policy']
version = policy['DefaultVersionId']
can_get = True
except Exception as error:
print('Get ... | 9a3f6e3a24727e203acc06b0b7022f695989c886 | 66,504 |
def adsr(x, t, a, d, s_val, r):
"""
x input vector
t signal total len
a attack duration
d decay duration
s_val sustain level
r release duration
"""
m0 = 1 / a
b0 = 0
m1 = (s_val - 1) / d
b1 = 1 - a * m1
s = t - r
m2 = s_val / (s - t)
b2 = -t * m2
y = []
... | c7861f2c97bcb1c6d65f7974afab4da7986b3cc3 | 66,506 |
def GetClosenessCentr(*args):
"""
GetClosenessCentr(PUNGraph const & Graph, int const & NId) -> double
Parameters:
Graph: PUNGraph const &
NId: int const &
"""
return _snap.GetClosenessCentr(*args) | f4e10abc66ae53f432dd936253692ea3dc17b680 | 66,507 |
def fix_whitespace_for_phantom(text: str):
"""Transform output for proper display
This is important to display pandas DataFrames, for instance
"""
text = text.replace(' ', r' ')
text = '<br>'.join(text.splitlines())
return text | 7a0e3cddd778263977da74096f7bd30f44a0ce45 | 66,508 |
def draw_shell(G, **kwargs):
"""Draw networkx graph with shell layout.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See hvplot.networkx.draw() for a description of optional
keywords, with the exception of the pos parameter which is not
used... | b6777476d642fd07b13c52310e3209319f878da2 | 66,509 |
def iou_detection(box1, box2):
"""Computational object detection iou.
Args:
box1: [xmin1, ymin1, xmax1, ymax1]
box2: [xmin2, ymin2, xmax2, ymax2]
return:
object detection iou values.
"""
xmin1, ymin1, xmax1, ymax1 = box1
xmin2, ymin2, xmax2, ymax2 = box2
s1 = (xm... | efaf6d2bef0b6de40c4f05cad15ebfb5810ebc80 | 66,510 |
def normalize_assignments(assignments):
"""Convert a clustering state <assignments> so that all essentially equal states can be
same array. Return value type is Tuple so that it can be hashed as a dict key.
"""
convert_table = {}
new_id = 0
for cluster_id in assignments:
if cluster_id no... | 1574a62db1ca65c1051bfac6fce9b30918892404 | 66,511 |
def get_temperature_reading_as_json(temperature_reading):
""" returns a single temp reading as a json object """
result = '{\n "probe_id" : "' + temperature_reading.probe_id + '",\n "temperature_C" : "' + str(temperature_reading.temperature_C) + '",\n "temperature_F" : "' + str(temperature_reading.temper... | 4836532602e4b0c704c6eab439ac873d8e53c237 | 66,512 |
def get_source_type():
"""
Выдает все типы источников, с которым может работать AnchorBase
"""
try:
l_available_source_type=C_AVAILABLE_SOURCE_LIST
l_source_type_str="" # все типы источников в строку
for i_source_type in l_available_source_type:
l_source_type_str+=i_s... | b53e5824567562dbbf21a7ef9f0d62e5d443d3e6 | 66,514 |
def assign_allometric_eq(ds):
"""
Given a dataset with ecoregion values (Ecoregions2017, NLCD, EOSD, IGBP), f_slope, and senergy, assign the correct allometric equation
"""
# calculate f_slope and senergy if not in dataset
for v in ['f_slope', 'senergy']:
if v not in ds:
ds[v] = ... | 4d8dc387122ae582aaaa779d7a94431e9afe57b4 | 66,515 |
def get_aurocs(X, y, pipeline):
"""
Fit the classifier for the given mutation (y) and output predictions for it
"""
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0)
pipeline.fit(X=X_train, y=y_train)
y_pred_train = pipeline.decision_function(X_train)
y... | 5434706d7ae47e04497376c2b95969e83ef80c75 | 66,516 |
def heugcd(f, g):
"""
Heuristic polynomial GCD in ``Z[X]``.
Given univariate polynomials ``f`` and ``g`` in ``Z[X]``, returns
their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg``
such that::
h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h)
The algorithm is purely h... | d82596709b15ae1ac501e0b1723a2fed4671dabc | 66,517 |
import json
def load_json_file(path_conf):
""" Loads a json file specified in the path """
with open(path_conf, "r", encoding="utf-8") as file_conf:
conf_physic = json.load(file_conf)
return conf_physic | 5eaa7a8a35c428a36bd6dc5608fc836a4a096253 | 66,518 |
import math
def step_decay(epoch: int):
"""
Learning rate scheduler.
Parameters
-----------
epoch: int
Number of epochs to perform
Returns
--------
float
Learning rate
"""
initial_lrate = 1e-3
drop = 0.5
epochs_drop = 50.0
lrate = initial_lrate * m... | 80af442b6ce0c7b454969896b7ac41efdf63eaf6 | 66,519 |
def api_call(url, **params):
"""Return response from API."""
data = get_url(url, **params).json()
remaining = data.get('quota_remaining') or 0
total = data.get('quota_max') or 0
if total and remaining:
log.info(u'%d/%d API requests remaining', remaining, total)
return data | 138800d21c9ec383be8545b2707c561d50e8f959 | 66,520 |
def baseCodeToJournalName(baseCode):
"""
Return the jrnl name for a baseCode
>>> print baseCodeToJournalName("ANIJP-IT.2006")
Annata Psicoanalitica Internazionale
>>> print baseCodeToJournalName("anijp-fr.2006")
Annee Psychanalytique Internationale
"""
base = baseOfBaseCode(baseCode)
... | a6511347f02d2245161a97b22326d3c93735dc9e | 66,521 |
def get_camera_parameters_intrinsic(scene):
""" Get intrinsic camera parameters: focal length and principal point. """
# ref: https://blender.stackexchange.com/questions/38009/3x4-camera-matrix-from-blender-camera/120063#120063
focal_length = scene.camera.data.lens # [mm]
res_x, res_y = get_scene_resolu... | 7db8f146bb36e3b209c8db56e8fa5a74c00a9344 | 66,522 |
def snr(spectrum, region=None):
"""
Calculate the mean S/N of the spectrum based on the flux and uncertainty
in the spectrum. This will be calculated over the regions, if they
are specified.
Parameters
----------
spectrum : `~specutils.spectra.spectrum1d.Spectrum1D`
The spectrum obj... | 9e29d6b2e5d6d3614ff10b2e8c3f24b4bc19c944 | 66,523 |
def input(_input, **options) -> Input:
"""Input options (ffmpeg pre_option ``-i`` input options)
You can also pass a cloud object as an input to the method. the file will be downloaded and will pass it to ffmpeg
if you want to open a resource from a pipe, set input "pipe:"
if you want to ope... | 229fa7f44488c9b54c17753b323bfdcff1407c53 | 66,524 |
import posixpath
def normalize_api_path(api_path):
"""Resolve paths with '..' to normalized paths, raising an error if the
final result is outside root."""
normalized = posixpath.normpath(api_path.strip('/'))
if normalized == '.':
normalized = ''
elif normalized.startswith('..'):
r... | b40f617631cbff27d6cc2bc8b42552cb0fc33cbc | 66,525 |
def define_plane_from_points(xyz1, xyz2, xyz3):
"""
Compute constants defining a plane from a set of points.
The equation defining a plane has the form ax+by+cz+d=0.
This utility returns the constants a, b, c and d.
Parameters
----------
xyz1 : numpy.ndarray
First point needed to d... | e3ed313882793b6483247ee94f4ab5dae1d9a2b7 | 66,526 |
def _internal_is_knet_ascii(buf):
"""
Checks if the file is a valid K-NET/KiK-net ASCII file.
:param buf: File to read.
:type buf: Open file or open file like object.
"""
first_string = buf.read(11).decode()
# File has less than 11 characters
if len(first_string) != 11:
return F... | 9ca251ef9c5eab64a97f69e1acd8b6aa746ea09b | 66,527 |
def _plot_1d(data, ax=None, **plt_kwargs):
"""Plot one dimensional functional data.
This function is used to plot an instance of functional data in 1D.
Parameters
----------
data: UnivariateFunctionalData or IrregularFunctionalData
The object to plot.
ax: matplotlib.axes._subplots.Axes... | f1a26ef962101758364f66f6acc7e79a39b06e69 | 66,528 |
def getAvgFeatureVecs(texts, keywords, stopwords, model, modelword_index, num_features):
"""
Obtains the vector representation for every word and takes the average over all tokens for every text
Returns a vector of average feature vectors for all texts
"""
counter = 0
# Initialise numpy vector ... | 4c3bc0787b47e9cac0f8318eac3120108492cdf2 | 66,529 |
def load_data(index: bool = False) -> pd.DataFrame:
"""
Function for loading and cleaning data in a usable format
Parameters:
-----------
index: boolean indicating whether to load data with a specified index column
Returns:
--------
A pandas DataFrame object containing cleaned data
... | 6725116d1e817f78e201e918671799d08bb28d12 | 66,530 |
def poly_real_part(poly):
"""Deprecated."""
return np.poly1d(poly.coeffs.real) | 26cb705b1da626d5342cafcf403346ba3f0bd24f | 66,531 |
import torch
from typing import List
from typing import Tuple
from typing import Callable
def graph_pit_loss(
estimate: torch.Tensor,
targets: List[torch.Tensor],
segment_boundaries: List[Tuple[int, int]],
loss_fn: Callable,
) -> torch.Tensor:
"""
Graph-PIT loss function.
... | c14a720c822554c1244cc323565557214b710b91 | 66,532 |
def encode_sentences(sentences, vocab=None, invalid_label=-1, invalid_key='\n', start_label=0):
"""Encode sentences and (optionally) build a mapping
from string tokens to integer indices. Unknown keys
will be added to vocabulary.
Parameters
----------
sentences : list of list of str
A l... | 2ee84f5f64ce383d025769a36515d33df41fad33 | 66,533 |
def make_affine_matrix(bbox, target_size, margin=1.2, aug_rotation= 0, aug_scale=1):
"""
transform bbox ROI to adapat the net-input size
`margin`: determine the distance between the bbox and input border . default: 1.2
`aug_rotation`: the rotation angle of augmentation, range from [0,180]. default: 0
... | 9be54cf4149d922c49afa2be27a8eceb030647c7 | 66,534 |
def flatten(lst):
"""Flat list out of list of lists."""
return [item for sublist in lst for item in sublist] | 3849afc94fdab885dbc6eea1960dba0294e03483 | 66,535 |
import posix
def _PopDirStack(mem, dir_stack, errfmt):
# type: (Mem, DirStack, ErrorFormatter) -> bool
"""Helper for popd and cd { ... }."""
dest_dir = dir_stack.Pop()
if dest_dir is None:
errfmt.Print('popd: directory stack is empty')
return False
try:
posix.chdir(dest_dir)
except OSError as... | 51496073a1aae766d09ae53f9d8b0af4fa7c295b | 66,537 |
async def get_fsc_revocation_job(request_id: UUID):
"""
Route for retrieving job status from an fsc revocation from the queue.
:param request_id: the id of the job.
"""
freischaltcode_service: FreischaltCodeService = get_service(RequestType.freischalt_code_revocate)
return freischaltcode_service... | d609665d7a831b80577a7a9db2f388999ffa92a7 | 66,538 |
from typing import Dict
from typing import List
def white_code_words(language_id: str) -> Dict[str, List[str]]:
"""
Words that do not count as code if it is the only word in a line.
"""
assert language_id is not None
assert language_id.islower()
return _LANGUAGE_TO_WHITE_WORDS_MAP.get(language... | acc0811ffb3a7e5947869affae98d01f90fc6edd | 66,539 |
def bits2octets(bits, rolen):
"""
Converts bits into octects modulo Curve.N, padded with zeros. Overflow is
discarded.
https://tools.ietf.org/html/rfc6979#section-2.3.4
Args:
bits (ByteArray): Bytes to convert.
rolen (int): Number of digits to allow.
Returns:
ByteArray... | 337422576f095104d4ebec54983f1c359318bfa5 | 66,540 |
def get_unique_names(to_lower=True):
"""
Get all product names.
Returns: list
"""
docs = products_ref().get()
unique_names = [
doc.to_dict()['producer'] + "_" + doc.to_dict()['product']
for doc in docs
if 'producer' in doc.to_dict() and 'product' in doc.to_dict()
]
... | c1fa49a42f67c62f1451063419c9bbb538e36309 | 66,541 |
def gae_advantages(rewards: jnp.ndarray, terminal_masks: jnp.ndarray,
values: jnp.ndarray, discount: float, gae_param: float):
"""Use Generalized Advantage Estimation (GAE) to compute advantages.
Args:
rewards: array shaped (actor_steps, num_agents)
terminal_masks: array shaped (actor_st... | 09d708c8b5e51452db585018db178d93980e9858 | 66,542 |
def list_opts():
"""Return a list of oslo.config options available.
The purpose of this is to allow tools like the Oslo sample config file
generator to discover the options exposed to users.
"""
opt_list = [
(service_available_group, ServiceAvailableGroup),
(sdn_group, SDNGroup),
... | 1ace405b375d26f6b374b9392030d69d0c8872e1 | 66,543 |
def GetBlueprintTargetForGit(messages, git_target, git_target_subdir='.'):
"""Returns the GitTarget representation of a blueprint git target.
Args:
messages: ModuleType, the messages module that lets us form blueprints API
messages based on our protos.
git_target: string, a Git repo path.
git_tar... | b5b7dc9ac3a9816482ecbfa05cebc59f83f60e8b | 66,544 |
def getInviteAcceptedRedirect(entity, _):
"""Returns the redirect for accepting an invite.
"""
return '/%s/accept_invite/%s/%s' % (
entity.role, entity.scope_path, entity.link_id) | 39affb109481cb96bb4ca992911e6a6a1957962a | 66,546 |
def z_request_dict(df: gpd.geodataframe.GeoDataFrame) -> dict:
""" DF -> dictionary conversion
:param df: dataframe to be used
:return: converted dictionary
"""
df.reset_index(inplace=True) # resetting index
dict_from_df = df.to_dict('index')
return dict_from_df | d4b2c25fadc483c54733a046b2c1b22cc2d9f542 | 66,547 |
import logging
import time
def google_http_error_retry(tries=4, delay=3, backoff=2, logger=logging):
"""
Retry calling the decorated function using an exponential backoff.
It retries HttpErrors with status code > 400(except 404).
Errors with another status code are reraised
:param tries: number o... | 16c7b33b2cb5409f25400ae54defb95d323a8227 | 66,548 |
def format_month(month):
"""Formats a month to first 3 characters of the month input
Args:
month: user input month
Returns:
A ValueError if the input is not a month, or a 3 character month.
"""
months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov... | da7ffd8bc801377ecebcc76e972219633ae21566 | 66,549 |
def compute_fingerprint(molecule, fingerprint: str, nbits: int, use_chirality: bool) -> np.ndarray:
"""Calculate a single fingerprint.
Parameters
----------
molecule
RDKit molecule
fingerprint
Name of the fingerprint to apply
bits
Number of bits to use
use_chirality
... | b13c5ed9cf7d51dd0fb6c6906955b623df42f133 | 66,550 |
from dms.utils_form import get_base_vars
from dms.utils import get_site_actions
from django.shortcuts import render_to_response
def do_manage(request, item_container, user_perms, add_ons, app_name,
my_title, my_title_own, dont={}, allow_copy=True):
""" Pflegemodus der Ressou... | eb052e660531673e4771cd2feb94cd3cebab30ae | 66,551 |
async def portfolios(_request: Request, user: User) -> response.HTTPResponse:
"""
User's list of portfolios
"""
return response.json({"email": user.email}) | e9a91017c22163aae7184784e42eaabd3ea7bbc4 | 66,553 |
def LongestIncreasingSubsequence(S):
"""
Find and return longest increasing subsequence of S.
If multiple increasing subsequences exist, the one that ends
with the smallest value is preferred, and if multiple
occurrences of that value can end the sequence, then the
earliest occurrence is preferr... | 0d3755abee33ccbb110ee7dc0e6552a19770bfdd | 66,554 |
def get_data(fn, split=False, split_char=None, filter_blanks=False):
"""
:param fn: filename to open
:param split: if you want to split the data read
:param split_char: character you want to split the data on
:param filter_blanks: remove empty strings if split=True
Example:
>>>data = get_dat... | 6ff198281d41f96fb48c45c51525245cffe8e7ec | 66,556 |
def add_cors(resp):
""" Ensure all responses have the CORS headers. This ensures any failures are also accessible
by the client. """
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Credentials'] = 'true'
resp.headers['Access-Control-Allow-Methods'] = 'POST, O... | 0e8044bcdbbfebad19b41b1323ba0935e178999c | 66,557 |
def FilterLabels(labels):
"""Filter label strings in label list.
Filter labels (list of strings) with the following conditions,
1. If 'label' has 'key' and 'value' OR 'key' only, then add the label to
filtered label list. (e.g. 'label_key=label_value', 'label_key')
2. If 'label' has an equal sign but no 'val... | 9ab4c5211d0f668c2bf83e359c27e0f7996964e8 | 66,558 |
def route_urgent_task(name, args, kwargs, options, task=None, **kw):
"""Allow routing urgent tasks to a special queue, according to URGENT_TASK_QUEUES
e.g. task.apply_async(args, kwargs, urgent=True)
"""
if name in URGENT_TASK_QUEUES and kwargs.get('urgent'):
return {'queue': URGENT_TASK_QUEUES... | 79de2cdda22378c34826f6f72f10486804fc6022 | 66,560 |
import glob
def points_to_crowns(
field_data,
rgb_dir,
savedir,
raw_box_savedir,
client=None):
"""Prepare NEON field data int
Args:
field_data: shp file with location and class of each field collected point
rgb_dir: glob to search RGB images
savedir: direcory to sa... | 6e45481b3185fee7121f0b05441edaa14a3498d5 | 66,561 |
def get_all_data(path):
"""
Gets all the reviewText and Overall Sentiment from the json file
"""
dict = {}
generator = parse(path)
i = 0
for line in generator:
dict[i] = line
i+=1
data = {"reviewText": [], "overall": []}
for d in dict:
data["reviewText"].appe... | e24c0275ad248ea9ced0be04e5c8b6392ae3f6c7 | 66,562 |
def configuration_for(key):
"""Retrieve the configuration value for a specified key"""
try:
return Configuration.query.filter_by(key=key).first()
except:
return None | ab0d4101d7d0386569f1646a78c46b7150494363 | 66,563 |
def maybe_add(d, exclude_false=False, **kws):
"""
Adds keywork argumnts to a dict if their values are not None.
Parameters
----------
d: dict
The dictionary to add to.
exclude_false: bool
Exclue keys whose values are false.
kws: dict
The keys to maybe add
"""
... | bc7bc09261f37fe052d30d6b0c2452937f33c563 | 66,564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.