content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def extract_dominant_keypoints2D(keypoint_2D, dominant_hand):
""" Extract keypoint 2D.
# Look Later with Octavio
# Arguments
keypoint_2D: Numpy array of shape (num_keypoints, 1).
dominant_hand: List of size (2) with booleans.
# Returns
keypoint_visibility_2D_21: Numpy array of s... | 2581b4cb68d6dad2da3933259582f9160224eef9 | 18,955 |
def translation_ev(h, t, tol=1e6):
"""Compute the eigenvalues of the translation operator of a lead.
Adapted from kwant.physics.leads.modes.
Parameters
----------
h : numpy array, real or complex, shape (N, N) The unit cell
Hamiltonian of the lead unit cell.
t : numpy array, real or co... | b5534b782b487ca195ab9b78438e68e81a62e74a | 18,956 |
def bsearch(n, pred):
"""
Given a boolean function pred that takes index arguments in [0, n).
Assume the boolean function pred returns all False and then all True for
values. Return the index of the first True, or n if that does not exist.
"""
# invariant: last False lies in [l, r) and pred(l) i... | 9274732aa9e24a0d0f73399ff50c19a544ac06a7 | 18,957 |
def test_rotating_file_handler_interval(tmpdir, logger, monkeypatch):
"""Test the rotating file handler when the rollover return a time smaller
than the current time.
"""
def rollover(obj, current_time):
return current_time - 0.1
monkeypatch.setattr(DayRotatingTimeHandler, 'computeRollover... | f6394f215e452fd7875b1fc624db9cb50cc19ed8 | 18,958 |
def compute_zero_crossing_wavelength(period, water_depth, gravity=GRAVITY):
"""Computes zero-crossing wavelength from given period.
This uses the dispersion relation for linear waves.
"""
return wavenumber_to_wavelength(
frequency_to_wavenumber(1. / period, water_depth, gravity)
) | 575ff3d251575fa7a232c120bde15f8f57c1dac9 | 18,959 |
def launch_transport_listener(transport, bindaddr, role, remote_addrport, pt_config, ext_or_cookie_file=None):
"""
Launch a listener for 'transport' in role 'role' (socks/client/server/ext_server).
If 'bindaddr' is set, then listen on bindaddr. Otherwise, listen
on an ephemeral port on localhost.
'... | 98ba849b3adc58b14b8983d0e61a409bc5ce3af7 | 18,960 |
import socket
import zmq
def send_array(A, flags=0, copy=True, track=False):
"""send a numpy array with metadata
Inputs
------
A: (subplots,dim) np array to transmit
subplots - the amount of subplots that are
defined in the current plot
dim - the amount of data that... | c53a17918c12e3ccec9046aad7fc7fc2f498a8ea | 18,962 |
import json
def api_file_upload(request):
""" Upload a file to the storage system """
try:
fobj = request.FILES["file"]
checksum, ext = fobj._name.split(".")
try:
request.user.check_staged_space(fobj._size, checksum)
except Exception as e:
return HttpRes... | 80b15b4d92b5ba2f3a247f1baf7900e73b18781f | 18,963 |
def set_vars(api, file:str, tess_profile:dict):
"""
Reads the user-specific variables from the tess_profile
:param api:
:param file:
:param tess_profile:
:return:
"""
# Set necessary information
api.SetImageFile(file)
# Set Variable
api.SetVariable("save_blob_choices", "T")
... | a7fbe0c5bc584928623e2eadc36240ea3b0f37de | 18,966 |
def qtrfit(numpoints, defcoords, refcoords, nrot):
"""Find the quaternion, q, [and left rotation matrix, u] that minimizes
| qTXq - Y | ^ 2 [|uX - Y| ^ 2]
This is equivalent to maximizing Re (qTXTqY)
The left rotation matrix, u, is obtained from q by
u = qT1q
Parameters
numpoint... | fdfde9deaf0b220bd468031264b029125c071fab | 18,967 |
import struct
def _embedded_bundles_partial_impl(
ctx,
bundle_embedded_bundles,
embeddable_targets,
frameworks,
plugins,
watch_bundles):
"""Implementation for the embedded bundles processing partial."""
_ignore = [ctx]
embeddable_providers = [
x[_Ap... | fe057887528a922ae89fe4c6d8066590d006e415 | 18,968 |
import yaml
def load_instrument(yml):
"""
Instantiate an instrument from YAML spec.
Parameters
----------
yml : str
filename for the instrument configuration in YAML format.
Returns
-------
hexrd.instrument.HEDMInstrument
Instrument instance.
"""
with open(ym... | a882b3b36def975b40124078c907a0f050b67a6f | 18,969 |
from typing import List
def serialize_model(self: models.Model, excludes: List[str] = None) -> dict:
"""
模型序列化,会根据 select_related 和 prefetch_related 关联查询的结果进行序列化,可以在查询时使用 only、defer 来筛选序列化的字段。
它不会自做主张的去查询数据库,只用你查询出来的结果,成功避免了 N+1 查询问题。
# See:
https://aber.sh/articles/A-new-idea-of-serializing-Djan... | 2c9a95b4d0e671492eefc73800d43196b6daa604 | 18,970 |
def isint(x):
"""
For an ``mpf`` *x*, or any type that can be converted
to ``mpf``, determines whether *x* is exactly
integer-valued::
>>> from sympy.mpmath import *
>>> isint(3), isint(mpf(3)), isint(3.2)
(True, True, False)
"""
if isinstance(x, int_types):
retu... | ec4516fa450cfc0e58c9a69d95f0f9b8aff2443c | 18,971 |
def update_header(file):
"""
Create a standard WCS header from the HDF5 header. To do this we clean up the
header data (which is initially stored in individual arrays). We then create
a new header dictionary with the old cleaned header info. Finally, we use
astropy.wcs.WCS to create an updated WCS h... | 1c46139a747acdf69ea6602ea123d20f540de30b | 18,972 |
def get_MD_psat():
""" MD data for saturation densities:
Thermodynamic properties of the 3D Lennard-Jones/spline model
Bjørn Hafskjold and Karl Patrick Travis and Amanda Bailey Hass and
Morten Hammer and Ailo Aasen and Øivind Wilhelmsen
doi: 10.1080/00268976.2019.1664780
"""
T = np.array([0.... | 363107962628ca9796397977f4f41e5b30bcfbc0 | 18,973 |
import logging
def get_reddit_client():
"""Utility to get a Reddit Client"""
reddit_username = redditUsername
reddit_password = redditPassword
reddit_user_agent = redditUserAgent
reddit_client_secret = redditClientSecret
reddit_client_id = redditClientID
logging.info("Logged in as user (%... | fe3a783a3ceb27954c658bf9dc036a067ab103a8 | 18,974 |
import six
def get_member_id():
"""
Retrieve member if for the current process.
:rtype: ``bytes``
"""
proc_info = system_info.get_process_info()
member_id = six.b('%s_%d' % (proc_info['hostname'], proc_info['pid']))
return member_id | 1d1cc24ffa62cc8982a23ea986bdf3cbecca53ac | 18,975 |
def get_table_arn():
"""A method to get the DynamoDB table ARN string.
Returns
-------
dict
A dictionary with AWS ARN string for the table ARN.
"""
resp = dynamodb_client.describe_table(
TableName=table_name
)
return {
"table_arn": resp['Table']['TableArn']
} | ee6648048b1cabdbc04e6c3507cc4e1992f059b2 | 18,976 |
def replace_characters(request):
"""Function to process execute replace_characters function."""
keys = ['text', 'characters', 'replacement']
values = get_data(request, keys)
if not values[0]:
abort(400, 'missing text parameter')
if not values[2]:
values[2] = ''
return _call('r... | 4765d7c3ace0a0069cac34adb04381efc7043355 | 18,977 |
def serialize_to_jsonable(obj):
"""
Serialize any object to a JSONable form
"""
return repr(obj) | c8632b8b475d49b56d47b29afa8b44676b7882a5 | 18,978 |
def compare(optimizers, problems, runs=20, all_kwargs={}):
"""Compare a set of optimizers.
Args:
optimizers: list/Optimizer; Either a list of optimizers to compare,
or a single optimizer to test on each problem.
problems: list/Problem; Either a problem instance or a list of problem ... | c0f2ed52fe5de8b32e54ca6e3dc05be18145b1e8 | 18,979 |
def az_el2norm(az: float, el: float):
"""Return solar angle as normalized vector."""
theta = np.pi/2-el*np.pi/180
phi = az*np.pi/180
norm = np.asarray(
[
np.sin(theta)*np.cos(phi),
np.sin(theta)*np.sin(phi),
np.cos(theta)
])
return norm | 5d6e53b778846281a6d2944a52acc64c4386ade4 | 18,980 |
async def api_get_user(user_id: int, db: Session = Depends(get_db)):
"""
Gets user entity
- **user_id**: the user id
- **db**: current database session object
"""
try:
user = await User.get_by_id(id=user_id, db=db)
return user
except UserNotFoundException as e:
... | 2d89fed33e4fbc81e3461b4791f93772a4814ffe | 18,981 |
import re
def remove_comments(json_like):
"""
Removes C-style comments from *json_like* and returns the result. Example::
>>> test_json = '''\
{
"foo": "bar", // This is a single-line comment
"baz": "blah" /* Multi-line
Comment */
}'''
>>> r... | 32ddf8dd19a8d1029b0d5f221aed05c3883d8ee5 | 18,982 |
def install_editable(projectroot, **kwargs):
"""Install the given project as an "editable" install."""
return run_pip('install', '-e', projectroot, **kwargs) | 70b4f5dc1da26beaae31bb1aeaed4457a0d055a3 | 18,983 |
import time
def retry_get(tap_stream_id, url, config, params=None):
"""Wrap certain streams in a retry wrapper for frequent 500s"""
retries = 20
delay = 120
backoff = 1.5
attempt = 1
while retries >= attempt:
r = authed_get(tap_stream_id, url, config, params)
if r.status_code !... | af9a0dd8d5c7022467562b7c339f8340b6d87d73 | 18,984 |
from typing import Mapping
from datetime import datetime
from typing import Tuple
def build_trie_from_to(template_dictionary: Mapping, from_timestamp: datetime.datetime, to_timestamp: datetime.datetime) -> Tuple[ahocorasick.Automaton, Mapping]:
"""Function which builds the trie from the first timestamp tot the la... | ddd655235a78834260ce1a46c19d0e251f62aede | 18,985 |
def check_monotonicity_at_split(
tree_df, tree_no, trend, variable, node, child_nodes_left, child_nodes_right
):
"""Function to check monotonic trend is in place at a given split in a single tree."""
if not isinstance(tree_df, pd.DataFrame):
raise TypeError("tree_df should be a pd.DataFrame")
... | 97ed2422c6f85112e364e9c63ff0a54d18b6377d | 18,986 |
def allocate_usda_ers_mlu_land_in_urban_areas(df, attr, fbs_list):
"""
This function is used to allocate the USDA_ERS_MLU activity 'land in
urban areas' to NAICS 2012 sectors. Allocation is dependent on
assumptions defined in 'literature_values.py' as well as results from
allocating 'EIA_CBECS_Land'... | 5fcb797b48b912595d722cde3ac0d499526ea899 | 18,987 |
def get_distances_between_points(ray_points3d, last_bin_width=1e10):
"""Estimates the distance between points in a ray.
Args:
ray_points3d: A tensor of shape `[A1, ..., An, M, 3]`,
where M is the number of points in a ray.
last_bin_width: A scalar indicating the witdth of the last bin.
Returns:
... | 34752bd64bcf4582945006c4bd3489397aa7350d | 18,988 |
def reclassification_heavy_duty_trucks_to_light_commercial_vehicles(register_df: pd.DataFrame) -> pd.DataFrame:
"""
Replace Category to Light Commercial Vehicles for Heavy Duty Trucks of weight below 3500kg
Es Tracta de vehicles registrats TIPUS CAMIONS i per tant classificats en la categoria Heavy Duty Tr... | 638e3281c323c1dac4ddcde5e58e2eeac4131c04 | 18,989 |
def SpComp(rho, U, mesh, fea, penal):
"""Alias SpCompFunction class with the apply method"""
return SpCompFunction.apply(rho, U, mesh, fea, penal) | 4c0997fa5213e291376feb415f74e48e273ea071 | 18,990 |
def get_landmark_position_from_state(x, ind):
"""
Extract landmark position from state vector
"""
lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :]
return lm | 048d31bbd6810663d51e9db34b5c87ebec9b6f27 | 18,992 |
def get_rectangle(roi):
"""
Get the rectangle that has changing colors in the roi.
Returns boolean success value and the four rectangle points in the image
"""
gaussian = cv2.GaussianBlur(roi, (9, 9), 10.0)
roi = cv2.addWeighted(roi, 1.5, gaussian, -0.5, 0, roi)
nh, nw, r = roi.shape
... | da3e6311f6a598cf57cffd2c0bb06f0ca53fa108 | 18,993 |
async def challenge_process_fixture() -> Challenge:
"""
Populate challenge with:
- Default user
- Is open
- Challenge in process
"""
return await populate_challenge() | cf553c0697c824df4273838c7d87ffe6e8ab6ae7 | 18,994 |
import pkgutil
def _read_pdg_masswidth(filename):
"""Read the PDG mass and width table and return a dictionary.
Parameters
----------
filname : string
Path to the PDG data file, e.g. 'data/pdg/mass_width_2015.mcd'
Returns
-------
particles : dict
A dictionary where the ke... | c61202aeb4ad36e22786457306de1ac5773b56d2 | 18,995 |
import torch
def fps_and_pred(model, batch, **kwargs):
"""
Get fingeprints and predictions from the model.
Args:
model (nff.nn.models): original NFF model loaded
batch (dict): batch of data
Returns:
results (dict): model predictions and its predicted
fingerprints, conformer w... | 1a8cca3ffe0d386e506ab42f6e77e00b1a5975d1 | 18,996 |
import re
def preprocess_text(text):
"""
Should return a list of words
"""
text = contract_words(text)
text = text.lower()
# text = text.replace('"', "").replace(",", "").replace("'", "")
text = text.replace('"', "").replace(",", "").replace("'", "").replace(".", " .") ## added by PAV... | 0b42b57629e68c2f0bf3831dc226a2ba823cfdb3 | 18,997 |
import unicodedata
def unicodeToAscii(s):
"""unicodeToAscii
Turn a Unicode string to plain ASCII, thanks to https://stackoverflow.com/a/518232/2809427
For example, 'Ślusàrski' -> 'Slusarski'
"""
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) !... | 7791ae244499b2448ac4bc5de0fde35057d1f5d5 | 18,998 |
def update_ip_table(nclicks, value):
"""
Function that updates the IP table in the Elasticsearch Database that
contains the frequency as well as the IP address of the machine querying
that particular domain.
Args:
nclicks: Contains the number of clicks registered by the submit button.
... | ef0df6f1fb79d86a707990d0790dadabecbd22c1 | 18,999 |
def collect_subclasses(mod, cls, exclude=None):
"""Collecting all subclasses of `cls` in the module `mod`
@param mod: `ModuleType` The module to collect from.
@param cls: `type` or (`list` of `type`) The parent class(es).
@keyword exclude: (`list` of `type`) Classes to not include.
"""
out = []... | 30e64b93fca4d68c3621cae54bb256350875eb77 | 19,000 |
import typing
from typing import Counter
def check_collections_equivalent(a: typing.Collection, b: typing.Collection,
allow_duplicates: bool = False,
element_converter: typing.Callable = identity) -> typing.Tuple[str, list]:
"""
:param a: one ... | 61d78f522a6e87927db6b32b46637f0bb6a10513 | 19,001 |
def voting_classifier(*args, **kwargs):
"""
same as in gradient_boosting_from_scratch()
"""
return VotingClassifier(*args, **kwargs) | ed92138c23b699672197d1b436773a5250685250 | 19,002 |
import re
def replace_subject_with_object(sent, sub, obj):
"""Replace the subject with object and remove the original subject"""
sent = re.sub(r'{}'.format(obj), r'', sent, re.IGNORECASE)
sent = re.sub(r'{}'.format(sub), r'{} '.format(obj), sent, re.IGNORECASE)
return re.sub(r'{\s{2,}', r' ', sent, re... | 1c7f8115968c4e4ef10dcc3b83f0f259433f5082 | 19,003 |
def estimate_using_user_recent(list_type: str, username: str) -> int:
"""
Estimate the page number of a missing (entry which was just approved) entry
and choose the max page number
this requests a recent user's list, and uses checks if there are any
ids in that list which arent in the approved cach... | b6a7a5bf6c0fa6e13021f10bf2fe613c4186f430 | 19,004 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_html2pdf package"""
reload_params = {"package": u"fn_html2pdf",
"incident_fields": [],
"action_fields": [],
"function_params": [u"html2pdf_data", u"html2pdf_data_type", u"htm... | 45a5e974f3e02953a6d121e37c05022c448adae6 | 19,005 |
def instrument_keywords(instrument, caom=False):
"""Get the keywords for a given instrument service
Parameters
----------
instrument: str
The instrument name, i.e. one of ['niriss','nircam','nirspec',
'miri','fgs']
caom: bool
Query CAOM service
Returns
-------
p... | 271f58615dbdbcde4fda9a5248d8ae3b40b90f6d | 19,006 |
from struct import unpack
from time import mktime, strftime, gmtime
def header_info(data_type, payload):
"""Report additional non-payload in network binary data.
These can be status, time, grapic or control structures"""
# Structures are defined in db_access.h.
if payload == None:
return ""
... | 6e83be0dff2d7f81a99419baf505e82957518c64 | 19,007 |
def dsa_verify(message, public, signature, constants=None):
"""Checks if the signature (r, s) is correct"""
r, s = signature
p, q, g = get_dsa_constants(constants)
if r <= 0 or r >= q or s <= 0 or s >= q:
return False
w = inverse_mod(s, q)
u1 = (bytes_to_num(sha1_hash(message)) * w) % q... | 9d6eeb9b5b2d84edd054cba01bdd47cb9bab120e | 19,008 |
def set_up_cgi():
"""
Return a configured instance of the CGI simulator on RST.
Sets up the Lyot stop and filter from the configfile, turns off science instrument (SI) internal WFE, and reads
the FPM setting from the configfile.
:return: CGI instrument instance
"""
webbpsf.setup_logging('ER... | 68559e88b9cebb5e2edb049f63d80c9545112804 | 19,009 |
def plot_line(
timstof_data, # alphatims.bruker.TimsTOF object
selected_indices: np.ndarray,
x_axis_label: str,
colorscale_qualitative: str,
title: str = "",
y_axis_label: str = "intensity",
remove_zeros: bool = False,
trim: bool = True,
height: int = 400
) -> go.Figure:
"""Plot... | 5db0468710e49158c4b13fc56446a23949544e57 | 19,010 |
def all_gather(data):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors)
Args:
data: any picklable object
Returns:
list[data]: list of data gathered from each rank
"""
world_size = get_world_size()
if world_size == 1:
return [data]
data_list ... | 46f34975d89766c842b6c20e312ad3dea4f3d7ff | 19,011 |
from ..utils import check_adata
def draw_graph(
adata,
layout=None,
color=None,
alpha=None,
groups=None,
components=None,
legend_loc='right margin',
legend_fontsize=None,
legend_fontweight=None,
color_map=None,
palette=None,
... | 006121b0162afcf6b91703dac8c1ea3e6d1351bc | 19,013 |
def post_token():
"""
Receives authentication credentials in order to generate an access
token to be used to access protected models. Tokens generated
by this endpoint are JWT Tokens.
"""
# First we verify the request is an actual json request. If not, then we
# responded with ... | d51de9aa201fdb0d879190c5f08352b43f425be4 | 19,014 |
def judgement(seed_a, seed_b):
"""Return amount of times last 16 binary digits of generators match."""
sample = 0
count = 0
while sample <= 40000000:
new_a = seed_a * 16807 % 2147483647
new_b = seed_b * 48271 % 2147483647
bin_a = bin(new_a)
bin_b = bin(new_b)
la... | 9d778909ba6b04e4ca3adbb542fce9ef89d7b2b7 | 19,015 |
def GJK(shape1, shape2):
""" Implementation of the GJK algorithm
PARAMETERS
----------
shape{1, 2}: Shape
RETURN
------
: bool
Signifies if the given shapes intersect or not.
"""
# Initialize algorithm parameters
direction = Vec(shape1.center, shape2.center).direct... | 4e3b24ec9fab1d2625c3d99ae3ffc2325c1dcaf8 | 19,016 |
def _set_int_config_parameter(value: OZWValue, new_value: int) -> int:
"""Set a ValueType.INT config parameter."""
try:
new_value = int(new_value)
except ValueError as err:
raise WrongTypeError(
(
f"Configuration parameter type {value.type} does not match "
... | e9e168aa1959dfab141622a0d0f3751a1e042dfd | 19,017 |
def split_dataset(dataset_file, trainpct):
"""
Split a file containing the full path to individual annotation files into
train and test datasets, with a split defined by trainpct.
Inputs:
- dataset_file - a .txt or .csv file containing file paths pointing to annotation files.
(Expects that t... | 0f24d29efdf3645a743bbb6d9e2e27b9087552be | 19,018 |
def accession(data):
"""
Get the accession for the given data.
"""
return data["mgi_marker_accession_id"] | 132dcbdd0712ae30ce7929e58c4bc8cdf73aacb2 | 19,019 |
def get_phase_dir(self):
"""Get the phase rotating direction of stator flux stored in LUT
Parameters
----------
self : LUT
a LUT object
Returns
----------
phase_dir : int
rotating direction of phases +/-1
"""
if self.phase_dir not in [-1, 1]:
# recalculate ... | e335f78d6219f0db5a390cf47aaa7aa093f7c329 | 19,020 |
def atomic_number(request):
"""
An atomic number.
"""
return request.param | 6f1a868c94d0a1ee4c84a76f04b4cabc3e0356e0 | 19,021 |
def plot_metric(title = 'Plot of registration metric vs iterations'):
"""Plots the mutual information over registration iterations
Parameters
----------
title : str
Returns
-------
fig : matplotlib figure
"""
global metric_values, multires_iterations
fig, ax = plt.... | 488d96876a469522263f6c7118b94b35a25e36de | 19,022 |
from re import T
def cross_entropy(model, _input, _target):
""" Compute Cross Entropy between target and output diversity.
Parameters
----------
model : Model
Model for generating output for compare with target sample.
_input : theano.tensor.matrix
Input sample.
_target : th... | c65efe3185269d8f7132e23abbd517ca9273d481 | 19,023 |
def get_groups_links(groups, tenant_id, rel='self', limit=None, marker=None):
"""
Get the links to groups along with 'next' link
"""
url = get_autoscale_links(tenant_id, format=None)
return get_collection_links(groups, url, rel, limit, marker) | 35188c3c6d01026153a6e18365ae0b4b596a8883 | 19,025 |
def over(expr: ir.ValueExpr, window: win.Window) -> ir.ValueExpr:
"""Construct a window expression.
Parameters
----------
expr
A value expression
window
Window specification
Returns
-------
ValueExpr
A window function expression
See Also
--------
ib... | e9c8f656403520d5f3287de38c139b8fd8446d13 | 19,026 |
def node_value(node: Node) -> int:
"""
Computes the value of node
"""
if not node.children:
return sum(node.entries)
else:
value = 0
for entry in node.entries:
try:
# Entries start at 1 so subtract all entries by 1
value += node_val... | c22ac3f73995e138f7eb329499caba3fc67175a5 | 19,027 |
import re
def load_mac_vendors() :
""" parses wireshark mac address db and returns dict of mac : vendor """
entries = {}
f = open('mac_vendors.db', 'r')
for lines in f.readlines() :
entry = lines.split()
# match on first column being first six bytes
r = re.compile(r'^([0-9A-F]{... | 361e9c79de8b473c8757ae63384926d266b68bbf | 19,028 |
def parse_time(s):
"""
Parse time spec with optional s/m/h/d/w suffix
"""
if s[-1].lower() in secs:
return int(s[:-1]) * secs[s[-1].lower()]
else:
return int(s) | 213c601143e57b5fe6cd123631c6cd562f2947e9 | 19,029 |
def resize_labels(labels, size):
"""Helper function to resize labels.
Args:
labels: A long tensor of shape `[batch_size, height, width]`.
Returns:
A long tensor of shape `[batch_size, new_height, new_width]`.
"""
n, h, w = labels.shape
labels = F.interpolate(labels.view(n, 1, h, w).float(),
... | 87c7127643e9e46878bc526ebed4068d40f25ece | 19,030 |
import re
def _extract_urls(html):
"""
Try to find all embedded links, whether external or internal
"""
# substitute real html symbols
html = _replace_ampersands(html)
urls = set()
hrefrx = re.compile("""href\s*\=\s*['"](.*?)['"]""")
for url in re.findall(hrefrx, html):
urls.... | 5303cf7b750926aa5919bbfa839bd227319aa9f7 | 19,031 |
def reorganize_data(texts):
"""
Reorganize data to contain tuples of a all signs combined and all trans combined
:param texts: sentences in format of tuples of (sign, tran)
:return: data reorganized
"""
data = []
for sentence in texts:
signs = []
trans = []
for sign,... | 27b4efd99bbf470a9f8f46ab3e34c93c606d0234 | 19,032 |
def client_new():
"""Create new client."""
form = ClientForm(request.form)
if form.validate_on_submit():
c = Client(user_id=current_user.get_id())
c.gen_salt()
form.populate_obj(c)
db.session.add(c)
db.session.commit()
return redirect(url_for('.client_view', ... | b355f43cd80e0f7fef3027f5f1d1832c4e4ece5a | 19,033 |
def query_schema_existence(conn, schema_name):
"""Function to verify whether the current database schema ownership is correct."""
with conn.cursor() as cur:
cur.execute('SELECT EXISTS(SELECT 1 FROM information_schema.schemata WHERE SCHEMA_NAME = %s)',
[schema_name])
return cu... | 9c556283d255f580fc69a9e41a4d452d15e1eb17 | 19,034 |
def get_number_of_params(model, trainable_only=False):
"""
Get the number of parameters in a PyTorch Model
:param model(torch.nn.Model):
:param trainable_only(bool): If True, only count the trainable parameters
:return(int): The number of parameters in the model
"""
return int(np.sum([np.pro... | 4e02e977e9fc2949a62ce433c9ff6d732d74a746 | 19,035 |
import time
import requests
def chart1(request):
"""
This view tests the server speed for transferring JSON and XML objects.
:param request: The AJAX request
:return: JsonResponse of the dataset.
"""
full_url = HttpRequest.build_absolute_uri(request)
relative = HttpRequest.get_full_path(... | 6eb88d3ef1aed85799832d5751ec4e30c54aaa07 | 19,036 |
def conv3x3(in_planes, out_planes, stride=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, bias=False) | 115dd9e8afdaa850293fa08c103ab2966eceedbf | 19,037 |
import mimetypes
def img_mime_type(img):
"""Returns image MIME type or ``None``.
Parameters
----------
img: `PIL.Image`
PIL Image object.
Returns
-------
mime_type : `str`
MIME string like "image/jpg" or ``None``.
"""
if img.format:
ext = "." + img.format
... | fe46af6e5c03a1ae80cb809c81ab358ac5c085fa | 19,038 |
def check_satisfy_dataset(w, D, involved_predicates=[]):
"""
This function is to check whether all facts in ``D'' have been installed in each of ruler intervals
of the given Window ``w'' if facts in ruler intervals holds in ``D''.
Args:
w (a Window instance):
D (dictionary of dictionary ... | b2715ca1eba03bbcf0581fdfeb97177cde8d12d7 | 19,040 |
def interp_at(d, g, varargs=None, dim=None, dask="parallelized"):
"""
Interpolates a variable to another.
Example : varargs = [THETA, mld] : THETA(t, z, y, x) is interpolated with Z=mld(t, y, x)
"""
var, coordvar = varargs
dim = (
dim if dim is not None else set(d[var].dims).difference(d... | a31cccee447deb2fd2612460471598d74e347c53 | 19,041 |
def get_history():
"""Get command usage history from History.sublime-project"""
f = open('%s/%s/%s' % (sublime.packages_path(),
"TextTransmute",
"History.sublime-project"), 'r')
content = f.readlines()
f.close()
return [x.strip() for x in conten... | fab11f52c2b90d1fb29ace944c8f80f67fc9170e | 19,042 |
from typing import Dict
from typing import Callable
from typing import Any
import asyncio
def inprogress(metric: Gauge, labels: Dict[str, str] = None) -> Callable[..., Any]:
"""
This decorator provides a convenient way to track in-progress requests
(or other things) in a callable.
This decorator func... | c10adbb07796c26fd59d1038a786b25b6346fd97 | 19,043 |
from typing import Optional
import base64
def b58_wrapper_to_b64_public_address(b58_string: str) -> Optional[str]:
"""Convert a b58-encoded PrintableWrapper address into a b64-encoded PublicAddress protobuf"""
wrapper = b58_wrapper_to_protobuf(b58_string)
if wrapper:
public_address = wrapper.publi... | a4c46800c0d22ef96d3fa622b6a37bf55e1960da | 19,044 |
def render_to_AJAX(status, messages):
"""return an HTTP response for an AJAX request"""
xmlc = Context({'status': status,
'messages': messages})
xmlt = loader.get_template("AJAXresponse.xml")
response = xmlt.render(xmlc)
return HttpResponse(response) | cb5ad3ead4d5bee9a710767d1f49c81b2b137441 | 19,045 |
def parse_params(environ, *include):
"""Parse out the filter, sort, etc., parameters from a request"""
if environ.get('QUERY_STRING'):
params = parse_qs(environ['QUERY_STRING'])
else:
params = {}
param_handlers = (
('embedded', params_serializer.unserialize_string, None),
('filter', params_serializer.unseri... | ff8d263e4495804e1bb30d0c4da352b2437fc8f8 | 19,046 |
def create_dict_facade_for_object_vars_and_mapping_with_filters(cls, # type: Type[Mapping]
include, # type: Union[str, Tuple[str]]
exclude, ... | cccdc19b43ca269cfedb4f7d6ad1d7b8abba78e1 | 19,047 |
import time
def now():
"""
此时的时间戳
:return:
"""
return int(time.time()) | 39c05a695bfe4239ebb3fab6f3a5d0967bea6820 | 19,048 |
def get_yourContactINFO(rows2):
"""
Function that returns your personal contact info details
"""
yourcontactINFO = rows2[0]
return yourcontactINFO | beea815755a2e6817fb57a37ccc5aa479455bb81 | 19,049 |
def hafnian(
A, loop=False, recursive=True, rtol=1e-05, atol=1e-08, quad=True, approx=False, num_samples=1000
): # pylint: disable=too-many-arguments
"""Returns the hafnian of a matrix.
For more direct control, you may wish to call :func:`haf_real`,
:func:`haf_complex`, or :func:`haf_int` directly.
... | 0e90f1d372bf7be636ae8eb333d2c59a387b58f1 | 19,050 |
def filter_out_nones(data):
"""
Filter out any falsey values from data.
"""
return (l for l in data if l) | 39eb0fb7aafe799246d231c5a7ad8a150ed4341e | 19,051 |
def BytesToGb(size):
"""Converts a disk size in bytes to GB."""
if not size:
return None
if size % constants.BYTES_IN_ONE_GB != 0:
raise calliope_exceptions.ToolException(
'Disk size must be a multiple of 1 GB. Did you mean [{0}GB]?'
.format(size // constants.BYTES_IN_ONE_GB + 1))
retu... | 49bc846ce6887fd47ac7be70631bddd8353c72ed | 19,053 |
def build_report(drivers: dict, desc=False) -> [[str, str, str], ...]:
"""
Creates a race report: [[Driver.name, Driver.team, Driver.time], ...]
Default order of drivers from best time to worst.
"""
sorted_drivers = sort_drivers_dict(drivers, desc)
return [driver.get_stats for driver in sorted_d... | c8c84319c0a14867b21d09c8b66ea434d13786aa | 19,054 |
def add_sites_sheet(ws, cols, lnth):
"""
"""
for col in cols:
cell = "{}1".format(col)
ws[cell] = "='Capacity_km2_MNO'!{}".format(cell)
for col in cols[:2]:
for i in range(2, lnth):
cell = "{}{}".format(col, i)
ws[cell] = "='Capacity_km2_MNO'!{}"... | c1db2b585021e8eef445963f8c300d726600e12a | 19,055 |
import itertools
def testBinaryFile(filePath):
"""
Test if a file is in binary format
:param fileWithPath(str): File Path
:return:
"""
file = open(filePath, "rb")
#Read only a couple of lines in the file
binaryText = None
for line in itertools.islice(file, 20):
... | 809a962881335ce0a3a05e341a13b413c381fedf | 19,056 |
def dup_max_norm(f, K):
"""
Returns maximum norm of a polynomial in ``K[x]``.
Examples
========
>>> from sympy.polys import ring, ZZ
>>> R, x = ring("x", ZZ)
>>> R.dup_max_norm(-x**2 + 2*x - 3)
3
"""
if not f:
return K.zero
else:
return max(dup_abs(f, K)) | 1ba4744781a3f5cb8e71b59bc6588579f88a6d43 | 19,058 |
def greedy_algorithm(pieces, material_size):
"""Implementation of the First-Fit Greedy Algorithm
Inputs:
pieces - list[] of items to place optimally
material_size - length of Boards to cut from, assumes unlimited supply
Output:
Optimally laid out BoardCollection.contents, which is a list[] of ... | f42b2372b50385c693765d65614d73a8b21f496b | 19,059 |
def start_tv_session(hypes):
"""
Run one evaluation against the full epoch of data.
Parameters
----------
hypes : dict
Hyperparameters
Returns
-------
tuple
(sess, saver, summary_op, summary_writer, threads)
"""
# Build the summary operation based on the TF coll... | f54cfa17871badf2cbe92200144a758d0fc2dc41 | 19,060 |
def factor_size(value, factor):
"""
Factors the given thumbnail size. Understands both absolute dimensions
and percentages.
"""
if type(value) is int:
size = value * factor
return str(size) if size else ''
if value[-1] == '%':
value = int(value[:-1])
return '{0}%... | 41b061fb368d56ba18b52cd7a6a3322292671d83 | 19,061 |
def categoryProfile(request, pk):
"""
Displays the profile of a :class:`gestion.models.Category`.
pk
The primary key of the :class:`gestion.models.Category` to display profile.
"""
category = get_object_or_404(Category, pk=pk)
return render(request, "gestion/category_profile.html", {"ca... | 87318332c7e317a49843f5becda8196951743ce5 | 19,062 |
def eoms(_x, t, _params):
"""Rigidy body equations of motion.
_x is an array/list in the following order:
q1: Yaw q2: Lean |-(Euler 3-1-2 angles used to orient A
q3: Pitch /
q4: N[1] displacement of mass center.
q5: N[2] displacement of mass center.
q6: ... | 3868411e2c082617311f59f3b39deec9d3a370fa | 19,063 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.