content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def url(method):
"""对于每一个URL的请求访问装饰器,在出错时返回对应的信息"""
@wraps(method)
def error_handler(*args, **kwargs):
try:
return success(method(*args, **kwargs))
except RequestError as r:
current_app.logger.exception(r)
# 返回对应异常类的字符串文档
return failed(reason... | cb2c36981372738b6b708d4e28566d4bb8ffcd90 | 3,654,600 |
def is_abbreviation(sentence):
"""
Evaluate a word to be an abbreviation if the immediate word before the
period contains a capital letter and not a single word sentence.
"""
sentence_split = sentence.split(" ")
if len(sentence_split) == 1:
return False
elif len(sentence_split[-1]) <... | a6f6ceae5b3b9adb7817a913e80a6af86b6d27d5 | 3,654,601 |
def compose_redis_key(vim_name, identifier, identifier_type="vdu"):
"""Compose the key for redis given vim name and vdu uuid
Args:
vim_name (str): The VIM name
identifier (str): The VDU or VNF uuid (NFVI based)
identifier_type (str): the identifier type. Default type is vdu. Also vnf is... | e9a03cf9ff704fea8b9cdf75c59695568e366649 | 3,654,602 |
def calGridID(locs, id, SPLIT = 0.0005):
"""
根据城市网格编号还原经纬度信息
:param locs:
:param id:
:param SPLIT=0.05:
"""
centerincrement = SPLIT/2.0
LNGNUM = int((locs['east'] - locs['west']) / SPLIT + 1)
latind = int(id / LNGNUM)
lngind = id - latind * LNGNUM
lat = (locs['south'] + latind * SPLIT)
lng = (locs['... | 8df119ff82bc1d3c14dbdfe358af6d956d6a52a2 | 3,654,603 |
def linear(x, *p):
"""[summary]
Arguments:
x {[type]} -- [description]
Returns:
[type] -- [description]
"""
return p[0] * x + p[1] | 07ef5fc7c5e78148528cccd09fe14c37cad22ead | 3,654,604 |
def convert_price_text(t):
"""
convert "$175/month' to 175
:param t:
:return: price, unit (i.e. 175, 'month')
"""
tok = t.split('$')[1]
if '/' in tok:
price, unit = tok.split('/')
else:
price = tok
unit = None
return float(price.strip().strip('$').replace(',... | b42d26dcd4eb1b2c2f8c5a63ddc9d48469e30a52 | 3,654,605 |
async def async_setup(hass, config):
"""Set up the WWLLN component."""
if DOMAIN not in config:
return True
conf = config[DOMAIN]
latitude = conf.get(CONF_LATITUDE, hass.config.latitude)
longitude = conf.get(CONF_LONGITUDE, hass.config.longitude)
identifier = '{0}, {1}'.format(latitud... | 3f0a4f5a017340780c8c1122425804e7862c3d0f | 3,654,606 |
from typing import Any
def __are_nearly_overlapped(
plane_predicted: NDArray[Any, np.int32],
plane_gt: NDArray[Any, np.int32],
required_overlap: np.float64,
) -> (bool, bool):
"""
Calculate if planes are overlapped enough (required_overlap %) to be used for PP-PR metric
:param required_overlap... | 7b686e7bb4b18e4e2e116cdfd14878acbcc4c92d | 3,654,607 |
def _get_prob_k_given_L(B, N=None):
"""
Helper function.
"""
if N is None:
N = int(B[0, 1])
return B / N | be1d0848b148b3413aaee2c5549bd6063e1f2d33 | 3,654,608 |
def base64_encode(s):
"""unicode-safe base64
base64 API only talks bytes
"""
if not isinstance(s, bytes):
s = s.encode('ascii', 'replace')
encoded = encodebytes(s)
return encoded.decode('ascii') | 6ef0722014aa56e22de102aa0ce8286416640f86 | 3,654,609 |
def _unpack_tableswitch(bc, offset):
"""
function for unpacking the tableswitch op arguments
"""
jump = (offset % 4)
if jump:
offset += (4 - jump)
(default, low, high), offset = _unpack(_struct_iii, bc, offset)
joffs = list()
for _index in xrange((high - low) + 1):
j, ... | af08ab85def5bf132227f20da8cb6032e2a9dff1 | 3,654,610 |
def force_orders(self, **kwargs):
"""User's Force Orders (USER_DATA)
GET /fapi/v1/forceOrders
https://binance-docs.github.io/apidocs/futures/en/#user-39-s-force-orders-user_data
Keyword Args:
symbol (str, optional)
autoCloseType (str, optional): "LIQUIDATION" for liquidation orders, ... | 6e848820e17e54df0f275ec4087d9c609d4e08fa | 3,654,611 |
def prosp_power_analysis_norm(d, sigma, pow_lev, alpha, direction):
"""
This function conducts pre-testing power analysis and
calculates the minimally required sample size for a normal sample.
@param d: difference between the mean differences under H1 and H0
@param sigma: standard deviation
@pa... | 319daf6434b774dcf3bf3f6f936a566e1640c175 | 3,654,612 |
def decision_tree_construction(examples, target_attribute, attributes, depth):
"""
:param examples: The data we will use to train the tree(x)
:param target_attribute: The label we want to classify(y)
:param attributes: The number(index) of the labels/attributes of the data-set
:return: The tree cor... | c9529deb71d3c0a89bbae053aae07e587d277255 | 3,654,613 |
import numpy
def mass_centered(geo):
""" mass-centered geometry
"""
geo = translate(geo, numpy.negative(center_of_mass(geo)))
return geo | 1081141d77383f857f986031fa03510fd2608741 | 3,654,614 |
def binaryMatrix(l, value=PAD_token):
"""
:param l:
:param value:
:return: seq: [3,4,5,0,0]
m: [[1],[1],[1],[0],[0]]
"""
m = []
for i, seq in enumerate(l):
m.append([])
for token in seq:
if token == PAD_token:
m[i].append(0)
... | 3c123b1ce8531bcde7c6673f8ca8a91f1300f0bb | 3,654,615 |
def load_map(mappath):
""" Attempt to load map with known loaders
"""
data = None
shirtloader = lambda path: fio.load_map(path)[0][0:3]
maploaders = [load_pfire_map, shirtloader]
for loader in maploaders:
try:
data = loader(mappath)
except (ValueError, OSError):
... | 2ab5c46e0b1ec0ed2e613b42c0553a1d6bcede36 | 3,654,616 |
def ifttt_account_options_topup_source():
""" Option values for topup source account selection"""
return ifttt_account_options(False, "Internal") | 83a0082ccc829c06c12fca2bb588db31468f51ef | 3,654,617 |
from bs4 import BeautifulSoup
def strip_classes(soup:BeautifulSoup, *args:str):
"""
Strip class from given tags in a BeautifulSoup object.
Args:
soup (BeautifulSoup): soup to clean
args ([str]): A list of tags to be unclassed
Returns:
soup (BeautifulSoup)
Modules:
... | c2195cd0eaf2cb3f741247b75411d252c7a85e8c | 3,654,618 |
import trace
def take_measurement(n_grid: np.int, n_rays: np.int, r_theta: np.float64) -> (
np.ndarray, np.ndarray, np.ndarray, np.ndarray):
"""
Take a measurement with the tomograph from direction r_theta.
Arguments:
n_grid: number of cells of grid in each direction
n_rays: number of parallel r... | f0ffac9da088402cff126bab9ee880ff33c460f1 | 3,654,619 |
def chrom_karyo_sort(chroms):
"""
:param chroms:
:return:
"""
ordered = []
unordered = []
for cname, size in chroms:
try:
ord = int(cname.lower().strip('chr'))
ordered.append((cname, size, ord * 10))
except ValueError:
ord = check_special_c... | 4531be10ad0c51e0257089aabda778357b2d7950 | 3,654,620 |
from typing import List
def calibrate_stereo(observations_left: List, observations_right: List, detector: FiducialCalibrationDetector,
num_radial: int = 4, tangential: bool = False, zero_skew: bool = True) -> (StereoParameters, List):
"""
Calibrates a stereo camera using a Brown camera mo... | bf9ee5b369f8614728db0023674c85a958a2559f | 3,654,621 |
from typing import Type
def register_producer_class(cls: Type[C]) -> Type[C]:
"""Registers the producer class and returns it unmodified."""
if not cls.TYPES:
raise ProducerInterfaceError(
f"Invalid producer. When defining producer, make sure to specify at least 1 type in the TYPES class va... | 7155ddb85077e2774fcc20c2d80345bd52ee86b1 | 3,654,622 |
import glob
import os
def get_file_list(var, obsname, start_date, end_date):
"""
Get a list of data set files that covers the time period defined by
start_date and end_date provided in the function call.
Parameters
----------
var: str
Input variable, e.g. 'tas'
obsname: str
... | de9780faca7830a7c26864f57b077e75eb1c7246 | 3,654,623 |
def structures_at_boundaries(gdf, datamodel, areas, structures, tolerance, distance):
"""
Check if there are structures near area (typically water-level areas) boundaries.
Parameters
----------
gdf : ExtendedGeoDataframe
ExtendedGeoDataFrame, HyDAMO hydroobject layer
datamodel : HyDAMO
... | 6f1c83f2ac02b6773bf51f64326ed4f6e3c7c354 | 3,654,624 |
from typing import List
from typing import Tuple
from typing import Union
def above_cutoff(gene_freq_tup_list: List[Tuple[Union[str, tuple], Tuple[str, str]]], cutoff: int) -> List[str]:
"""Return the genes/edges that are are in at least the given cutoff's networks
Parameters
----------
gene_freq_tup... | c5679743d0b87fcbf7b6955a755aa8bbb11f5f95 | 3,654,625 |
def normalizeWindows(X):
"""
Do point centering and sphere normalizing to each window
to control for linear drift and global amplitude
Parameters
----------
X: ndarray(N, Win)
An array of N sliding windows
Returns
XRet: ndarray(N, Win)
An array in which the mean of each r... | 013b5829153ee21979bcf9dac8457beb1adbe2a2 | 3,654,626 |
import torch
def cost_matrix_slow(x, y):
"""
Input: x is a Nxd matrix
y is an optional Mxd matirx
Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:]
if y is not given then use 'y=x'.
i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2
"""
x_norm =... | c27889346d6fb1a075eabf908f5e56ececb554d0 | 3,654,627 |
def get_dists(ts1_sax, ts2_sax, lookup_table):
"""
Compute distance between each symbol of two words (series) using a lookup table
ts1_sax and ts2_sax are two sax representations (strings) built under the same conditions
"""
# Verify integrity
if ts1_sax.shape[0] != ts2_sax.shape[0]:
ret... | 3da21a1c57952225326c97bb7a58238545131e94 | 3,654,628 |
def get_dom_coords(string, dom):
"""Get Coordinates of a DOM specified by the string and dom number.
Parameters
----------
string : int
String number (between 1 and 86)
dom : int
DOM number (between 1 and 60)
Returns
-------
tuple(float, float, float)
The x, y, ... | 08e0817ab85e71caa38e6c247e1cc488d03ce1c0 | 3,654,629 |
def relevance_ka(x):
"""
based on code from https://www.kaggle.com/aleksandradeis/regression-addressing-extreme-rare-cases
see paper: https://www.researchgate.net/publication/220699419_Utility-Based_Regression
use the sigmoid function to create the relevance function, so that relevance function
has ... | e056c8ae1b1c527dc1a875c201967eacf914d7e0 | 3,654,630 |
from datetime import datetime
def now(mydateformat='%Y%m%dT%H%M%S'):
""" Return current datetime as string.
Just a shorthand to abbreviate the common task to obtain the current
datetime as a string, e.g. for result versioning.
Args:
mydateformat: optional format string (default: '%Y... | f4f98116700888a4be273143d635c62859c96e03 | 3,654,631 |
import os
def getOnePackageInfo(pkgpath):
"""Gets receipt info for a single bundle-style package"""
pkginfo = {}
plist = getBundleInfo(pkgpath)
if plist:
pkginfo['filename'] = os.path.basename(pkgpath)
try:
if 'CFBundleIdentifier' in plist:
pkginfo['packagei... | 5161eaf806a0f616814c92d2b9693a02c16bdff4 | 3,654,632 |
from datetime import datetime
def cmp_point_identities(a, b):
"""
Given point identities a, b (may be string, number, date, etc),
collation algorithm compares:
(a) strings case-insensitively
(b) dates and datetimes compared by normalizing date->datetime.
(c) all other types use __cmp_... | 475206398fc0c2f301446c5c264bf67d1671a2ad | 3,654,633 |
def shortest_complement(t, m, l):
"""
Given a primitive slope t and the holonomies of the current
meridian and longitude, returns a shortest complementary slope s
so that s.t = +1.
"""
c, d = t # second slope
_, a, b = xgcd(d, c) # first slope
b = -b
assert a*d - b*c == 1
return ... | 4653a7eac7af7ed8a67ce298f1453236cfeabf73 | 3,654,634 |
def run_pii(text, lang):
"""
Runs the given set of regexes on the data "lines" and pulls out the
tagged items.
The lines structure stores the language type(s). This can be used for
language-specific regexes, although we're dropping that for now and using
only "default"/non-language-specific regexes.
"""
... | e9f34686be27773952f64a9231e86c76c0170483 | 3,654,635 |
def get_ref_cat(butler, visit, center_radec, radius=2.1):
"""
Get the reference catalog for the desired visit for the requested
sky location and sky cone radius.
"""
ref_cats = RefCat(butler)
try:
band = list(butler.subset('src', visit=visit))[0].dataId['filter']
except dp.butlerExce... | d2814729aeb775668d6eff6fdc68a0676168b16e | 3,654,636 |
def replace_dict(d, **kwargs):
"""
Replace values by keyword on a dict, returning a new dict.
"""
e = d.copy()
e.update(kwargs)
return e | be1cc21be5320eeea13307dd4ed5025b51339eec | 3,654,637 |
def pageHeader(
headline="",
tagline=""):
"""
*Generate a pageHeader - TBS style*
**Key Arguments:**
- ``headline`` -- the headline text
- ``tagline`` -- the tagline text for below the headline
**Return:**
- ``pageHeader`` -- the pageHeader
"""
pageHeade... | 7d9e91df8af2fff92b0b7096cd1a13198d899e15 | 3,654,638 |
def get_counter_merge_suggestion(merge_suggestion_tokens):
"""Return opposite of merge suggestion
Args:
merge_suggestion_tokens (list): tokens in merge suggestion
Returns:
str: opposite of merge suggestion
"""
counter_merge_suggestion = ' '.join(merge_suggestion_tokens)
if merg... | e32e0f1b64fe77acaa8d88d72dca9304b7427674 | 3,654,639 |
import re
from datetime import datetime
import pytz
def parse_rfc3339_utc_string(rfc3339_utc_string):
"""Converts a datestamp from RFC3339 UTC to a datetime.
Args:
rfc3339_utc_string: a datetime string in RFC3339 UTC "Zulu" format
Returns:
A datetime.
"""
# The timestamp from the Google Operation... | 04653bd5673c5ca7713c9e6014947886781f3f5e | 3,654,640 |
from datetime import datetime
def response(code, body='', etag=None, last_modified=None, expires=None, **kw):
"""Helper to build an HTTP response.
Parameters:
code
: An integer status code.
body
: The response body. See `Response.__init__` for details.
etag
: A value for the ET... | 094e7dc99114d4b742808c0aa123001fb301fb14 | 3,654,641 |
def oauth2callback():
"""
The 'flow' has this one place to call back to. We'll enter here
more than once as steps in the flow are completed, and need to keep
track of how far we've gotten. The first time we'll do the first
step, the second time we'll skip the first step and do the second,
and so on.
"""
... | 07c232275ad93d2b8d47a6d0b7de03f57fa356c8 | 3,654,642 |
from datetime import datetime
import click
def parse_tweet(raw_tweet, source, now=None):
"""
Parses a single raw tweet line from a twtxt file
and returns a :class:`Tweet` object.
:param str raw_tweet: a single raw tweet line
:param Source source: the source of the given tweet
... | 85f90ce469091cc82dd120e6c100859f8bcc8f2c | 3,654,643 |
import requests
def scopes(request, coalition_id):
"""
Update coalition required scopes with a specific set of scopes
"""
scopes = []
for key in request.POST:
if key in ESI_SCOPES:
scopes.append(key)
url = f"{GLOBAL_URL}/{coalition_id}"
headers = global_headers(reque... | 71d07be26815a8e30ed37074b4452fa7574d07b5 | 3,654,644 |
def recursive_dictionary_cleanup(dictionary):
"""Recursively enrich the dictionary and replace object links with names etc.
These patterns are replaced:
[phobostype, bpyobj] -> {'object': bpyobj, 'name': getObjectName(bpyobj, phobostype)}
Args:
dictionary(dict): dictionary to enrich
... | b49798dd1918401951bae57e544406ee1d14ebd6 | 3,654,645 |
def validate_dtype(dtype_in):
"""
Input is an argument represention one, or more datatypes.
Per column, number of columns have to match number of columns in csv file:
dtype = [pa.int32(), pa.int32(), pa.int32(), pa.int32()]
dtype = {'__columns__': [pa.int32(), pa.int32(), pa.int32(), pa.int32()]}
... | 274df2e010314867f31c14951f1e0b18190218ad | 3,654,646 |
import os
import sys
def get_secret(name):
"""Load a secret from file or env
Either provide ``{name}_FILE`` or ``{name}`` in the environment to
configure the value for ``{name}``.
"""
try:
with open(os.environ[name + "_FILE"]) as secret_file:
return secret_file.read().strip()
... | 3b240f7b494c7817f58c8ab3f7f9000ff7f85844 | 3,654,647 |
from typing import Callable
from re import T
from typing import List
from typing import Any
from typing import Dict
def cache(
cache_class: Callable[[], base_cache.BaseCache[T]],
serializer: Callable[[], cache_serializer.CacheSerializer],
conditional: Callable[[List[Any], Dict[str, Any]], bool... | c4d5318d471e13f5001eb12b6d3dc4f278478855 | 3,654,648 |
def words2chars(images, labels, gaplines):
""" Transform word images with gaplines into individual chars """
# Total number of chars
length = sum([len(l) for l in labels])
imgs = np.empty(length, dtype=object)
newLabels = []
height = images[0].shape[0]
idx = 0;
for i, gaps... | e04bf5b1e9b47c2f930600433b4214343e067f26 | 3,654,649 |
def create_spark_session(spark_jars: str) -> SparkSession:
"""
Create Spark session
:param spark_jars: Hadoop-AWS JARs
:return: SparkSession
"""
spark = SparkSession \
.builder \
.config("spark.jars.packages", spark_jars) \
.appName("Sparkify ETL") \
.getOrCreate(... | 576072460e465610fff98da377cc20a8472c537f | 3,654,650 |
from datetime import datetime
def make_expired(request, pk):
"""
将号码状态改为过号
"""
try:
reg = Registration.objects.get(pk=pk)
except Registration.DoesNotExist:
return Response('registration not found', status=status.HTTP_404_NOT_FOUND)
data = {
'status': REGISTRATION_STATUS... | 827f45c12bcbb973eb073662d8a14765422fdf51 | 3,654,651 |
def word2vec_similarity(segmented_topics, accumulator, with_std=False, with_support=False):
"""For each topic segmentation, compute average cosine similarity using a
:class:`~gensim.topic_coherence.text_analysis.WordVectorsAccumulator`.
Parameters
----------
segmented_topics : list of lists of (int... | 1a3d439e75c4732138f42ea14e7fd50eb6e7d5cb | 3,654,652 |
def addGroupsToKey(server, activation_key, groups):
"""
Add server groups to a activation key
CLI Example:
.. code-block:: bash
salt-run spacewalk.addGroupsToKey spacewalk01.domain.com 1-my-key '[group1, group2]'
"""
try:
client, key = _get_session(server)
except Exceptio... | 346690a9eac24f62f4410b23f60bb589d174c9ed | 3,654,653 |
def get_user_for_delete():
"""Query for Users table."""
delete_user = Users.query \
.get(DELETE_USER_ID)
return delete_user | 208dbbe47550c6889848b7ff61324acf23a4c495 | 3,654,654 |
from typing import List
from typing import Optional
def station_code_from_duids(duids: List[str]) -> Optional[str]:
"""
Derives a station code from a list of duids
ex.
BARRON1,BARRON2 => BARRON
OSBAG,OSBAG => OSBAG
"""
if type(duids) is not list:
return None
... | 1f976ee0b7a82453673ea07c20070e502df5fcf5 | 3,654,655 |
def erosion(image, selem, out=None, shift_x=False, shift_y=False):
"""Return greyscale morphological erosion of an image.
Morphological erosion sets a pixel at (i,j) to the minimum over all pixels
in the neighborhood centered at (i,j). Erosion shrinks bright regions and
enlarges dark regions.
Para... | 2e7c2547b862add24cc6a4355cf3e0308cb2f342 | 3,654,656 |
def NE(x=None, y=None):
"""
Compares two values and returns:
true when the values are not equivalent.
false when the values are equivalent.
See https://docs.mongodb.com/manual/reference/operator/aggregation/ne/
for more details
:param x: first value or expression
:param y: second... | be721daf480ec0cb465a3c010c4f910a10fbbb1d | 3,654,657 |
def TCPs_from_tc(type_constraint):
"""
Take type_constraint(type_param_str, allowed_type_strs) and return list of TypeConstraintParam
"""
tys = type_constraint.allowed_type_strs # Get all ONNX types
tys = set(
[onnxType_to_Type_with_mangler(ty) for ty in tys]
) # Convert to Knossos and... | 7c2162bb2dde0b00caf289511f20804cadaa17e5 | 3,654,658 |
def _randomde(allgenes,
allfolds,
size):
"""Randomly select genes from the allgenes array and fold changes from the
allfolds array. Size argument indicates how many to draw.
Parameters
----------
allgenes : numpy array
numpy array with all the genes expressed in ... | 1a5f38eab8933b90697f4999cb7571fe602db3f9 | 3,654,659 |
import time
def XCor(spectra, mask_l, mask_h, mask_w, vel, lbary_ltopo, vel_width=30,\
vel_step=0.3, start_order=0, spec_order=9,iv_order=10,sn_order=8,max_vel_rough=300.):
"""
Calculates the cross-correlation function for a Coralie Spectra
"""
# speed of light, km/s
c = 2.99792458E5
# loop over ... | 7007c56e5173999b9d20dfbd8018133a59bb777c | 3,654,660 |
import json
def marks_details(request, pk):
"""
Display details for a given Mark
"""
# Check permission
if not has_access(request):
raise PermissionDenied
# Get context
context = get_base_context(request)
# Get object
mark = get_object_or_404(Mark, pk=pk)
mark.catego... | 1f193c67f1e047ecd6da0e5eec1d29da50f6595e | 3,654,661 |
from bs4 import BeautifulSoup
def clean_text(text):
"""
text: a string
return: modified initial string
"""
text = BeautifulSoup(text, "lxml").text # HTML decoding
text = text.lower() # lowercase text
# replace REPLACE_BY_SPACE_RE symbols by space in text
text = REPLACE_BY_SP... | 6594bd61c2f1ff885948755a0dfc74e7256b9a3e | 3,654,662 |
import logging
import sys
def get_input_device(config):
""" Create the InputDevice instance and handle errors """
dev_path = config['flirc_device_path']
logging.debug('get_input_device() dev_path: %s', dev_path)
try:
input_device = InputDevice(dev_path)
return input_device
except ... | fef51e92f6e81ff873d0df821e871545a86eb900 | 3,654,663 |
def _simpsons_interaction(data, groups):
"""
Calculation of Simpson's Interaction index
Parameters
----------
data : a pandas DataFrame
groups : list of strings.
The variables names in data of the groups of interest of the analysis.
Returns
-------
statistic ... | d7c4bc8bfb2d6db17868f0d140c2547e65cfd666 | 3,654,664 |
import os
def find_includes(armnn_include_env: str = INCLUDE_ENV_NAME):
"""Searches for ArmNN includes.
Args:
armnn_include_env(str): Environmental variable to use as path.
Returns:
list: A list of paths to include.
"""
armnn_include_path = os.getenv(armnn_include_env)
if arm... | b601f8253d9c7e3f1966f0b5e8810d8f12576621 | 3,654,665 |
import sys
def read_missing_oids(oid_lines):
"""
Parse lines into oids.
>>> list(read_missing_oids([
... "!!! Users 0 ?", "POSKeyError: foo",
... "!!! Users 0 ?",
... "!!! Users 1 ?",
... "bad xref name, 1", "bad db", ]))
[0, 1]
"""
result = OidSet()
for line in o... | 0f408ba7673fa78b57b2533d9ffe8ab5296a633c | 3,654,666 |
import json
def run(target='192.168.1.1', ports=[21,22,23,25,80,110,111,135,139,443,445,554,993,995,1433,1434,3306,3389,8000,8008,8080,8888]):
"""
Run a portscan against a target hostname/IP address
`Optional`
:param str target: Valid IPv4 address
:param list ports: Port numbers to scan on target... | 201e4dc1809553eb4fb57848d9e5f8001ccdef23 | 3,654,667 |
import torch
def subsequent_mask(size: int):
"""
Mask out subsequent positions (to prevent attending to future positions)
Transformer helper function.
:param size: size of mask (2nd and 3rd dim)
:return: Tensor with 0s and 1s of shape (1, size, size)
"""
mask = np.triu(np.ones((1, size, s... | f4e40d2e9ac944d3582ed16088e8096f75a5f29e | 3,654,668 |
from typing import Type
def _get_dist_class(
policy: Policy, config: TrainerConfigDict, action_space: gym.spaces.Space
) -> Type[TorchDistributionWrapper]:
"""Helper function to return a dist class based on config and action space.
Args:
policy (Policy): The policy for which to return the action
... | 6511786dff734ddb78ce7c28e19b651c70fe86e2 | 3,654,669 |
def timeexec(fct, number, repeat):
"""
Measures the time for a given expression.
:param fct: function to measure (as a string)
:param number: number of time to run the expression
(and then divide by this number to get an average)
:param repeat: number of times to repeat the computation
... | 01ea6d74bed9d8a7d1b7793d3f8473bc6442f83f | 3,654,670 |
import sys
def is_bst(root):
""" checks if binary tree is binary search tree """
def is_bst_util(root, min_value, max_value):
""" binary search tree check utility function """
if root is None:
return True
if (root.data >= min_value and root.data < max_value
... | 46828b5b3fc1827908faf7b9bb646bc3b6594b30 | 3,654,671 |
def regexify(w, tags):
"""Convert a single component of a decomposition rule
from Weizenbaum notation to regex.
Parameters
----------
w : str
Component of a decomposition rule.
tags : dict
Tags to consider when converting to regex.
Returns
-------
w : str
Co... | 113a631674c5984d81f830c5e8ca840d95678aa1 | 3,654,672 |
def row_dot_product(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""
Returns a vectorized dot product between the rows of a and b
:param a: An array of shape (N, M) or (M, )
(or a shape that can be broadcast to (N, M))
:param b: An array of shape (N, M) or (M, )
(or a shape that can be broadcas... | d2544f2957963d343bdeb079418a1a5d96373eb4 | 3,654,673 |
def pmg_pickle_dump(obj, filobj, **kwargs):
"""
Dump an object to a pickle file using PmgPickler.
Args:
obj : Object to dump.
fileobj: File-like object
\\*\\*kwargs: Any of the keyword arguments supported by PmgPickler
"""
return PmgPickler(filobj, **kwargs).dump(obj) | 4ac72623538ce463b1bfc183bcac90919e47c513 | 3,654,674 |
def condition_header(header, needed_keys=None):
"""Return a dictionary of all `needed_keys` from `header` after passing
their values through the CRDS value conditioner.
"""
header = { key.upper():val for (key, val) in header.items() }
if not needed_keys:
needed_keys = header.keys()
else:... | cd8c39e355a05367d479e76bda6f0869c10f8130 | 3,654,675 |
from typing import OrderedDict
def get_generic_path_information(paths, stat_prefix=""):
"""
Get an OrderedDict with a bunch of statistic names and values.
"""
statistics = OrderedDict()
returns = [sum(path["rewards"]) for path in paths]
# rewards = np.vstack([path["rewards"] for path in paths]... | a90995c43d588cee4869bfa8b3f6a1026d265aab | 3,654,676 |
import math
import numpy as np
def pad_images(images, nlayers):
"""
In Unet, every layer the dimension gets divided by 2
in the encoder path. Therefore the image size should be divisible by 2^nlayers.
"""
divisor = 2**nlayers
nlayers, x, y = images.shape # essentially setting nlayers to z dire... | 671fa940d0a0ed87819335b60d12d9e268bf9932 | 3,654,677 |
def remove_measurements(measurements, model_dict, params=None):
"""Remove measurements from a model specification.
If provided, a params DataFrame is also reduced correspondingly.
Args:
measurements (str or list): Name(s) of the measurement(s) to remove.
model_dict (dict): The model specif... | fffddf4368579c999648c29b4746006b38de140c | 3,654,678 |
def good2Go(SC, L, CC, STR):
"""
Check, if all input is correct and runnable
"""
if SC == 1 and L == 1 and CC == 1 and STR == 1:
return True
else:
print(SC, L, CC, STR)
return False | e49229df6b9b187e1840d5bc5c8a1a8e087a5a4e | 3,654,679 |
def __validate_tweet_name(tweet_name: str, error_msg: str) -> str:
"""Validate the tweet's name.
Parameters
----------
tweet_name : str
Tweet's name.
error_msg : str
Error message to display for an invalid name.
Returns
-------
str
Validated tweet name.
Rai... | 7086aeac6ccd0afcad0d13e947f3b454f7333b9f | 3,654,680 |
def convert_event(obj):
"""
:type obj: :class:`sir.schema.modelext.CustomEvent`
"""
event = models.event(id=obj.gid, name=obj.name)
if obj.comment:
event.set_disambiguation(obj.comment)
if obj.type is not None:
event.set_type(obj.type.name)
event.set_type_id(obj.type.gi... | 23a6a31abca03d0c92f6162ce28b8548dc95bdda | 3,654,681 |
from typing import Any
import requests
import json
def get_pr_review_status(pr: PullRequestDetails, per_page: int = 100) -> Any:
"""
References:
https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request
"""
url = (f"https://api.github.com/repos/{pr.repo.organization}/{pr.re... | 5ce662ab5d82e374def95e5f3cc4da9f2d4dbf96 | 3,654,682 |
def make_sph_model(filename):
"""reads a spherical model file text file and generates interpolated values
Args:
filename:
Returns:
model:
"""
M = np.loadtxt(filename, dtype={'names': ('rcurve', 'potcurve', 'dpotcurve'),'formats': ('f4', 'f4', 'f4')},skiprows=1)
model = ... | d86a88ffca93ee0618cf5a19aa015077247cffb0 | 3,654,683 |
import os
def list_dir(filepath):
"""List the files in the directory"""
return sorted(list(map(lambda x: os.path.join(filepath, x), os.listdir(filepath)))) | 29c50f132b5abfdfea819db58a816a83e6efaccd | 3,654,684 |
def minimum(x, y):
"""
Returns the min of x and y (i.e. x < y ? x : y) element-wise.
Parameters
----------
x : tensor.
Must be one of the following types: bfloat16, half, float32, float64, int32, int64.
y : A Tensor.
Must have the same type as x.
name : str
A name fo... | 384e7d15687d03f7b639fc50707712c94029620f | 3,654,685 |
def seconds_to_timestamp(seconds):
"""
Convert from seconds to a timestamp
"""
minutes, seconds = divmod(float(seconds), 60)
hours, minutes = divmod(minutes, 60)
return "%02d:%02d:%06.3f" % (hours, minutes, seconds) | 8b9806f05fe4796baae51001e69455e82fb51eed | 3,654,686 |
def query(querystring: str,
db: tsdb.Database,
**kwargs):
"""
Perform query *querystring* on the testsuite *ts*.
Note: currently only 'select' queries are supported.
Args:
querystring (str): TSQL query string
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query... | fa43123b3e0c4706b738104c641836fa08a4fc35 | 3,654,687 |
def TTF_SizeUTF8(font, text, w, h):
"""Calculates the size of a UTF8-encoded string rendered with a given font.
See :func:`TTF_SizeText` for more info.
Args:
font (:obj:`TTF_Font`): The font object to use.
text (bytes): A UTF8-encoded bytestring of text for which the rendered
s... | 3d24382222b1795caa0981c659d00a717c22fc86 | 3,654,688 |
def get_mse(y_true, y_hat):
"""
Return the mean squared error between the ground truth and the prediction
:param y_true: ground truth
:param y_hat: prediction
:return: mean squared error
"""
return np.mean(np.square(y_true - y_hat)) | 3d4c1828abf5bf88607e4ca1a263c483105733aa | 3,654,689 |
def generate_v2_token(username, version, client_ip, issued_at_timestamp, email=''):
"""Creates the JSON Web Token with a new schema
:Returns: String
:param username: The name of person who the token identifies
:type username: String
:param version: The version number for the token
:type versi... | dee10b68fc15ec730a7b8921f95a77804618879c | 3,654,690 |
import math
def choose(n, k):
"""return n choose k
resilient (though not immune) to integer overflow"""
if n == 1:
# optimize by far most-common case
return 1
return fact_div(n, max(k, n - k)) / math.factorial(min(k, n - k)) | fecd411a4148127f998f58d8d27668777bf5efbe | 3,654,691 |
from typing import List
def part_one(puzzle_input: List[str]) -> int:
"""Find the highest seat ID on the plane"""
return max(boarding_pass_to_seat_id(line) for line in puzzle_input) | 1ae95a7784f5348bb435483228630c8795d62d30 | 3,654,692 |
def readbit(val, bitidx):
""" Direct word value """
return int((val & (1<<bitidx))!=0) | 4ca368f89b2496ec46c1641835c1f2a0a1cdd573 | 3,654,693 |
def matrix_bombing_plan(m):
""" This method calculates sum of the matrix by
trying every possible position of the bomb and
returns a dictionary. Dictionary's keys are the
positions of the bomb and values are the sums of
the matrix after the damage """
matrix = deepcopy(m)
rows = len(m)
... | 013d1dc3685013fa6fd5c87cfc2513e07e66e310 | 3,654,694 |
def coord_to_gtp(coord, board_size):
""" From 1d coord (0 for position 0,0 on the board) to A1 """
if coord == board_size ** 2:
return "pass"
return "{}{}".format("ABCDEFGHJKLMNOPQRSTYVWYZ"[int(coord % board_size)],\
int(board_size - coord // board_size)) | a0419e8a7f39cd282585ed1d29d94bbded0e3f1c | 3,654,695 |
def test_alternative_clusting_method(ClusterModel):
"""
Test that users can supply alternative clustering method as dep injection
"""
def clusterer(X: np.ndarray, k: int, another_test_arg):
"""
Function to wrap a sklearn model as a clusterer for OptimalK
First two arguments are ... | 173e376726abe943f15fae44aa746bf9abe7dd53 | 3,654,696 |
def load_dataset(spfile, twfile):
"""Loads dataset given the span file and the tweets file
Arguments:
spfile {string} -- path to span file
twfile {string} -- path to tweets file
Returns:
dict -- dictionary of tweet-id to Tweet object
"""
tw_int_map = {}
# for filen in os.... | e25c382b3fe8c321b70206894e483c3f04ade2ed | 3,654,697 |
from typing import Union
from typing import Tuple
def nameof(var, *more_vars,
# *, keyword only argument, supported with python3.8+
frame: int = 1,
vars_only: bool = True) -> Union[str, Tuple[str]]:
"""Get the names of the variables passed in
Examples:
>>> a = 1
... | 4a7c7d8390dad2597cad65409aaa6cd3f716a8a8 | 3,654,698 |
import os
def cache_get_filepath(key):
"""Returns cache path."""
return os.path.join(settings.CACHE_PATH, key) | 7b6ace1c68a4783a95390b4dcf1c658b7b9db0b2 | 3,654,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.