content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import asyncio
def create_future(*, loop):
""" Helper for `create a new future`_ with backward compatibility for Python 3.4
.. _create a new future: https://goo.gl/YrzGQ6
"""
try:
return loop.create_future()
except AttributeError:
return asyncio.Future(loop=loop) | 1708ac124c46fa81b7ff3ca1d7b685e4835cd53a | 3,630,579 |
def log_sum_exp(mat, axis=0):
"""
Computes the log-sum-exp of a matrix with a numerically stable scheme,
in the user-defined summation dimension: exp is never applied
to a number >= 0, and in each summation row, there is at least
one "exp(0)" to stabilize the sum.
For instance, if dim = 1 and m... | a72536b03e58eede19e6d18846b44fb1454891cb | 3,630,580 |
def msd(n_x, yr, min_support):
"""Compute the Mean Squared Difference similarity between all pairs of
users (or items).
Only **common** users (or items) are taken into account. The Mean Squared
Difference is defined as:
.. math ::
\\text{msd}(u, v) = \\frac{1}{|I_{uv}|} \cdot
\\sum... | 867989ef28cbce2e4235cb2704ab39cab0eae5f3 | 3,630,581 |
def wrap_deepmind(env,
episode_life=True,
resize=True,
grayscale=True,
width=84,
height=84,
scale=False,
clip_rewards=True,
frame_stack=True,
stack=4):
""... | 83229995b9be22721e386e8162dde49516d4c0b5 | 3,630,583 |
def annotate_intersection(sv, elements, filetype='gtf'):
"""
Parameters
----------
sv : pbt.BedTool
SV breakpoints and CNV intervals
gencode : pbt.BedTool
Gencode annotations
"""
# Number of fields in SV bedtool
N_BED_FIELDS = 6
# Check intersection with gene bounda... | 4a4b395438c3d1f2c8e1c7fdaccbd3acadbfc6d3 | 3,630,584 |
def analyzeGHP(ghp):
"""Analyze this libLF.GitHubProject
Returns:
(testsPassed, libLF.RegexUsage[])
"""
dynoRegexFileName = getRegexOutputFileName()
libLF.log("{}/{} will use dyno regex file {}".format(ghp.owner, ghp.name, dynoRegexFileName))
libLF.log("Untarring")
untarDir = unpackTarball(ghp)
... | acc0303706ae87f9be643adb9512e32a16b1cfb3 | 3,630,585 |
import re
def convert(name):
"""
Converts camelCase strings to snake_case ones.
:param name
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | 6a2177023e2f4cdc495aa0525790aeb40ea9d8b8 | 3,630,586 |
def normalize_inputs(py_dict: dict) -> dict:
"""Normalize a dictionary of inputs to contiguous numpy arrays."""
return {k: (Tensor(v) if isinstance(v, np.ndarray) else v)
for k, v in py_dict.items()} | e82d877f98478b2483dca2d6ca8026dba5d87e10 | 3,630,587 |
def get_task_definition_arns():
"""List all task definition ARNs."""
client = get_client("ecs")
return client.list_task_definitions() | 77b016f0f6911870a5f48edcd57fa90e596e1e8b | 3,630,588 |
def clean_column(df, column):
"""
Function to return clean column text. Pass each cell to a cleaner
and return the cleaned text for that specific column
:params:
--------
:df dataframe(): containing the column
:column str(): in which column the text is located
:returns:
---... | 095a854c452f87b9a960eabb81ace5c18814f266 | 3,630,589 |
from typing import Optional
from typing import Iterable
def augment_cost_function(
cost_function: CostFunction,
cost_function_augmentations: Optional[Iterable[FunctionAugmentation]] = None,
gradient_augmentations: Optional[Iterable[FunctionAugmentation]] = None,
):
"""Augment a function and its gradie... | 3cf0e1e51d63ccff75f7438ae052a2832fd9b9e3 | 3,630,591 |
def edit_name(request, name, editable_authorities):
"""View to edit an existing Name object."""
# Much of the code here is a duplicate or close copy of the code
# in create_name.
number_name_part_forms = 2
number_name_note_forms = 1
name_part_forms = []
name_note_forms = []
assertion = n... | 075d6004f2415beaa5e09b529b9df6a0e77b7f89 | 3,630,592 |
import math
def create_convolutional_autoencoder_model_2d(input_image_size,
number_of_filters_per_layer=(32, 64, 128, 10),
convolution_kernel_size=(5, 5),
deconvolution_kernel_size... | 8bc7ad876f67591a81fb14299d6beb09c4e0cf65 | 3,630,593 |
def to_volume(data):
"""Ensure that data is a numpy 3D array."""
assert isinstance(data, np.ndarray)
if data.ndim == 2:
data = data[np.newaxis,...]
elif data.ndim == 3:
pass
elif data.ndim == 4:
assert data.shape[0]==1
data = np.squeeze(data, axis=0)
else:
... | d816dc16a1bdd27437d8c907c2dd8b18902edd80 | 3,630,595 |
def search_down(*args):
"""
search_down(sflag) -> bool
Is the 'SEARCH_DOWN' bit set?
@param sflag (C++: int)
"""
return _ida_search.search_down(*args) | c931b2152e8d5cf803aea9b1228fbd38dc8acc20 | 3,630,596 |
def assign_number_to_top_categories(paths):
"""Assign numbers to the top categories
returned by split_path for consistency"""
cats = {}
def assign_number(path):
name = path[0][1]
n = cats.setdefault(name, len(cats) + 1)
return [(n, name)] + path[1:]
return map(assign_number,... | 0027986bd9097819b76ef9358f3fb0b491456b48 | 3,630,597 |
def instrument_parameters_odim5(radar, odim_file):
"""
Builds the dictionary 'instrument_parameters' in the radar instance,
using the parameter metadata in the input odim5 file.
Parameters
----------
radar : Radar
Py-ART radar structure
odim_file : str
Complete path and fil... | 185838c40a8d8f41dd16dcd92bdb9082396a772f | 3,630,598 |
def topodstostep_DecodeVertexError(*args):
"""
* Returns a new shape without undirect surfaces.
:param E:
:type E: TopoDSToStep_MakeVertexError
:rtype: Handle_TCollection_HAsciiString
"""
return _TopoDSToStep.topodstostep_DecodeVertexError(*args) | 6604b4f834d07ccb5ded4ebd8c573301e72b21ea | 3,630,599 |
def sort_keywords(scores):
"""
:param scores: A dictionary of lemmas and their corresponding scores,
assigned by the pagerank algorithm
:return: The same dictionary, sorted in descending order
"""
sorted_lemmas = [lemma for lemma in sorted(scores, key=scores.get, reverse=True)]
return sorte... | ef4349976e755fb5d0d95b0ee98c5184fbf055f2 | 3,630,600 |
def DecodeControlTuples(ldapControlTuples,knownLDAPControls=None):
"""
Returns list of readily decoded ResponseControl objects
ldapControlTuples
Sequence-type of 3-tuples returned by _ldap.result4() containing
the encoded ASN.1 control values of response controls.
knownLDAPControls
Dictionary... | d792ba07134b07d16881623123589709099a9a0c | 3,630,601 |
def transform_geom(
src_crs,
dst_crs,
geom,
antimeridian_cutting=True,
antimeridian_offset=10.0,
precision=-1):
"""Transform geometry from source coordinate reference system into target.
Parameters
------------
src_crs: CRS or dict
Source coordina... | 918d1018b9fcc591fa7c4761c0bfe4f3a394dddc | 3,630,602 |
def part_one(data: str) -> int:
"""The best possible cookie score given the ingredient properties from data."""
total_quantity = 100
ingredients = [parse_ingredient(line) for line in data.splitlines()]
# There are 4 ingredients total in the input, so nothing is lost here.
quantities = [total_quantit... | 3958414bffa0836c909c746cbbfa7ef9b01b35cc | 3,630,603 |
import unittest
def skip_if_quick(func):
"""Decorator to skip tests if quick option is used."""
@wraps(func)
def wrapper(*args):
# C0111: *Missing docstring*
# pylint: disable=C0111
# W0212: *Access to a protected member %%s of a client class*
# pylint: disable=W0212
... | 6b3bb6073b076e79d9795cf26b454783d7fcfcaf | 3,630,604 |
def _build_edges(wave, sampling_type):
"""
Calculates edges of bins of given wavelength given the center value of the
bin and the type of sampling.
Parameters
----------
wave : numpy.ndarray
Array with the wavelengths.
sampling_type : string
Sampling type of the array. It ca... | 16c92dec058e895fa0be6cc2738ada23ba198099 | 3,630,605 |
def file_readlines(fn):
"""Open file with name `fn`, return open(fn).readlines()."""
fd = open(fn, 'r')
lst = fd.readlines()
fd.close()
return lst | 2594e6763b566f4e83844f2f4457bcc8ea3663a5 | 3,630,606 |
import re
def filter_table(table, **kwargs):
"""Retrieve the filtered rows
Parameters
----------
table: astropy.table.Table, pandas.DataFrame
The table to filter
param: str
The parameter to filter by, e.g. 'Teff'
value: str, float, int, sequence
The criteria to filter ... | 50629e02c5e9ab6c17fcde1211b2a0a2c74570ca | 3,630,607 |
def get_cached_skin_path():
"""
Get the value of the #SKINSPATH# variable.
This can be collected from various installation locations,
since there are numerous ways to install Rainmeter.
The easiest solution is, if the user tells Sublime Rainmeter,
that he installed Rainmeter in a specific fold... | 403e83a785620bb7291a89524646db75711f74fa | 3,630,608 |
from typing import Callable
import functools
import inspect
from typing import Hashable
def func_dispatch(func: Callable = None, *, default: bool, clazz=None):
"""
Value-based dynamic-dispatch function decorator.
Transforms a function into a dynamic dispatch function, which has different
behaviors de... | af2dd4d389a26ba887cf4a34115a744fcff25534 | 3,630,609 |
import functools
def access_controlled_app(app):
"""
An app where all the routes are access-controlled to the 'buyer' role, and there are some login routes if we need.
"""
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
... | 638658711e02cc5d7fc51221a27a87099a264d38 | 3,630,610 |
def get_local_content_list(filename, encoding):
"""Return the file content with status"""
textl = []
stat = False
try:
with open(filename, 'r', encoding=encoding) as f:
textl = ''.join([f.read(), '\n']).splitlines()
stat = True
except Exception as e:
log.excep... | c4171befc0b6107739d216b6854531956c2e2ac6 | 3,630,611 |
def check_pods_status(run_name: str, namespace: str, status: PodStatus, app_name: NAUTAAppNames = None) -> bool:
"""
Returns true if all pods related to a given run have given status.
:param run_name: name of a run - obligatory
:param namespace: namespace where run is located - obligatory
:param sta... | 6c8eed3a769976b4c8095bc93328c5ecc759778d | 3,630,612 |
def retrieve_account(community, platform_type, platform_identifier, blah, community_platform_id=None):
"""Helper method to get a specific linked account."""
result = LinkedAccount.objects.filter(community=community, platform_type=platform_type,
platform_identifier=platform_identifier)
if community_p... | 99ffa075668e374b84bd498008f16a79f1d294c4 | 3,630,613 |
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):
"""
Reconstruct a state from unconstrained least-squares fitting.
Args:
tomo_data (list[dict]): state or process tomography data.
weights (list or array or None): weights to use for least squares
fitting. The def... | cc15c7e440ccf10f5e90c6daa27e6fb31a8f59c6 | 3,630,615 |
import http
async def testpoint(mockserver: server.MockserverFixture) -> TestpointFixture:
"""Testpoint fixture returns testpoint session instance that works
as decorator that registers testpoint handler. Original function is
wrapped with :ref:`AsyncCallQueue`
:param name: testpoint name
:returns... | f9168902b4eb6074786062aba2a58e9cd083e4f8 | 3,630,616 |
def cfg(c=[], all=None):
"""returns parsed config for section <endpoint> - if not exists, builds it
When interactive auth is requred we do not write - i.e. only valid for cur.
session.
To avoid frequent password queries, call GL.setup function.
"""
try:
return c[0][FLG.endpoint_name]
... | 6886df8163cce6b8df37e69e181d19e443770a53 | 3,630,617 |
from datetime import datetime
def JIRATOSQLdatetimeformat(datetime_in):
"""
removes certain characters from fields returned by Jira requests, in order to facilitate insertion into SQL tables
would need to be written differently for a production application, to handle escape characters etc. more intelligently
par... | d75df0f925e4a3ed104ca98f8ef4ea0ae1d0557b | 3,630,618 |
def _split_and_reshape_to_ndarrays(flat_v, sizes, shapes):
"""Split and reshape a single flat vector to make a list of ndarrays."""
xp = chainer.cuda.get_array_module(flat_v)
sections = np.cumsum(sizes)
vs = xp.split(flat_v, sections)
return [v.reshape(shape) for v, shape in zip(vs, shapes)] | f388260cc9da0b2b8836248f109b12670e4aed57 | 3,630,619 |
import json
def apply_lookup(dataframe, group_type):
"""
converts df[group_type] from ids to names
dataframe : df
group_type : string
returns : df
"""
print("applying look up")
print("working with {}".format(group_type))
df = dataframe.copy(deep=True)
df[group_type] = (
... | a41749555f106b4477414cc837f1c0cd56128acc | 3,630,621 |
def make_url_parser(global_conf, directory, base_python_name,
index_names=None, hide_extensions=None,
ignore_extensions=None,
**constructor_conf):
"""
Create a URLParser application that looks in ``directory``, which
should be the directory for the... | 2865a0adcdac1dd7879a9bf286ca91140c88945e | 3,630,622 |
def add_memo():
"""
Insert a memo into the database.
"""
try:
date = arrow.get(request.args.get('date', 0, type=str),
'YYYY/MM/DD').naive
text = request.args.get('text', 0, type=str)
record = {"type": "dated_memo",
"date": date,
... | cc89826956d6b2e5dc9bed3276bf7e102f47b285 | 3,630,624 |
def items_JSON():
"""Returns JSON object with all items"""
# Get all items
items = getItemAll(session)
# Return JSON object
return jsonify(Items=[i.serialize for i in items]) | 9e6d86c066054e2e567059fcc00f08c13c4fa797 | 3,630,625 |
def unescape(value, escape = "\\"):
"""
Unescapes the provided string value using the provided escape
character as the reference for the unescape operation.
This is considered to be a very expensive operation and so it
should be used carefully.
:type value: String
:param value: The string ... | 28aaebbfc5ea0022ce519a3ef91988504ea345f4 | 3,630,626 |
def __num_elems(shape):
"""Returns the number of elements in the given shape
Args:
shape: TensorShape
Return:
tot_elems: int
"""
tot_elems = 1
for s in shape:
tot_elems *= int(s)
return tot_elems | fd4f72394b22c98e6bedb545d7d11b8bfae11add | 3,630,627 |
def ocrRawCaptcha(image):
"""
recognize a captcha from http://bkxk.xmu.edu.cn/xsxk/login.html without preprocessing
:param image: image data of the captcha
:return: a string with four character
"""
images, _ = processImg.processImg(image)
result = ocrCaptchas(images)
return result | 672cb1fbd405cf4268971d87b17581563600fea4 | 3,630,628 |
from typing import Optional
from typing import Any
import json
def read_JSON(path: OpenFile) -> Optional[Any]:
"""
Attempt to read a JSON file. Returns False if the file doesn't exist.
:param path: the path of the file to read
"""
try:
with open(path, "r") as f:
return json.lo... | 0403b2a3e891c82389ddbdcf1f13f58400cec0c8 | 3,630,629 |
def adoptionSearch(cursor, search):
# search = data_params['search']
"""Return the result based on Mo's search input"""
lower_search = search.lower()
query = f"SELECT DISTINCT Adopter.email, AdoptionApplication.application_num, AdoptionApplication.date, " \
f"AdoptionApplication.co_applicant... | 22388799f65bef447c80c3da5c8f656705cba27e | 3,630,630 |
def onc_datetime(date_time, timezone="Canada/Pacific"):
"""Return a string representation of a date/time in the particular
ISO-8601 extended format required by the Ocean Networks Canada (ONC)
data web services API.
:arg date_time: Date/time to transform into format required by
ONC d... | ac22065635dbba3eef6381eb464dee4cd8994c36 | 3,630,631 |
def req(retry=3, proxy=False, timeout=30, concurren=1):
""" 通过装饰器来给出可选的配置。 """
def call(func):
req = ReqParse(func, retry=retry, proxy=proxy, timeout=timeout, concurren=concurren)
return req
return call | dd02e6fb79e9333a07cf41c0e955ff7671fe1683 | 3,630,632 |
def getHandValue(cards):
"""Returns value of cards."""
value = 0
numberOfAces = 0
for card in cards:
rank = card[0]
if rank == 'A':
numberOfAces += 1
elif rank in ('K','Q','J'):
value += 10
else:
value += int(rank)
value += number... | b40d45db627add8376ff9135229688114f81be83 | 3,630,635 |
from typing import Dict
def zigzag(n: int = 8) -> Dict:
"""
ZigZag encoder & decoder
Args:
n: size of chunk
Returns:
dictionary of encoder and decoder
"""
idx_zigzag = []
for a in sorted((p % n + p // n, (p % n, p // n)[(p % n - p // n) % 2], p) for p in range(n * n)):
... | c3e67aa5e41030eafd09058413e40ac3bb1f3201 | 3,630,636 |
def get_lr(optimizer):
"""Get current learning rate
Parameters
----------
optimizer : obj
An optimizer object.
Returns
-------
lr
Current learning rate.
"""
for param_group in optimizer.param_groups:
return param_group["lr"] | d3636ab7e4c1e92c24de29aff02d95151a7f42e8 | 3,630,637 |
import requests
def get_business_by_id(business_ids):
"""
Gets the business details for all the business_id's that are provided (
:param business_ids: This takes a single business id or a list of business ids
:type business_ids: list
:return: business
:rtype: dict
"""
logger.info("Atte... | 26161afc4b06da6572bcce28c82099fbf476e74e | 3,630,638 |
def twilio_secure(func):
"""Wrap a view function to ensure that every request comes from Twilio."""
@wraps(func)
def wrapper(*a, **kw):
if validate_twilio_request():
return func(*a, **kw)
return Response("Not a valid Twilio request", status=403)
return wrapper | 364b5dcb34b626d207296417c719bb0d4ddc54e8 | 3,630,641 |
def get_batch_dataset(record_file, parser, config):
"""
训练数据集TFRecordDataset的batch生成器。
Args:
record_file: 训练数据tf_record路径
parser: 数据存储的格式
config: 超参数
"""
num_threads = tf.constant(config.num_threads, dtype=tf.int32)
dataset = tf.data.TFRecordDataset(record_file).map(
... | 1e8ea8e8b7991d52b51d27245850a8abd7a486a6 | 3,630,642 |
from typing import Iterable
from typing import Tuple
from typing import List
def find_bundles_rescalings(
bundles: Iterable[InstanceBundle]
) -> Tuple[Tuple[List[InstanceBundle], Rescaling], ...]:
"""Finds a rescaling parameters for each subset of compatible instances.
Args:
bundles: Iterable... | 44e3e5fd9ff563a3c4c906f0282e41ce1c4beba3 | 3,630,643 |
def get_ordinal_suffix(number):
"""Receives a number int and returns it appended with its ordinal suffix,
so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc.
Rules:
https://en.wikipedia.org/wiki/Ordinal_indicator#English
- st is used with numbers ending in 1 (e.g. 1st, pronounced first)... | fc59e8586fa1df40b91c2922f52e4208ecc58038 | 3,630,644 |
def get_greppable(string):
"""Simply produces a string that -- when grepped -- will omit listing the grep process in a grep listing.
"""
return string.replace(string[0], '[%s]' % string[0], 1) | 65be4daa5650605ca3d95720d74a7a1137b5f4d7 | 3,630,645 |
def is_convergent_pair(p, rules):
"""Is the critical pair convergent?"""
u , v = p
n1, n2 = list(normalforms(u, rules)), list(normalforms(v, rules))
return n1 == n2 | e5e6790a98c5bb6fd6f3c6fb2e8b578d82d22d19 | 3,630,646 |
def is_userti(*args):
"""
is_userti(ea) -> bool
"""
return _ida_nalt.is_userti(*args) | 8171b1bf071bf78306035008238d7ca96812409e | 3,630,647 |
def players_player_id_get(player_id): # noqa: E501
"""Retrieve a single player's record
Returns a player record # noqa: E501
:param player_id: ID of player to return
:type player_id: str
:rtype: Player
"""
return 'do some magic!' | d9c2c92dbba3d139b2b5188e8722a0add7668393 | 3,630,648 |
def zero_array(array):
"""
Method to zero an array of data with the initial values.
:param array: Array of data - rows are time points, columns are signals.
:return: Zero'd numpy array
:rtype: np.ndarray
"""
init = array[:, 0]
zerod = np.apply_along_axis(lambda x: x - init, 0, array)
... | 79b51adb648f1fa56f6264079c8b24236c6e9714 | 3,630,649 |
from typing import Callable
from typing import Sequence
from typing import Hashable
from typing import List
def _stemmatological_costs_factory(
max_del_len: int = 5, frag_start: float = 10.0, frag_end: float = 10.0
) -> Callable:
"""
Define and return a function for computing candidate costs for a "stemma... | 2be18ea378fb70b7efc511d3d5572ef8b7638a9c | 3,630,650 |
def results_by_parameter(res, param, sort_by=None, sort_desc=False,
crossvalid_use_measurment='validation',
crossvalid_reduce=False,
crossvalid_reduce_fn=None):
"""
Takes a list of evaluation results `res` returned by a LDA evaluation fu... | 2ff2f4cc8edfb750bfa82b03e2d3f5cfea8646b5 | 3,630,651 |
def generate_case_study(
sampling_method: NormalSamplingMethod, cmap: CommitMap,
case_study_version: int, project_name: str, **kwargs: tp.Any
) -> CaseStudy:
"""
Generate a case study for a given project.
This function will draw `num_samples` revisions from the history of the
given project and ... | cd116a9cf1ae0b9eea55dde7f04ecc1d0fdeb47a | 3,630,652 |
def is_checkbox(field):
"""
Boolean filter for form fields to determine if a field is using a checkbox
widget.
"""
return isinstance(field.field.widget, forms.CheckboxInput) | e59b1f7692babd1d91752cf72c2fd51b6b9fac31 | 3,630,653 |
def build_info_str(username: str, name_len: int, remaining_chip: int, action: str,
chip: int, is_waiting: bool, countdown: int) -> str:
"""Build a string to explain action of a user
Args:
username (str): user name
name_len (int): characters to show the name
remaining_... | 1ecbb6c33d54a55500d51ce09cf9740ac28def96 | 3,630,654 |
def clustering_from_distance(dendrogram, distance):
"""
Given a dendrogram and a distance level, compute the partitions corresponding to the distance level
Parameters
----------
dendrogram: numpy.array
Each line of the dendrogram contains the merged nodes, the distance between merged n... | f4399e4dbe54b9cb9e9c3e786e8e11805ef0a75f | 3,630,656 |
def equivPhkv(k,v,n):
"""
Checks if two values are the same and implicitly checks if id actually checks if two variables
point to an object at the same memory location
"""
return equivValue(k,v,n) and referenceIdentity(n,v) and referenceIdentity(n.node,v.node) | 87d1983123cf56d964adb6c6f0bc039d5a33b775 | 3,630,659 |
import numpy
def get_spherical_bounding_box(lons, lats):
"""
Given a collection of points find and return the bounding box,
as a pair of longitudes and a pair of latitudes.
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays.
:retu... | 6a66b6d42f993036258a73f6fe7783f1dcb6d701 | 3,630,660 |
def get_similarity_score(dict1, dict2, dissimilarity = False):
"""
The keys of dict1 and dict2 are all lowercase,
you will NOT need to worry about case sensitivity.
Args:
dict1: frequency dictionary of words or n-grams for one text
dict2: frequency dictionary of words or n-grams for ano... | 31e8602d6ef098a58a8eaf497badebf2e19288eb | 3,630,661 |
def predict_fn(input_data, model):
"""Predict using input and model"""
return model(input_data) | 00f7bf0bd71f70833f8f77b16ffa62559747e915 | 3,630,662 |
def uniform_2_sphere(num: int = None):
"""Uniform sampling on a 2-sphere
Source: https://gist.github.com/andrewbolster/10274979
Args:
num: Number of vectors to sample (or None if single)
Returns:
Random Vector (np.ndarray) of size (num, 3) with norm 1.
If num is None returned ... | 097c65af0f24c1d20ee66c99723f413e6450b8f9 | 3,630,664 |
import torch
def nce_past(z_next_trans_dist, z_next_enc):
"""
z_next_trans_dist: p(.|z, u)
z_next_enc: samples from p(.|x')
"""
batch_size, z_dim = z_next_enc.size(0), z_next_enc.size(1)
z_next_trans_dist_rep = repeat_dist(z_next_trans_dist, batch_size, z_dim)
z_next_enc_rep = z_next_enc.... | ad5c0206a1295dc32588464c519bead4d7591448 | 3,630,665 |
def plot_performance(barcode_counts,
tick_label_size = 8,
cbar_label_size = 5,
dpi = 300,
barcode_threshold = 1,
absent_color = "black",
present_color = "green",
save = False,
... | c88f14ce7ea07473fe6b3d99d34a9823eb4580fe | 3,630,666 |
def get_simple_countings(df, start_yr=START_YR, end_yr=END_YR):
"""Generates simple counting statistics for the criterias ports, authors,
platforms, file extensions and types of exploits. It determines the 10
largest countings of each criteria.
:param df (DataFrame): A DataFrame object.
:param start... | e44ce1b7a0d9fe1e83726d52e8cd3f1eb90a50b7 | 3,630,667 |
from zine.application import get_application
def get_engine():
"""Return the active database engine (the database engine of the active
application). If no application is enabled this has an undefined behavior.
If you are not sure if the application is bound to the active thread, use
:func:`~zine.appl... | 2cfeb1aed8eceab4cc94db3e3619f6bcc12d59bd | 3,630,668 |
def get_unnormalized_text(words):
""" Returns the (unnormalized) text composed from the given words."""
return "".join([x.unnormalized_with_whitespaces for x in words]) | 162854d917ee4d49c3b2b824abc07697ac4f05ba | 3,630,669 |
def getCurrentUsersHomePath():
""" Return the path to the users home directory. Usually C:/Users/<user> """
return (shell.SHGetFolderPath (0, shellcon.CSIDL_PROFILE, None, 0)) | f6f637028bbf6b6dd6eb976e7ed81b460173b4eb | 3,630,670 |
import re
def alpha_num_order(string: str) -> str:
"""Returns all numbers on 5 digits to let sort the string with numeric order.
Ex: alphaNumOrder("a6b12.125") ==> "a00006b00012.00125"
"""
return "".join(
[
format(int(x), "05d") if x.isdigit() else x
for x in re.split(... | 01d49320c30f232163198ae8e88a11e4dfbc611f | 3,630,671 |
import requests
def _web_services_request(endpoint, params, method='GET'):
"""
Perform a request on an NYC.ID Web Services endpoint.
'userName' and 'signature' are added to the specified params.
:param endpoint: web services endpoint (e.g. "/account/validateEmail.htm")
:param params: request para... | 745a93616cc8fa1bc5a275f7abf3c000c5635af4 | 3,630,674 |
def dihedral_group(n):
"""
Return the dihedral group S_n.
>>> from qitensor import dihedral_group
>>> S3 = dihedral_group(3)
>>> S3.order
6
>>> S3.elements
[<S3.r0>, <S3.r1>, <S3.r2>, <S3.s0>, <S3.s1>, <S3.s2>]
>>> S3.e
<S3.r0>
>>> S3.r1 * S3.s0
<S3.s1>
>>> import p... | 9045d3d417f5aea2b6e118fd2ad7f054a194c308 | 3,630,676 |
def _half(X):
"""Returns the lower triangular part of
a matrix with half of diagonal part.
Args:
X: tensor of shape (..., m, m).
Returns:
tensor of shape (..., m, m), a set of matrices with half
of diagonal and without upper triangular parts."""
dim = tf.shape(X)[-1]
d... | 3f52e2c4a289fc9d14ba8e9c9c42c3d3a22a7b28 | 3,630,677 |
def multipart_encode_for_requests(params, boundary=None, cb=None):
"""streams uploads instead of loading entire file into memory"""
datagen, headers = multipart_encode(params, boundary, cb)
return IterableToFileAdapter(datagen), headers | 859c07b9af80b4df3267900276ab1c0506d42355 | 3,630,678 |
import json
def get_ability_icons(champion, input_path):
"""
This function takes a champion and input path strings as input and returns a
dictionary of png file paths with keys corresponding to the following
abilities: Passive, Q, W, E, and R
"""
global ability_icon_paths
ability_icon_pa... | e33c01bedcd8bf20959978df2bc2b33b934e2181 | 3,630,679 |
import json
def build_json_response(data, response_code='200 OK'):
"""
data (str | dict) : JSON encodable data
response_code (str) : HTTP response code
----
Return (bytes) HTTP response of JSON-encoded data.
"""
if type(data) == str:
data = json.loads(data)
elif type(data) ==... | ca2e19fbcaea7811c45d984540f2b03d21a1ce87 | 3,630,680 |
import math
def eval_biot_savart(xcp0, xnode1, xnode2, gamma, l0, delta_visc=0.025):
"""
This function uses the Biot-Savart law to evaluate the induced velocities
at control points (xcp), due to vortex line elements defined by locations xnode1, xnode2,
with strengths gamme and lengths l0. The delta_v... | 01595ad9eb5977f39ebe916f733746f8789e4bd0 | 3,630,681 |
import inspect
def validate_params(func):
"""
@note: validate decorator
"""
def _decorator(*args, **kwargs):
def _get_param_items(func, args, kwargs):
parameters = inspect.signature(func).parameters
arg_keys = tuple(parameters.keys())
vparams = [k for k, v... | ae0eb32347a3916f657653b1d8fda4ddd3292e44 | 3,630,682 |
def techniques_used(technique_list, technique):
""" Add technique to technique list and make distinction between techniques
subtechniques
"""
attack_id = util.buildhelpers.get_attack_id(technique['object'])
has_subtechniques = False
if attack_id:
# Check if technique not already in... | b1132f1bdf2abc0084a284ef891fd78b716a602b | 3,630,683 |
def admin_view_semesters_of_a_curriculum(request, curriculum_id):
""" gets all the semesters of a specfic curriculum """
curriculum = Curriculum.objects.get(id=curriculum_id)
semesters = Curriculum.get_semesters_objects(curriculum)
semester_slots = []
for sem in semesters:
a = list(Semester... | 60be9bad528d4e144bc53370719b94b0692716c2 | 3,630,684 |
from typing import Awaitable
from re import T
async def _aw_to_coro(aw: Awaitable[T]) -> T:
"""Wrap a given awaitable so it appears as a coroutine."""
return await aw | 5ac8301fa23fb9c231bfb68be43cee70cdeb8b8e | 3,630,686 |
from typing import Union
def get_text_recursive(tag: Union[Tag, NavigableString, None]) -> str:
"""Extract the text using the childrens."""
if tag is None:
return ""
if isinstance(tag, NavigableString):
return str(tag).strip().replace("\n", " ")
tag_name = tag.name
# Special tags... | 012019d845825f6cdba4d2d1883cd0b3940cd4d3 | 3,630,687 |
def _l1_regularization(l1, model):
"""Computes the L1 regularization for the given model
Args:
l1 (float): L1 parameter
model (:obj:`torch.nn.Module`): Model to use
Returns:
float: L1 loss (i.e. l1 * l1_norm(params))
"""
l1_loss = sum(param.norm(1) for param in model.parame... | 32826672a7de00f8a0412e2496e6ebfea213b502 | 3,630,688 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return Conv2D(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias_attr=False) | 55a4e869297ed1faccdabfcddae6a61855a67efb | 3,630,689 |
import torch
def create_feature_extractor(model, device=None):
"""
Factory function for creating an evaluator for supervised models
Args:
model (`torch.nn.Module`): the model to evaluate
device (str, optional): device type specification (default: None).
Applies to bo... | d39bf294c7a667e6319eda27b4436c4ce6688d65 | 3,630,690 |
def callit(iteratee, *args, **kwargs):
"""Inspect argspec of `iteratee` function and only pass the supported arguments when calling
it."""
maxargs = len(args)
argcount = kwargs["argcount"] if "argcount" in kwargs else getargcount(iteratee, maxargs)
argstop = min([maxargs, argcount])
return iter... | 2a23ad787929e7f50e6a38447c2a6fc458fc528e | 3,630,691 |
def get_doc_tokens(paragraph_text):
"""Tokenize the given paragraph and return character to word token offset for answer ranges"""
doc_tokens = []
char_to_word_offset = []
prev_is_whitespace = True
for c in paragraph_text:
if is_whitespace(c):
prev_is_whitespace = True
el... | bbe0374877ee19f2d9c31298f84201e8c5261a13 | 3,630,692 |
def ispython(script_path):
"""
Check to see if file is a python script file by extension
:param script_path:
:return:
"""
return hasextension(script_path, ".py") | 2d2c13df1eff659fb12c502b64eb5ed81b04466e | 3,630,693 |
def num_to_name(num):
"""
(int) -> str
Get IO pin name from its numeric identifier
>> num_to_name(8)
gpio_8
>> num_to_name(107)
D7
>>num_to_name(115)
A1
"""
# Pi pin numeric identifiers are the actual GPIO number
if num <= 27:
pname = "gpio_" + str(num)
# 100 ... | 202a7be3831ad9adbca68a3ff46587775b467ca2 | 3,630,694 |
def ConnectToDb_Return_Df_table(id,pwd,host,db_name,table_name):
"""
This method will Connect to Data base and return the requested table in the form of a dataframe
Better to make it a singleton to ensure multiple db connections are not spawned
:param id:
:param pwd:
:param host:
:param db_n... | af1fca9a0c7cacd22bb9fbb032eee0599b7158bd | 3,630,696 |
def n_prop_vs_rec(sorted_props, gt, n=100):
"""
sort n proposals by their score.
returns #proposals vs. recall -> [[a], [b], ..., [n]]
a = recall for 1 proposal
b = recall for 2 proposals
.
.
.
n = recall for (n+1) proposals
:param sorted_props: [[prop_0], [prop_1], ... | 558c4fcccd08329ed97b1dbbba87b8d8fca883e8 | 3,630,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.