content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def covered_cv_skills_from_course(user_id, course_id):
"""This function is used find the relation of a course to a user cv"""
fetch_cv_command = """SELECT DISTINCT id FROM "CVs" WHERE user_id={user_id}""""".format(**{'user_id': user_id})
cv_df = get_table(sql_command=fetch_cv_command)
if len(cv_df) > 0:... | 6befec8d8e15e759ac24718176fcf516d851d3ae | 3,623,247 |
def processRHS(rhs):
"""
Depending on the type of the argument, calls the corresponding
function to deal with that type.
:param rhs: portion of JSGF rule
:type rhs: either a JSGF Expression, list, or string
:returns: list of strings
"""
if type(rhs) is list:
return processSequen... | 412def2461fcfa3cc3ae48f8bcb2e4a4c18bb9e9 | 3,623,248 |
def svn_prop_name_is_valid(prop_name):
"""svn_prop_name_is_valid(char const * prop_name) -> svn_boolean_t"""
return _core.svn_prop_name_is_valid(prop_name) | 50c9c833f5d1935d6f411530700bb28ce60f0ca7 | 3,623,249 |
def factory():
"""
A factory that creates clustering algorithms.
"""
return ClusteringFactory | 4b4e81e4e32b9bf1e0b69b499e4f748f4a4836d3 | 3,623,250 |
import pycountry
def subdivision_type(country_code):
"""Returns the name of the most common country subdivision type for
the given country code."""
ensure_definition(country_code)
counts = dict()
for subdivision in pycountry.subdivisions.get(country_code=country_code):
if subdivision.paren... | e8268095cea3eb8e0e48772dd2b257f78fc4d314 | 3,623,251 |
def get_fans(tp):
""" Get fan_in and fan_out with corresponding slices """
slices_fan_in = {} # fan_in per slice
slices_fan_out = {}
for weight, instr in zip(tp.weight_views(), tp.instructions):
slice_idx = instr[2]
mul_1, mul_2, mul_out = weight.shape
fan_in = mul_1 * mul_2
... | 7fdff84c5129bd22a738653b6676d48c2a5f073d | 3,623,252 |
import numpy as np
import xarray as xr
from pandas import Timestamp
def download_noaa_mbl(
noaa_mbl_url,
download_dest="../data/raw/co2_GHGreference_surface.txt",
target_lat=None,
target_lon=None,
interp_method="linear",
):
"""
Downloads the NOAA marine boundary layer xCO2 and grids it
... | ba13bce93174bf3fbf3b47de2855f7fd3ff7dee3 | 3,623,253 |
import math
def get_pier_nodes(bridge: Bridge, ctx: BuildContext) -> PierNodes:
"""All the nodes for a bridge's piers.
NOTE: This function assumes that 'get_deck_nodes' has already been called
with the same 'BuildContext'.
"""
pier_nodes = []
for pier_i, pier in enumerate(bridge.supports):
... | 4f2ca233c4c58538c5074f168c52d086614e71b7 | 3,623,254 |
def secret_token():
"""
Fixture that yields a usable secret token.
"""
return 'super-secret-token-string'.encode() | 90e6c54a18387c64e27fea93912278c126df1585 | 3,623,255 |
def gf_from_int_poly(f, p):
"""
Create ``GF(p)[x]`` polynomial from ``Z[x]``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.galoistools import gf_from_int_poly
>>> gf_from_int_poly([7, -2, 3], 5)
[2, 3, 3]
"""
return gf_trunc(f, p) | 8716d08286b49310953a5d00d2d0c7f8a98a540d | 3,623,256 |
import requests
def macro_uk_halifax_yearly():
"""
东方财富-经济数据-英国-Halifax 房价指数年率
http://data.eastmoney.com/cjsj/foreign_4_1.html
:return: Halifax房价指数年率
:rtype: pandas.DataFrame
"""
url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx"
params = {
"type": "GJZB",
... | 09214bda60da565865c24e82f831466844fac92e | 3,623,257 |
def fock_state(state, device_wires, params):
"""Computes the expectation value of the ``qml.FockStateProjector``
observable in Strawberry Fields.
Args:
state (strawberryfields.backends.states.BaseState): the quantum state
device_wires (Wires): the measured mode
params (Sequence): se... | 955d59f3edcb8c6d0fbdfebb0fe1beca534df957 | 3,623,258 |
from datetime import datetime
def datetime_from_filetime(filetime):
"""return a :class:`datetime.datetime` from a ``windows`` FILETIME int"""
# Manual non-approx rounding as filetime will not have a perfect representation as Python float
# We do some sort of "manual rounding cause of py2 vs py3
# PY2:... | fc63e7a1072adff64bc8da3548285fed2e0add44 | 3,623,259 |
def forward_one_to_one_with_sr(request):
"""
Return all the publishers with associated owner, using select_related.
53ms overall
1ms on queries
1 queries
SELECT "bookstore_publisher"."id",
"bookstore_publisher"."name",
"bookstore_publisher"."owner_id",
"auth_us... | 70b991a56b30e8ba0847ca6a69b64c8d44647bd1 | 3,623,260 |
import types
def is_variable(tup):
""" Takes (name, object) tuple, returns True if it is a variable.
"""
name, item = tup
# callable()
# 函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;
# 但如果返回False,调用对象ojbect绝对不会成功。
# 对于函数, 方法, lambda 函式, 类, 以及实现了 __call__
# 方法的类实例, 它都返回 True。
if callab... | 81055d1ed252160c417b386c875e818b87780f14 | 3,623,261 |
def _Solve_Amplitude(data, ufit, error=None) :
""" Compute the amplitude needed to normalise the 1d profile which minimises
the Chi2, given a x array, data and an error array
The calculation follows a simple linear optimisation using
Ioptimal = (dn x dn / dn x fn)
where dn i... | ccf513130dd8631acc61e88a328645243bdf7f94 | 3,623,263 |
def generate_ethmac(peripheral, shadow_base, **kwargs):
""" Generates definition of 'ethmac' peripheral.
Args:
peripheral (dict): peripheral description
shadow_base (int or None): shadow base address
kwargs (dict): additional parameters, including 'buffer'
Returns:
string: ... | e0c34117c972fb007ec9b322a48f54fcdad6c8ab | 3,623,264 |
def pix_centers(geoTransform, rows, cols, make_grid=True):
""" provide the pixel coordinate from the axis, or the whole grid
Parameters
----------
geoTransform : tuple, size=(6,1)
georeference transform of an image.
rows : integer
amount of rows in an image.
cols : integer
... | 05ad408b99c70c554eb42300e0d7cdd19630817f | 3,623,265 |
from typing import List
def rhymes(input_val: str_or_list_of_str, sample_size=None) -> List[str]:
"""Return a list of rhymes in randomized order for a given word if at least one can be found using the pronouncing
module (which uses the CMU rhyming dictionary).
:param input_val: the word or words in relat... | 71366876027efaf5ab43f7fe1e765aaad068825d | 3,623,266 |
async def logout():
"""Clear the current session, including the stored user id."""
logout_user()
return redirect(url_for("index")) | cc944f1069cf87d7b6cc94a44dde94e91efba369 | 3,623,267 |
from typing import Any
def delete_user_class(user_class_id: int) -> flask.Response:
"""
Create a new user class. Requires the ``userclasses_modify`` permission.
.. :quickref: UserClass; Delete user class.
**Example request**:
.. parsed-literal::
PUT /user_classes HTTP/1.1
{
... | acb7327231ff15473ada1906da75452c04c1a555 | 3,623,268 |
def ajax_form_errors(errors):
""" returns form errors as python list """
errs = [{'key': k, 'msg': unicode(errors[k])} for k in errors.keys()]
#equivalent to
#for k in form.errors.keys():
# errors.append({'key': k, 'msg': unicode(form.errors[k])})
return errs | 678c47de36d3f72c37acb394aff02b6c3f1253b6 | 3,623,269 |
def sanitize_html(html, bad_tags=['body']):
"""Removes identified malicious HTML content from the given string."""
if html is None or html == '':
return html
cleaner = Cleaner(style=False, page_structure=True, remove_tags=bad_tags,
safe_attrs_only=False)
return cleaner.clea... | 260f01804b720de97406c3f277a91c17c360ccab | 3,623,271 |
from typing import Optional
def create_base_map(
move_data: DataFrame,
lat_origin: Optional[float] = None,
lon_origin: Optional[float] = None,
tile: Optional[Text] = TILES[0],
default_zoom_start: Optional[float] = 12,
) -> Map:
"""
Generates a folium map.
Parameters
----------
... | f5be52152234747469bb20357cba65f9c2b2f7cd | 3,623,272 |
from typing import Callable
import operator
def when(condition: Callable, f_true: Callable) -> Callable:
"""Returns `f_true(args)` if `condition(args)` returns true, else returns args.
>>> f = when(gamla.greater_than(5), lambda i: -i)
>>> f(6)
'-6'
>>> f(3)
'3'
"""
return ternary(cond... | 0fa5b4ae94910624a42f2da86d7c45be516f9cc4 | 3,623,273 |
from typing import Dict
def check_use_speech_in_inference(tts: AbsTTS, decode_config: Dict) -> bool:
"""Check whether to require speech in inference.
Args:
tts (AbsTTS): TTS model instance.
decode_config (Dict): Decoding config dictionary.
Returns:
bool: True if speech is require... | 147a144dc326a3eea3017f288dde24111dc44569 | 3,623,274 |
def f56a():
"""Return a unit-distance embedding of the F56A graph.
Note that MathWorld's LCF notation for this is incorrect;
it should be [11, 13, -13, -11]^14."""
t = tan(pi/14)
u = sqrt(polyval([-21, 98, 71], t*t))
z1 = 2*sqrt(14*polyval([31*u, -20, -154*u, 104, 87*u, -68], t))
z2 = 7*t*(t... | c5c0b0ac623858fc23005b82e81a9d3ca21834c4 | 3,623,275 |
def _nova_to_osvif_route(route):
"""Convert Nova route object into os_vif object
:param route: nova.network.model.Route instance
:returns: os_vif.objects.route.Route instance
"""
obj = objects.route.Route(
cidr=route['cidr'])
if route['interface'] is not None:
obj.interface =... | 2c6c3ae48f7c58e5b88404844e8a7ad4bc24fde7 | 3,623,276 |
import torch
def recall(pred, target):
"""Calculate macro-averaged recall according to the prediction and target
Args:
pred (torch.Tensor | np.array): The model prediction.
target (torch.Tensor | np.array): The target of each prediction.
Returns:
float: The function will return a... | a4b0852f4a66fdabee0ef2fee8f29fdb8ceda7db | 3,623,277 |
from typing import Union
def fetch_dataset_as_namedtuple(dataset_id: int, target: str,
read_csv_kwargs: dict,
load_dataframe: bool,
) -> Union[DatasetAll, DatasetInfoOnly]:
"""
Takes a dataset identifier, a target ... | 489106701c5f016cd6c25ff1a60b44491990ef8d | 3,623,279 |
def mps_to_kmph(mps):
"""
Transform a value from meters-per-second to kilometers-per-hour
"""
return mps * 3.6 | fee133def1727801e5e473d3ffb2df6c7e733a04 | 3,623,280 |
from typing import List
def get_comparison_data(data_type: str, similar: List[str]):
"""Screener Overview
Parameters
----------
data_type : str
Data type between: overview, valuation, financial, ownership, performance, technical
Returns
----------
pd.DataFrame
Dataframe w... | 7d736b666a98edacdfaa69e8894ba5782158901f | 3,623,281 |
def common_params(task_instance, task_cls):
"""
Grab all the values in task_instance that are found in task_cls.
"""
if not isinstance(task_cls, task.Register):
raise TypeError("task_cls must be an uninstantiated Task")
task_instance_param_names = dict(task_instance.get_params()).keys()
... | 3d9fd8e4d6aad9a04841fe1338d51bcf9b968a96 | 3,623,282 |
def two_ammonia_fake_print(ammonia_fake) -> (oechem.OEMol, oechem.OEMol):
"""
Returns two fingerprints for ammonia molecules with fake Wiberg bond
orders
"""
fingerprint1 = danceprops.DanceFingerprint(ammonia_fake[1], 0.05)
fingerprint2 = danceprops.DanceFingerprint(ammonia_fake[1], 0.05)
re... | e7e7ccc44b7beea1f78a33ea7779438e02473574 | 3,623,283 |
def imread(path, grayscale=False, size=None, interpolate="bilinear",
channel_first=False, as_uint16=False, num_channels=-1, **kwargs):
"""
Read image from ``path``.
If you specify the ``size``, the output array is resized.
Default output shape is (height, width, channel) for RGB image and (he... | d647b8248a40de6a254303db9ac06046fbbd5e23 | 3,623,284 |
import logging
import ssl
def get_client(project_id, cloud_region, registry_id, device_id, private_key_file,
algorithm, ca_certs, mqtt_bridge_hostname, mqtt_bridge_port):
"""Create our MQTT client. The client_id is a unique string that identifies
this device. For Google Cloud IoT Core, it must be i... | 7e135739b7eaf87f8a761a1b7eebea61febef727 | 3,623,285 |
def heat_diffusion(heat, laplacian, start=0, end=0.1):
"""Heat diffusion
Iterative matrix multiplication between the graph laplacian and heat
"""
out_vector=expm_multiply(
-laplacian,
heat,
start=start,
stop=end,
endpoint=True
)[-1]
return out_vect... | a308f8719ec340435751ac32fd7ca1fb176b8374 | 3,623,287 |
import inspect
def behavior(instance_mode="session", instance_creator=None):
"""
Decorator to specify the server behavior of your Pyro class.
"""
def _behavior(clazz):
if not inspect.isclass(clazz):
raise TypeError("behavior decorator can only be used on a class")
if instan... | 748817411f58cdbce66b2cacdaf0a642183c7963 | 3,623,288 |
import torch
def gt2out(gt_bboxes_list, gt_labels_list, inp_shapes_list, stride, categories):
"""transform ground truth into output format"""
batch_size = len(gt_bboxes_list)
inp_shapes = gt_bboxes_list[0].new_tensor(inp_shapes_list, dtype=torch.int)
output_size = inp_shapes[0] / stride
height_rat... | da3636776f75abc53cc790e0ffd6871fc6a1d7ca | 3,623,289 |
import time
import hashlib
def get_wx_js_sdk_config():
"""
获取微信JS-SDK权限验证配置
:return:
"""
url = request.args.get('url')
claim_args(1201, url)
appid = current_app.config['INTERVAL_APPID']
wx_authorizer = WXAuthorizer.query_by_appid(appid)
jsapi_ticket = wx_authorizer.get_jsapi_ticket... | 46daffecd53d08945dc601368a3a0291c85bd7fc | 3,623,291 |
def get_reviewer_by_id(reviewerID): # noqa: E501
"""Get a Reviewer by ID
# noqa: E501
:param reviewerID: ID of Reviewer
:type reviewerID: int
:rtype: List[Reviewer]
"""
results = _globals.pgapi.get(
'Reviewers',
clause=f'WHERE reviewerID={reviewerID}'
)
if type... | 72564cd627c1ccc3c384e5df2539c893b67e931d | 3,623,292 |
def get_quats(tpf=None, camera=None, sector=None, time=None, dt=None):
"""Get an array of the quaternions, at the time resolution of the input TPF"""
if (tpf is None) and (camera is None) and (sector is None):
raise ValueError('set either TPF or camera/sector')
if camera is None:
camera = tp... | 99f6b9093e24528a353618ac1f2fbe4606bc02c0 | 3,623,293 |
def create_list_id_title(sheets: list) -> list:
"""
Args:
this function gets a list of all the sheets of a spreadsheet
a sheet is represented as a dict format with the following fields
"sheets" : [
{
"properties": {
... | a32d2cbfce6f06d326f49e69983e05e67bfc1697 | 3,623,294 |
import types
import scipy
def qng(qc: qiskit.QuantumCircuit, thetas: np.ndarray, create_circuit_func: types.FunctionType, **kwargs):
"""Calculate G matrix in qng
Args:
- qc (qiskit.QuantumCircuit)
- thetas (np.ndarray): parameters
- create_circuit_func (FunctionType)
- num_lay... | 4c7433f96c7a4ce36ea6e20d0c82e189e725e611 | 3,623,295 |
def horizontal_projection(img_matrix):
"""
Function that calculate the angle rotation according to the Hough Transform technique
:param img_matrix: A list of ints with the matrix of pixels of the image
:return: rotateAngle: angle of rotation
"""
try:
img_grey = cv2.cvtColor(img_matrix... | 3eb7596a4f082300216fa4d7b3a87983aeee2b11 | 3,623,296 |
def fit_lfm_pcfp(x, p, sig2, k_):
"""For details, see here.
Parameters
----------
x : array, shape (t_, n_)
p : array, shape (t_,)
sig2 : array, shape (t_, t_)
k_ : scalar
Returns
-------
alpha_PC : array, shape (n_,)
beta_PC : array, shape (n_, k_)
... | 9154045af81561b20a83394f0f03bcb9b27719c3 | 3,623,298 |
def _generate_is_in_range(message):
"""Generate range checks for all signals in given message.
"""
signals = []
for signal in message.signals:
scale = signal.decimal.scale
offset = (signal.decimal.offset / scale)
minimum = signal.decimal.minimum
maximum = signal.decima... | 2fc3e9939cb6225d4e6fb405efb4dd323e698179 | 3,623,299 |
def computeRealExpectation(params1, params2, angles, backend):
"""
Computes the real part of the inner product of the
quantum states produced by acting with U(θ)
characterised by two sets of parameters, params1 and
params2.
"""
qreg = QuantumRegister(2)
anc = QuantumRegister(1)
creg ... | 5a800a7f543c4d54e58d3d4a122fa3b428bd67a2 | 3,623,300 |
def green_on_black(string, *funcs, **additional):
"""Text color - green on background color - black. (see sgr_combiner())."""
return sgr_combiner(string, ansi.GREEN, *funcs, attributes=(ansi.BG_BLACK,)) | 50311029d1659d09ade8a9cb6b5eff191bcc7424 | 3,623,301 |
from typing import List
from typing import Any
def format_params_diff(parameter_diff: List[DictValue[Any, Any]]) -> str:
"""Handle the formatting of differences in parameters.
Args:
parameter_diff: A list of :class:`DictValue` detailing the differences
between two dicts returned by :func:... | 85022afae55b7b06715d0bf675e29db1f129ecda | 3,623,302 |
import hashlib
import gzip
def hashfile(path, hasher=None, blocksize=65536):
"""
A function to hash files.
See: http://stackoverflow.com/questions/3431825
"""
if hasher is None: hasher = hashlib.md5()
try:
try:
f = gzip.open(path, "rb")
buf = f.read(blocksize... | 44946dfa3eeb1c82353b3470423a3a4f699c1d9d | 3,623,303 |
def EditFragNeighborIds(fnids: list, bbtps: list) -> list:
"""Remove fragment neighbor ids that are doubly/triply bonded to fragment."""
# not double/triple bonds
n23bonds = [
[
(x != Chem.rdchem.BondType.DOUBLE and x != Chem.rdchem.BondType.TRIPLE)
for x in y
]
... | 655e229422ac0b212e35bc43fea3a65372a0e666 | 3,623,304 |
def db_add_game(game: str, channel: str, set_default_game: bool=False) -> bool:
"""Adds a game to the database for a channel, does not allow duplicates
"""
if not db_check_for_duplicate(game, channel):
return False
else:
if set_default_game:
default = "YES"
else:
... | ab47a57f94428afe84c45d6ed4d1608079562bd8 | 3,623,305 |
def _proxy_for_evolvable_object(obj):
"""
:returns: an ``_IRecursiveEvolverProxy`` suitable for the type of ``obj``.
"""
if not _IEvolvable.providedBy(obj):
raise TypeError(
"{!r} does not provide {}".format(
obj,
_IEvolvable.__name__
)
... | c5c71484e392cf387cc4259c3c3c2df13385b60d | 3,623,307 |
from typing import List
def parse_download_data(data: List[AnimeThemeAnime]) -> List[DownloadData]:
"""
Parses a list of animethemes api returns for anime.
Returns download data.
"""
out = []
songs = set()
for anime in data:
last_group = None
for tracknumber,t... | b91db9b9eb5c0c34fe7dcf6b03e64ea7e0976cbb | 3,623,309 |
def parse_glyphs_groups(names, groups):
"""
Parse a ``gstring`` and a groups dict into a list of glyph names.
"""
glyph_names = []
for name in names:
# group names
if name[0] == '@':
group_name = name[1:]
if group_name in groups:
glyph_names +... | 50e79acffdc6d26576e8524b52219afad3e40a4e | 3,623,310 |
from typing import Sequence
from typing import Mapping
def ensure_strings_have_quotes_sequence(sequence_object):
"""Ensures Sequence objects have quotes on string entries.
Args:
sequence_object (iter): A python iterable object to ensure strings have quotes.
Returns:
iter: The ``sequence_... | a0299f52b4d16816a00002fbc8ef14f64645ac2c | 3,623,311 |
import json
def patient_detail(request, pk):
"""
View to display patient details (name, ID, fractions)
"""
patient = get_object_or_404(Patient, pk=pk)
fractions = Fraction.objects.filter(patient=pk)
url = 'doseapp/static/doseapp/tolerances.json'
json_data = open(url)# False
tolerances ... | 91518c26e092f75024689d29be586472252f4652 | 3,623,313 |
def event_fixture():
"""Return a received event from the websocket client."""
return {
"type": "event",
"event": {
"source": "node",
"event": "value updated",
"nodeId": 52,
"args": {
"commandClassName": "Basic",
"com... | 4866641f285ca65003c3dada9c2f406ae2f5d218 | 3,623,314 |
def tf_idf(train_data, test_data, weight_type, sentence_type):
"""
:param train_data:
:param test_data:
:param weight_type:
:param sentence_type:
:return:
"""
tfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2),max_df=0.9, min_df=3, use_idf=1, smooth_idf=1, sublinear_tf=1)
# tfidf_... | 22cd362dc350a2039c919233d9a799d40c413e25 | 3,623,317 |
def receive_product_view(sender, product, user, request, response, **kwargs):
"""
Receiver to handle viewing single product pages
Requires the request and response objects due to dependence on cookies
"""
return CustomerHistoryManager.update(product, request, response) | 880954a38b79fc7a3443d015a22758c503fb28bb | 3,623,319 |
from typing import Union
from typing import List
from datetime import datetime
def bulk_create_entries(
es_client: elasticsearch.Elasticsearch,
es_index: Union[str, UUID],
journal_id: Union[str, UUID],
entries: List[JournalEntryResponse],
) -> str:
"""
Index a new entry in a journal. Returns t... | 24ea4c618feac971f05b3a795b81bfaa5b943068 | 3,623,320 |
def norm_density(matrix: np.ndarray):
"""
Calculate normalized density for a given activity matrix.
:param matrix: activity matrix
:return: normalized density value
"""
return 1 - abs(1 - 2 * (np.count_nonzero(matrix) / matrix.size)) | a6fed6febc697cc84d1691b9f95dbb04cd6eba9e | 3,623,321 |
def kernel(a, b, length_scale=1.):
""" GP squared exponential kernel """
n = a.shape[0]
m = b.shape[0]
K = np.zeros(shape=(n, m), dtype=float)
for i in np.arange(n):
for j in np.arange(m):
dif = a[i, :] - b[j, :]
sqdist = dif * dif.T
if sqdist.shape[0] != ... | e15d1c755ed607dae5046d5f2ebee01e7ffaf808 | 3,623,322 |
def str_id(qualified_name):
"""Return PROVN representation of a URI qualified name.
Params
------
qualified_name : QualifiedName
Qualified name for which to return the PROVN
string representation.
"""
return qualified_name.provn_representation().replace("'", "") | ff1cf6614a098818e8a70de105d7bfb7810548dc | 3,623,323 |
def detect(text_proposals, scores, size):
"""
Detect text boxes
Args:
text_proposals(numpy.array): Predict text proposals.
scores(numpy.array): Bbox predicts scores.
size(numpy.array): Image size.
Returns:
boxes(numpy.array): Text boxes after connect.
"""
keep_pr... | 6030a0e859c2fabc4ca6ad89470fca0da937be0e | 3,623,324 |
import requests
from bs4 import BeautifulSoup
def GetImage():
"""
获得Bing壁纸
"""
url = 'https://cn.bing.com'
# 请求标头
# 获取页面并转为dict格式
req = requests.get(url=url)
req.encoding = req.apparent_encoding
soup = BeautifulSoup(req.text, 'html.parser') # 用BeautifulSoup库解析网页
head = soup.he... | e451628d54b5ae7894d1dbbd9339e98c6e3dad37 | 3,623,325 |
def csr_load(data, prefix=None):
"""
Rematerialize a CSR matrix from loaded data. The inverse of :py:func:`csr_save`.
Args:
data(dict-like): the input data.
prefix(str): the prefix for the data keys.
Returns:
CSR: the matrix described by ``data``.
"""
if prefix is None... | 9899ee559e7e5e8d7dcf5aceab6bde895127e5b8 | 3,623,326 |
def perc_range(n, min_val, max_val, rounding=2):
"""
Return percentage of `n` within `min_val` to `max_val` range. The
``rounding`` argument is used to specify the number of decimal places to
include after the floating point.
Example::
>>> perc_range(40, 20, 60)
50
"""
ret... | 379515f6c0483b4bfed93d0c1012bb2ca111e410 | 3,623,327 |
def _translate_tag_class(tag_class):
""" Translate ASN.1 tag class names to pyasn1 equivalents.
Defaults to tag.tagClassContext if tag_class is not
recognized.
"""
return _ASN1_TAG_CONTEXTS.get(tag_class, 'tag.tagClassContext') | 6abe7ce27b0904d1767a561ec403816bdc45c0b1 | 3,623,329 |
def memo(f):
"""Memoization for function $f$"""
cache = {}
@wraps(f)
def wrap(*args):
if args not in cache:
cache[args] = f(*args)
return cache[args]
return wrap | 084f6bbd212b25694ea512ba4c407085b4a2ca04 | 3,623,330 |
def expand_nested_tasks_or_globs(p, tasksglobs_to_filenames):
"""
Expand globs and tasks "in-line", unless they are the top level, in which case turn
it into a list
N.B. Globs are only expanded if they are in tasksglobs_to_filenames
This function is called for @split descriptors which leave ou... | 949f1c9f221c21470ba6f476f58a36a9e4ee35ce | 3,623,331 |
from typing import List
def process_experience(
experience: List[List[agent.ExpTuple]],
actor_steps: int,
num_agents: int,
gamma: float,
lambda_: float):
"""Process experience for training, including advantage estimation.
Args:
experience: collected from agents in the form of nested lists... | 234adfdc0b4abc7f4eb44e85bbd159a01a3b3e6d | 3,623,332 |
def associateIpAddress(**kargs):
""" Get additional public IP in Selected Zone
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
* Examples : print(server.associateIpAddress(zone='KR-M'))
"""
my_apikey, my_secretkey = c.read_config()
if not 'zone' in kargs:
retu... | 84474d50ef8f47f7150791781c41a7b6ef86f6b4 | 3,623,333 |
def nltk_regex_tokenizer(input_dict):
"""
The Regex Tokenizer splits a string into substrings using a regular expression.
:param :param pattern: The pattern used to build this tokenizer.
(This pattern may safely contain capturing parentheses.)
:param gaps: True if this tokenizer's pattern shoul... | df4bfb4f002e6588edabef99b65e29e7226ff131 | 3,623,334 |
def get_or_create_default_gcs_bucket(options):
"""Create a default GCS bucket for this project."""
if getattr(options, 'dataflow_kms_key', None):
_LOGGER.warning(
'Cannot create a default bucket when --dataflow_kms_key is set.')
return None
project = getattr(options, 'project', None)
region = g... | bd2e905c37984eb7b75021c7ef9ce8b81baf220f | 3,623,336 |
def lab_to_xyz(image: tf.Tensor) -> tf.Tensor:
"""
Convert an image from LAB color space to XYZ color space
Parameters
----------
image: tf.Tensor
Returns
-------
tf.Tensor : LAB image
"""
l, a, b = tf.unstack(image, axis=-1)
var_y = (l + 16) / 116
var_x = a / 500 + var... | 7534222c16c8d654eaad43515af54582af54ffb3 | 3,623,337 |
def make_pairs(coords,pair_indices,offset=.01):
"""Returns list of Polygon objects, given a list of coordinates and indices.
- coords: list of [x,y] coordinates, already scaled to matplotlib axes.
- pair_indices: indices in the coordinate list that are paired.
"""
pairs = []
for fir... | 21137de57e666f0789a115467bfc1a75df5e8631 | 3,623,339 |
def medialive_multiplexes(region):
"""
Return the MediaLive Multiplexes for the given region.
Tags included.
"""
items = []
service_name = "medialive"
if region in boto3.Session().get_available_regions(service_name):
service = boto3.client(service_name, region_name=region, config=MSA... | 5cb3a57b40d44d630c4ab720290451b98e76110d | 3,623,340 |
def sort_sequence_by_key(sequence, key_name, reverse=False):
"""
often when setting up initial serializations (especially during testing),
I pass a list of dictionaries representing a QS to some fn.
That list may or may not be sorted according to the underlying model's "order" attribute
This fn sort... | fbe46c942ac35d5399450c6bba430a096e6b7503 | 3,623,342 |
from typing import Union
from typing import List
from typing import Dict
from typing import Any
def process_hdmedia(hdmedia: Union[List, Dict[Any, Any]]) -> Dict[Any, Any]:
"""Pull out the relevant HDMedia dictionary based on SAP code values
:param hdmedia (list): list of HDMedia dictionaries"""
# Note: H... | 549867a866763459f58c1f4b7e8ffd14f0b7ab0a | 3,623,343 |
def gauss_newton(x_init, model, cost_thresh=1e-9, delta_thresh=1e-9, max_num_it=10):
"""Implements nonlinear least squares using the Gauss-Newton algorithm
:param x_init: The initial state
:param model: Model with a function linearise() the returns A, b and the cost for the current state estimate.
:par... | abdb34810c1fa5d393649b8ca9ba125ec8535ad6 | 3,623,344 |
def SRCNNex(input_shape= (None, None, 3), depth_multiplier=1, multi_output=False): #33.12
"""
Implementation of SRCNNex. The kernel size of the mapping layer is increased from 1 to 5.
@ multi_output : set to True
"""
inputs = Input(input_shape, name="inputs")
# normalize value betw... | 565edc3be6e4e35af0dddf1ce2a19c96b6b2f27b | 3,623,345 |
def identity() -> GradientTransformation:
"""Stateless identity transformation that leaves input gradients untouched.
This function passes through the *gradient updates* unchanged.
Note, this should not to be confused with `set_to_zero`, which maps the input
updates to zero - which is the transform required f... | 16700a32bc9b17a6c5f7f8f64e2affb0be746740 | 3,623,346 |
def width_from_bitdefs(bitdefs):
"""
Determine how wide an binary value needs to be based on bitdefs used
to define it.
Args:
bitdefs (list(BitDef)): List of bitdefs to find max width of
Returns:
(int): Maximum width
"""
max_index = max([bitdef.end for bitdef in bitdefs])
... | 59503f335d6d427579be730806c738108091e9ed | 3,623,348 |
def _mkdir_recursive_local(uri, local=None):
"""
Recursively create local directory specified by URI.
Args:
uri: parsed URI to create.
local: local context options.
Returns:
On success: True.
On failure: False.
"""
# same as the non-recursive call
return _m... | 2902fe96a8aa8169e6a686681496e4c0a633dcb0 | 3,623,350 |
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to fi... | 41e93460afba46cafb3d88986f36312dad7c4fb9 | 3,623,352 |
def get_intersection_over_union(first_segmentation, second_segmentation):
"""
Computes intersection over union (IoU) between two segmentation maps.
Maps are binary - that is their values are 0s and 1s only.
IoU is computed between non-zero elements of both segmentation maps.
:param first_segmentatio... | d313d6117bd14fbe242697c6e28136e036981465 | 3,623,353 |
def logLikelihood(params, main_time_series, reply_time_series, verbose=False):
"""Log-likelihood object function"""
" The log-likelihood fucntion is composed with main post stream and reply post stream events "
" ... | 66e8ae4c481fe6973969656f8f0bf9de852349a9 | 3,623,354 |
def getAnglesFromDict(d):# NOTE Fails currently if dict is None
"""
Converts a dictionary to a angles of a JointState()
:param d (dict): The dictionary to be converted
:return (sensor_msgs.msg.JointState): The angles
"""
# print datapath
if d is None:
rospy.loger... | 9af5671cfa3d5e26d8a47812a57eaf85b0a0d3ad | 3,623,355 |
import string
def generate_randomkey(length):
"""Generate random key, given a number of characters"""
chars = string.ascii_letters + string.digits
return ''.join([choice(chars) for i in range(length)]) | 143d9053b3b2fdfbf02fb5e19760ba711f0585ee | 3,623,356 |
def get_vectorized_series(text_series, vectorizer):
"""
사전 훈련된 벡터화 객체를 사용해 입력 시리즈를 벡터화합니다.
:param text_series: 텍스트의 판다스 시리즈
:param vectorizer: 사전 훈련된 sklearn의 벡터화 객체
:return: 벡터화된 특성 배열
"""
vectors = vectorizer.transform(text_series)
vectorized_series = [vectors[i] for i in range(vectors... | 31c9d550d60443da41277833c2f79be66238951a | 3,623,357 |
def _gen_request_slices(**kwargs):
"""Creates a TaskRequest."""
now = utils.utcnow()
args = {
u'created_ts': now,
u'manual_tags': [u'tag:1'],
u'name': u'Request name',
u'priority': 50,
u'task_slices': [
task_request.TaskSlice(expiration_secs=30, properties=_gen_properties()),
],
... | 3874e4f6abfe3b22cd9916e20874eb54ee68fb73 | 3,623,358 |
def idm_cutin_pars(**kwargs):
""" Define the parameters for the IDM model in a cut-in scenario.
The reaction time is sampled from the lognormal distribution mentioned in
Wang & Stamatiadis (2014) if it not provided through kwargs.
:param kwargs: Parameter object that can be passed via init_simulation.... | 694da1c2635a998981168b16c77f0176aa9032c8 | 3,623,359 |
def profile(request):
"""A view handler for fetching the user's profile data."""
profile_id = begin(request)
request_id = param_or_null(request, "request_id")
cursor = connection.cursor()
cursor.execute("""SELECT p.username,
p.real_name,
p.em... | 0a9b6fe68bfd000cfe6cc0a11065609ca7eadacd | 3,623,361 |
def snapshot_stabilizer(self, label):
"""Take a stabilizer snapshot of the simulator state.
Args:
label (str): a snapshot label to report the result.
Returns:
QuantumCircuit: with attached instruction.
Raises:
ExtensionError: if snapshot is invalid.
Additional Information... | 6678c3d2f33db7073e0a3ddc97a612cf1f621f14 | 3,623,362 |
def normalise_composition(comp):
"""Normalise rows of an array to unit sum, i.e. rows are compositional vectors."""
s = comp.sum(axis=-1)
if type(s) is float:
return comp / s
return comp / s[..., np.newaxis] | e7387c5e068078aa62c64ed8dbdfab445241eecf | 3,623,363 |
from typing import Sequence
import difflib
def _validate_magics_with_black(before: Sequence[str], after: Sequence[str]) -> bool:
"""
Validate the state of the notebook before and after running nbqa with black.
Parameters
----------
before
Notebook contents before running nbqa with black
... | e6e655f2e6ea5e8d055f27e8da14cf0233c0c202 | 3,623,364 |
def segment_denoise(rec_vol, rhos):
"""This function computes the segmentation of the denoised image.
:param rec_vol: The reconstruction (np.array_like)
:param rhos: The segmentation target levels (np.array_like)
:returns: The segmented image
:rtype: np.array_like
"""
prnt_str = "Solving w... | dd9b8ebf0f25128aa1ed72eda0b31a47015ec363 | 3,623,365 |
import requests
import json
import random
def get_gelImage(tags):
"""Returns pictures from Gelbooru with given tags."""
tags = list(tags)
formatted_tags = ""
rating = ""
ratings = {
"re": "rating%3aexplicit",
"rq": "rating%3aquestionable",
"rs": "rating%3asafe"
}
... | 1ad643483d96ab53dd217b14dae6cfa5febc3d44 | 3,623,367 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.