content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_contact():
"""
Get a contact form submission
"""
data = request.get_json(force=True)
contact = ContactDAO.create(**data)
return jsonify(contact.to_dict()) | af2c5efbd06d3220faf3b16059ea9d612cece19e | 10,613 |
from typing import DefaultDict
from typing import Tuple
from typing import List
import copy
def separate_sets(
hand: DefaultDict[int, int], huro_count: int, koutsu_first: bool = True
) -> Tuple[List[Tile], List[List[Tile]], Tile]:
"""Helper function for seperating player's remaining hands into sets.
It sh... | 894a712a739e16a98e2150c4461a3d66c759bace | 10,615 |
def units(legal_codes):
"""
Return sorted list of the unique units for the given
dictionaries representing legal_codes
"""
return sorted(set(lc["unit"] for lc in legal_codes)) | 85803ecb3d1f51c058c959b7e060c3cb5263f6a3 | 10,616 |
def resize_terms(terms1, terms2, patterns_to_pgS, use_inv):
"""
Resize the terms to ensure that the probabilities are the same on both sides.
This is necessary to maintain the null hypothesis that D = 0 under no introgression.
Inputs:
terms1 --- a set of patterns to count and add to each other to de... | d422e3d5b32df55036afa3788cdb0bdd4aa95001 | 10,617 |
def get_network_list():
"""Get a list of networks.
---
tags:
- network
"""
return jsonify([
network.to_json(include_id=True)
for network in manager.cu_list_networks()
]) | 6a54b76091160fc28cd45502aea4c54d2862a588 | 10,618 |
def bfixpix(data, badmask, n=4, retdat=False):
"""Replace pixels flagged as nonzero in a bad-pixel mask with the
average of their nearest four good neighboring pixels.
:INPUTS:
data : numpy array (two-dimensional)
badmask : numpy array (same shape as data)
:OPTIONAL_INPUTS:
n : int
... | ae6b6c44e82dc70f998b31d9645cf74fef92c9fd | 10,619 |
import re
def parse_discount(element):
"""Given an HTML element, parse and return the discount."""
try:
# Remove any non integer characters from the HTML element
discount = re.sub("\D", "", element)
except AttributeError:
discount = "0"
return discount | 658f8a6bef8ba4bf82646a10c495904c03a717c7 | 10,620 |
import bisect
def read_files(allVCFs):
"""
Load all vcfs and count their number of entries
"""
# call exists in which files
call_lookup = defaultdict(list)
# total number of calls in a file
file_abscnt = defaultdict(float)
for vcfn in allVCFs:
v = parse_vcf(vcfn)
# disa... | 8518eac3c43772016fd5cbe0fd6c423a1e463ebc | 10,621 |
def parse_dat_file(dat_file):
"""
Parse a complete dat file.
dat files are transposed wrt the rest of the data formats here. In addition, they only contain integer fields,
so we can use np.loadtxt.
First 6 columns are ignored.
Note: must have a bims and info file to process completely.
Para... | 3b84730a347075c5be1e0ebe5a195338a86ed0c6 | 10,622 |
from typing import List
def next_whole_token(
wordpiece_subtokens,
initial_tokenizer,
subword_tokenizer):
"""Greedily reconstitutes a whole token from a WordPiece list.
This function assumes that the wordpiece subtokens were constructed correctly
from a correctly subtokenized CuBERT tokenizer, but ... | d26f4da0932030242c2209bc998bc32b6ce98cdf | 10,625 |
def match_seq_len(*arrays: np.ndarray):
"""
Args:
*arrays:
Returns:
"""
max_len = np.stack([x.shape[-1] for x in arrays]).max()
return [np.pad(x, pad_width=((0, 0), (0, 0), (max_len - x.shape[-1], 0)), mode='constant', constant_values=0) for x
in arrays] | 2cd8715eb634e0b3604e1d5c305a5209bb0ae03d | 10,627 |
import torch
import math
def get_cmws_5_loss(
generative_model, guide, memory, obs, obs_id, num_particles, num_proposals, insomnia=1.0
):
"""Normalize over particles-and-memory for generative model gradient
Args:
generative_model
guide
memory
obs: tensor of shape [batch_si... | 5e2b87a7d19eab1f09e5207f4c16c8e4a56b2225 | 10,628 |
import torch
def to_float_tensor(np_array):
"""
convert to long torch tensor
:param np_array:
:return:
"""
return torch.from_numpy(np_array).type(torch.float) | 84512d8383999bf22841c0e7e1fc8048bcba9a1a | 10,630 |
def display_heatmap(salience_scores,
salience_scores_2=None,
title=None,
title_2=None,
cell_labels=None,
cell_labels_2=None,
normalized=True,
ui=False):
"""
A utility funct... | 8229db9630c8553567f0f93f8320c71397180ced | 10,631 |
import re
def _cleanse_line(line, main_character):
"""
Cleanse the extracted lines to remove formatting.
"""
# Strip the line, just in case.
line = line.strip()
# Clean up formatting characters.
line = line.replace('\\' , '') # Remove escape characters.
line = line.replace('[mc]... | 87177c557ab89b77c63cc1df10874e52606258a7 | 10,632 |
def require_pandapower(f):
"""
Decorator for functions that require pandapower.
"""
@wraps(f)
def wrapper(*args, **kwds):
try:
getattr(pp, '__version__')
except AttributeError:
raise ModuleNotFoundError("pandapower needs to be manually installed.")
r... | 35b0e5a5f9c4e189d849e3a6ba843b6f9e6b49b1 | 10,633 |
def optimal_path_fixture():
"""An optimal path, and associated distance, along the nodes of the pyramid"""
return [0, 1, 2, 3], 10 + 2 + 5 | 10c4e436907ecb99740a2514c927f05fd8488cf4 | 10,634 |
import timeit
def evaluate_DynamicHashtablePlusRemove(output=True):
"""
Compare performance using ability in open addressing to mark deleted values.
Nifty trick to produce just the squares as keys in the hashtable.
"""
# If you want to compare, then add following to end of executable statements:
... | 243b5f4972b8eaa2630b6920c2d640d729feae61 | 10,635 |
def closest(lat1, lon1):
"""Return distance (km) and city closest to given coords."""
lat1, lon1 = float(lat1), float(lon1)
min_dist, min_city = None, None
for city, lat2, lon2 in CITIES:
dist = _dist(lat1, lon1, lat2, lon2)
if min_dist is None or dist < min_dist:
min_dist, ... | 4227e357f41619b6e2076bdcf3bb67b92daa9c4a | 10,636 |
def get_previous_term():
"""
Returns a uw_sws.models.Term object,
for the previous term.
"""
url = "{}/previous.json".format(term_res_url_prefix)
return Term(data=get_resource(url)) | a261bc9d744f8f0b70ac76ac596f922b63ea9a46 | 10,637 |
from re import T
def used(obj: T) -> T:
"""Decorator indicating that an object is being used.
This stops the UnusedObjectFinder from marking it as unused.
"""
_used_objects.add(obj)
return obj | 33d241fe4a0953352ecad2ba306f915a88500d46 | 10,638 |
import scipy
def fit_double_gaussian(x_data, y_data, maxiter=None, maxfun=5000, verbose=1, initial_params=None):
""" Fitting of double gaussian
Fitting the Gaussians and finding the split between the up and the down state,
separation between the max of the two gaussians measured in the sum of the st... | 65a54120e2d244301d36d0bba1e25fc711a9d6bb | 10,639 |
def _set_advanced_network_attributes_of_profile(config, profile):
"""
Modify advanced network attributes of profile.
@param config: current configparser configuration.
@param profile: the profile to set the attribute in.
@return: configparser configuration.
"""
config = _set_attribute_of_pr... | f5254f5f055865bf43f0e97f2dcf791bbbe61011 | 10,640 |
def ring_bond_equal(b1, b2, reverse=False):
"""Check if two bonds are equal.
Two bonds are equal if the their beginning and end atoms have the same symbol and
formal charge. Bond type not considered because all aromatic (so SINGLE matches DOUBLE).
Parameters
----------
b1 : rdkit.Chem.rdchem.B... | e0c5ab25d69f5770dcf58dd284519b3ed593ad33 | 10,642 |
import _warnings
def survey_aligned_velocities(od):
"""
Compute horizontal velocities orthogonal and tangential to a survey.
.. math::
(v_{tan}, v_{ort}) = (u\\cos{\\phi} + v\\sin{\\phi},
v\\cos{\\phi} - u\\sin{\\phi})
Parameters
----------
od: OceanDataset
oceandata... | c506f8ca5db1ed6045ac02fb1988900f0ae10451 | 10,643 |
def insertion_sort(numbers):
"""
At worst this is an O(n2) algorithm
At best this is an O(n) algorithm
"""
for index in xrange(1, len(numbers)):
current_num = numbers[index]
current_pos = index
while current_pos > 0 and numbers[current_pos - 1] > current_num:
numb... | d32a73b156f8b469cfcbdda70f349c7f3173d6a9 | 10,644 |
def ratio_shimenreservoir_to_houchiweir():
"""
Real Name: Ratio ShiMenReservoir To HouChiWeir
Original Eqn: Sum Allocation ShiMenReservoir To HouChiWeir/Sum Allcation From ShiMenReservoir
Units: m3/m3
Limits: (None, None)
Type: component
"""
return sum_allocation_shimenreservoir_to_hou... | e49969f53d6641a02b6cea5d3010ac34eb0739fd | 10,645 |
import torch
def torch_profiler_full(func):
"""
A decorator which will run the torch profiler for the decorated function,
printing the results in full.
Note: Enforces a gpu sync point which could slow down pipelines.
"""
@wraps(func)
def wrapper(*args, **kwargs):
with torch.autog... | 7a92eb75d0131c6d151c9908fdcf2e84f6499468 | 10,646 |
def bias_add(x, bias, data_format=None):
"""Adds a bias vector to a tensor.
# Arguments
x: Tensor or variable.
bias: Bias tensor to add.
data_format: string, `"channels_last"` or `"channels_first"`.
# Returns
Output tensor.
# Raises
ValueError: In one of the tw... | 1b783bbd6f685be336b565d7e5db9c5aa91a1f16 | 10,647 |
def get_news_with_follow(request, user_id):
"""
获取用户关注类型的前30条,未登录300未登录
:param request: 请求对象
:return: Json数据
"""
data = {}
try:
user = User.objects.get(pk=user_id)
follow_set = user.follow_type.value_list('id').all()
follow_list = [x[0] for x in follow_set]
n... | 41e9c8cb20c9c1757a8633d584f738b6a64e4f2b | 10,648 |
def trigger():
"""Trigger salt-api call."""
data = {'foo': 'bar'}
return request('/hook/trigger', data=data) | 6aa469468711c3c94e0b5a20d9825fc9c0a73d83 | 10,650 |
from typing import List
import math
def fitness_function(cams: List[Coord], pop: List[Coord]) -> int:
"""
Function to calculate number of surveilled citizens.
Check if all the cameras can see them, if any can score increases
"""
score = []
for cit in pop:
test = False
for cam ... | d10c02a7b182a8c38d8db37f13aec5b4c9def593 | 10,651 |
import requests
def scrape_opening_hours():
""""scrape opening hours from https://www.designmuseumgent.be/bezoek"""
r = requests.get("https://www.designmuseumgent.be/bezoek")
data = r.text
return data | 297a35f3bc4e10d453da495e031fae5ce79ca643 | 10,652 |
import torch
def _demo_mm_inputs(input_shape=(1, 3, 256, 256)):
"""Create a superset of inputs needed to run test or train batches.
Args:
input_shape (tuple):
input batch dimensions
"""
(N, C, H, W) = input_shape
rng = np.random.RandomState(0)
imgs = rng.rand(*input_shap... | abef4e006fe6e530c5ca372904a40eecc3dbb5b7 | 10,653 |
import random
def compute_one_epoch_baseline():
"""
Function to compute the performance of a simple one epoch baseline.
:return: a line to display (string reporting the experiment results)
"""
best_val_obj_list = []
total_time_list = []
for nb201_random_seed in nb201_random_seeds:
... | 1bc3b03d49f0bbb8e2213acb31c64367b577aed2 | 10,654 |
import string
import random
def generate_random_string( length ):
"""Generate a random string of a given length containing uppercase and lowercase letters, digits and ASCII punctuation."""
source = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
return ''.join( random.... | 9bb1ee7e21f27231e498f48bff505d963565f582 | 10,655 |
from typing import Mapping
from typing import Sequence
def pretty_table(rows, header=None):
"""
Returns a string with a simple pretty table representing the given rows.
Rows can be:
- Sequences such as lists or tuples
- Mappings such as dicts
- Any object with a __dict__ attribute (most pla... | 1b4707932b27277ef22f17631e7a5778a38f99eb | 10,657 |
def interpolate_trajectory(world_map, waypoints_trajectory, hop_resolution=1.0):
"""
Given some raw keypoints interpolate a full dense trajectory to be used by the user.
Args:
world: an reference to the CARLA world so we can use the planner
waypoints_trajectory: the current coarse trajectory... | df544616954868aaa25c86b50420202bea860d9b | 10,658 |
def import_data(filepath="/home/vagrant/countries/NO.txt", mongodb_url="mongodb://localhost:27017"):
"""
Import the adress data into mongodb
CLI Example:
salt '*' mongo.import_data /usr/data/EN.txt
"""
client = MongoClient(mongodb_url)
db = client.demo
address_col = db.address
... | 8f80343c60000a8ab988c02bac54e2f748e346b9 | 10,659 |
import async_timeout
import requests
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Enphase Envoy sensor."""
ip_address = config[CONF_IP_ADDRESS]
monitored_conditions = config[CONF_MONITORED_CONDITIONS]
name = config[CONF_NAME]
username = confi... | 07e762a8fbcc987b57d38bc8a10d3f51e6fa58a4 | 10,660 |
from .register import PIPING_SIGNS
from .verb import Verb
import ast
def _get_piping_verb_node(calling_node: ast.Call) -> ast.Call:
"""Get the ast node that is ensured the piping verb call
Args:
calling_node: Current Call node
Returns:
The verb call node if found, otherwise None
"""
... | 2f6be9b382f2bf2e31d39ff9682f5b26618aa1af | 10,661 |
def slot(**kwargs):
"""Creates a SlotConfig instance based on the arguments.
Args:
**kwargs: Expects the following keyed arguments.
in_dist: Distribution for inbound in msec. Optional
in_max_bytes: Optional. Ignored when in_dist is missing.
in_max_pkts: Optional. Ign... | 4b26f7a805b88a7a6bd03f7d23db7a14d7979eeb | 10,662 |
def get_agent_type(player):
""" Prompts user for info as to the type of agent to be created """
print('There are two kinds of Agents you can initialise.')
print(' 1 - <Human> - This would be a totally manually operated agent.')
print(' You are playing the game yourself.')
print(' ... | 3d0fce9faafaa6c993cb2b5b54a1480268c22ab3 | 10,663 |
def _try_match_and_transform_pattern_1(reduce_op, block) -> bool:
"""
Identify the pattern:
y = gamma * (x - mean) / sqrt(variance + epsilon) + beta
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
x --> reduce_mean --> sub --> square --> reduce_mean --> a... | f1baecfc53daf731c5b518aadcc11c88508258e3 | 10,664 |
import click
def cli_resize(maxsize):
"""Resize images to a maximum side length preserving aspect ratio."""
click.echo("Initializing resize with parameters {}".format(locals()))
def _resize(images):
for info, image in images:
yield info, resize(image, maxsize)
return _resize | f0695940531c45a88ff1722c002dacc6103962e0 | 10,665 |
import numpy
def _fetch_object_array(cursor):
"""
_fetch_object_array() fetches arrays with a basetype that is not considered
scalar.
"""
arrayShape = cursor_get_array_dim(cursor)
# handle a rank-0 array by converting it to
# a 1-dimensional array of size 1.
if len(arrayShape) == 0:
... | 7c84306c0b84a126f401e51bac5896203357380a | 10,666 |
def sldParse(sld_str):
"""
Builds a dictionary from an SldStyle string.
"""
sld_str = sld_str.replace("'", '"').replace('\"', '"')
keys = ['color', 'label', 'quantity', 'opacity']
items = [el.strip() for el in sld_str.split('ColorMapEntry') if '<RasterSymbolizer>' not in el]
sld_items = []
... | 888a2ee3251a0d1149b478d32ccb88ff0e309ec3 | 10,667 |
def x_ideal(omega, phase):
"""
Generates a complex-exponential signal with given frequency
and phase. Does not contain noise
"""
x = np.empty(cfg.N, dtype=np.complex_)
for n in range(cfg.N):
z = 1j*(omega * (cfg.n0+n) * cfg.Ts + phase)
x[n] = cfg.A * np.exp(z)
return x | 87e4df7cbbfe698e5deb461642de72efb6bfffad | 10,668 |
def _wrap_stdout(outfp):
"""
Wrap a filehandle into a C function to be used as `stdout` or
`stderr` callback for ``set_stdio``. The filehandle has to support the
write() and flush() methods.
"""
def _wrap(instance, str, count):
outfp.write(str[:count])
outfp.flush()
retu... | f7d773890b17b18855d2d766bd147c67ac7ade3b | 10,669 |
def svn_fs_apply_textdelta(*args):
"""
svn_fs_apply_textdelta(svn_fs_root_t root, char path, char base_checksum,
char result_checksum, apr_pool_t pool) -> svn_error_t
"""
return _fs.svn_fs_apply_textdelta(*args) | d8d228415d8768ec297415a42113e0eb2463163f | 10,670 |
def find(x):
"""
Find the representative of a node
"""
if x.instance is None:
return x
else:
# collapse the path and return the root
x.instance = find(x.instance)
return x.instance | 5143e9d282fb1988d22273996dae36ed587bd9d2 | 10,671 |
def convert_shape(node, **kwargs):
"""Map MXNet's shape_array operator attributes to onnx's Shape operator
and return the created node.
"""
return create_basic_op_node('Shape', node, kwargs) | 7d4414eac78208b0c35d7ab5a9f21ab70a0947ae | 10,672 |
import time
def get_timestamp(prev_ts=None):
"""Internal helper to return a unique TimeStamp instance.
If the optional argument is not None, it must be a TimeStamp; the
return value is then guaranteed to be at least 1 microsecond later
the argument.
"""
t = time.time()
t = TimeStamp(*tim... | 89751c53679f11efd26b88609887c4a2ed475418 | 10,674 |
def get_element_as_string(element):
"""
turn xml element from etree to string
:param element:
:return:
"""
return lxml.etree.tostring(element, pretty_print=True).decode() | f62945ff4bdd3bea2562ba52a89d8d01c74e0b10 | 10,675 |
def _select_ports(count, lower_port, upper_port):
"""Select and return n random ports that are available and adhere to the given port range, if applicable."""
ports = []
sockets = []
for i in range(count):
sock = _select_socket(lower_port, upper_port)
ports.append(sock.getsockname()[1])
... | 2f92cb7e4ab26c54bc799369cd950c4269049291 | 10,677 |
def is_solution_quad(var, coeff, u, v):
"""
Check whether `(u, v)` is solution to the quadratic binary diophantine
equation with the variable list ``var`` and coefficient dictionary
``coeff``.
Not intended for use by normal users.
"""
reps = dict(zip(var, (u, v)))
eq = Add(*[j*i.xrepla... | b19d7678c725a41df755352f5af1ce322f3efad7 | 10,678 |
def is_callable(x):
"""Tests if something is callable"""
return callable(x) | 72584deb62ac5e34e69325466236792c5299a51b | 10,679 |
def validate_version_argument(version, hint=4):
""" validate the version argument against the supported MDF versions. The
default version used depends on the hint MDF major revision
Parameters
----------
version : str
requested MDF version
hint : int
MDF revision hint
Retur... | e29342f78236f043b079cf5e4473f6dccb29d35c | 10,680 |
import torch
def roc_auc(probs, labels):
"""
Computes the area under the receiving operator characteristic between output probs
and labels for k classes.
Source: https://github.com/HazyResearch/metal/blob/master/metal/utils.py
args:
probs (tensor) (size, k)
labels (tensor... | 9ae79a4ff5cbf93d2187857c8ac62014c6fa98f0 | 10,681 |
from typing import Collection
def show_collection(request, collection_id):
"""Shows a collection"""
collection = get_object_or_404(Collection, pk=collection_id)
# New attribute to store the list of problems and include the number of submission in each problem
collection.problem_list = collection.probl... | a23efc449258839a7d7bfa0c0a73d889a6891a0f | 10,682 |
from typing import Union
from typing import Callable
from typing import List
def alpha(
data: np.ndarray,
delta: Union[Callable[[int, int], float], List[List[float]], str] = "nominal",
):
"""Calculates Krippendorff's alpha coefficient [1, sec. 11.3] for
inter-rater agreement.
[1] K. Krippendorff,... | 98c86120287d9d4b2c7f10ad074702c2088ade8d | 10,683 |
def enforce(action, target, creds, do_raise=True):
"""Verifies that the action is valid on the target in this context.
:param creds: user credentials
:param action: string representing the action to be checked, which
should be colon separated for clarity.
O... | 16cdefe38bfc56f529a735b8517d94ade7db780d | 10,684 |
from operator import and_
from operator import or_
def query_data(session, agency_code, period, year):
""" Request A file data
Args:
session: DB session
agency_code: FREC or CGAC code for generation
period: The period for which to get GTAS data
year: The ye... | 0eb856f699eebf95bf10ff2d3dd6c9a72ec0843a | 10,685 |
def vocublary(vec_docs):
""" vocabulary(vec_docs) -> tuple: (int avg_doc_len, updated vec_docs, corpus Vocabulary dictionary {"word": num_docs_have__this_term, ...})
vec_docs = list of documents as dictionaries [{ID:"word_i word_i+1 ..."} , {ID:"word_i word_i+1"}, ...}]
"""
vocabulary = {}
count_v... | 4e6f4df1e36c2fdf3d7d1d20750d74f91a0214b6 | 10,686 |
import warnings
def _build_type(type_, value, property_path=None):
""" Builds the schema definition based on the given type for the given value.
:param type_: The type of the value
:param value: The value to build the schema definition for
:param List[str] property_path: The property path of the curr... | 7033e5f8bc5cd5b667f25b8554bfe3296191762f | 10,688 |
def lidar_2darray_to_rgb(array: np.ndarray) -> np.ndarray:
"""Returns a `NumPy` array (image) from a 4 channel LIDAR point cloud.
Args:
array: The original LIDAR point cloud array.
Returns:
The `PyGame`-friendly image to be visualized.
"""
# Get array shapes.
W, H, C = array.shape
assert C == 2
... | 69e2de793b9280b269ac8ab9f3d313e51c932c8c | 10,689 |
from typing import Tuple
from typing import Union
from typing import List
from typing import Dict
import tqdm
import torch
def rollout(dataset: RPDataset,
env: RPEnv,
policy: Policy,
batch_size: int,
num_workers: int = 4,
disable_progress_bar: bool = False,
... | 1b88ff01b86d567de2c78d4450825e4fd1120311 | 10,691 |
def regex_ignore_case(term_values):
"""
turn items in list "term_values" to regexes with ignore case
"""
output=[]
for item in term_values:
output.append(r'(?i)'+item)
return output | 5dbf5fba758fe91fb0bbfaed6ab3cfa5f05357eb | 10,692 |
from typing import Callable
def importance_sampling_integrator(function: Callable[..., np.ndarray],
pdf: Callable[..., np.ndarray],
sampler: Callable[..., int],
n: int = 10000,
s... | 14b6abfaa38f37430ec0e9abcd330f1392543978 | 10,693 |
from apex.amp._amp_state import _amp_state
import torch
def r1_gradient_penalty_loss(discriminator,
real_data,
mask=None,
norm_mode='pixel',
loss_scaler=None,
use_apex_amp=F... | d142375d89f39ae2510575d0615a878bd67e9574 | 10,694 |
import json
import re
def visualize(args):
"""Return the visualized output"""
ret = ""
cmd_list = json.load(args.results)['cmd_list']
cmd_list = util.filter_cmd_list(cmd_list, args.labels_to_include, args.labels_to_exclude)
(cmd_list, label_map) = util.translate_dict(cmd_list, args.label_map)
... | 8a9e655adfc9713785f96ab487d579a19d9d09b2 | 10,695 |
def send_request(apikey, key_root, data, endpoint):
"""Send a request to the akismet server and return the response."""
url = 'http://%s%s/%s/%s' % (
key_root and apikey + '.' or '',
AKISMET_URL_BASE,
AKISMET_VERSION,
endpoint
)
try:
response = open_url(url, data=... | aea5ac8eb0b8b91002e680376c6f2647a631e58c | 10,696 |
def request_set_bblk_trace_options(*args):
"""
request_set_bblk_trace_options(options)
Post a 'set_bblk_trace_options()' request.
@param options (C++: int)
"""
return _ida_dbg.request_set_bblk_trace_options(*args) | 728d7e2a7a0ef0085d4bb72763b2a019d89896ec | 10,697 |
def range_str(values: iter) -> str:
"""
Given a list of integers, returns a terse string expressing the unique values.
Example:
indices = [0, 1, 2, 3, 4, 7, 8, 11, 15, 20]
range_str(indices)
>> '0-4, 7-8, 11, 15 & 20'
:param values: An iterable of ints
:return: A string of u... | 85dedc97342b07dcb2a8dda753768309aa31ed43 | 10,698 |
import json
def analyze(request):
"""
利用soar分析SQL
:param request:
:return:
"""
text = request.POST.get('text')
instance_name = request.POST.get('instance_name')
db_name = request.POST.get('db_name')
if not text:
result = {"total": 0, "rows": []}
else:
soar = Soa... | a033774727242783357a35a6608d7154f77bc016 | 10,699 |
import math
def sin(c):
"""
sin(a+x)= sin(a) cos(x) + cos(a) sin(x)
"""
if not isinstance(c,pol): return math.sin(c)
a0,p=c.separate();
lst=[math.sin(a0),math.cos(a0)]
for n in range(2,c.order+1):
lst.append( -lst[-2]/n/(n-1))
return phorner(lst,p) | a6ec312df4362c130343133dae9a09b377f56cf5 | 10,700 |
def _calc_metadata() -> str:
"""
Build metadata MAY be denoted by appending a plus sign
and a series of dot separated identifiers
immediately following the patch or pre-release version.
Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-].
"""
if not is_appveyor:
... | ccbd4912622808b5845d8e30546d6eb27e299342 | 10,701 |
import functools
def authorization_required(func):
"""Returns 401 response if user is not logged-in when requesting URL with user ndb.Key in it
or Returns 403 response if logged-in user's ndb.Key is different from ndb.Key given in requested URL.
"""
@functools.wraps(func)
def decorated_function(*p... | 12c0d645b0b26bf419e413866afaf1b4e7a19869 | 10,702 |
import torch
def pad_col(input, val=0, where='end'):
"""Addes a column of `val` at the start of end of `input`."""
if len(input.shape) != 2:
raise ValueError(f"Only works for `phi` tensor that is 2-D.")
pad = torch.zeros_like(input[:, :1])
if val != 0:
pad = pad + val
if where == '... | 77caa028bb76da922ba12492f077811d2344c2a9 | 10,703 |
from typing import List
import itertools
def seats_found_ignoring_floor(data: List[List[str]], row: int, col: int) -> int:
"""
Search each cardinal direction util we hit a wall or a seat.
If a seat is hit, determine if it's occupied.
"""
total_seats_occupied = 0
cardinal_direction_operations ... | e5442d757df6304da42f817c975969723ad0abca | 10,704 |
def product_design_space() -> ProductDesignSpace:
"""Build a ProductDesignSpace for testing."""
alpha = RealDescriptor('alpha', lower_bound=0, upper_bound=100, units="")
beta = RealDescriptor('beta', lower_bound=0, upper_bound=100, units="")
gamma = CategoricalDescriptor('gamma', categories=['a', 'b', '... | 93468cc7aaeb6a6bf7453d2f3e974bc28dece31f | 10,705 |
def compute_percents_of_labels(label):
"""
Compute the ratio/percentage size of the labels in an labeled image
:param label: the labeled 2D image
:type label: numpy.ndarray
:return: An array of relative size of the labels in the image. Indices of the sizes in the array \
is corresponding to the... | 6dfe34b7da38fa17a5aa4e42acc5c812dd126f77 | 10,706 |
def removepara(H,M,Hmin = '1/2',Hmax = 'max',output=-1,kwlc={}):
""" Retrieve lineal contribution to cycle and remove it from cycle.
**H** y **M** corresponds to entire cycle (two branches). I.e. **H**
starts and ends at the same value (or an aproximate value).
El ciclo M vs H se separa ... | 1d70c60f60b3ab7b976a0ec12a3541e5a7e53426 | 10,707 |
def flush():
"""
Remove all mine contents of minion.
:rtype: bool
:return: True on success
CLI Example:
.. code-block:: bash
salt '*' mine.flush
"""
if __opts__["file_client"] == "local":
return __salt__["data.update"]("mine_cache", {})
load = {
"cmd": "_m... | fe7d120362393fcb4380473cdaf76e153646644a | 10,708 |
def polygon_to_shapely_polygon_wkt_compat(polygon):
"""
Convert a Polygon to its Shapely Polygon representation but with WKT
compatible coordinates.
"""
shapely_points = []
for location in polygon.locations():
shapely_points.append(location_to_shapely_point_wkt_compat(location))
ret... | 54c889d2071cc8408c2bb4b739a30c3458c80f4c | 10,709 |
import six
def ccd_process(ccd, oscan=None, trim=None, error=False, masterbias=None,
bad_pixel_mask=None, gain=None, rdnoise=None,
oscan_median=True, oscan_model=None):
"""Perform basic processing on ccd data.
The following steps can be included:
* overscan corr... | 610a53693ff84ba2e1a68662dd0a19e55228c129 | 10,710 |
def get_role_keyids(rolename):
"""
<Purpose>
Return a list of the keyids associated with 'rolename'.
Keyids are used as identifiers for keys (e.g., rsa key).
A list of keyids are associated with each rolename.
Signing a metadata file, such as 'root.json' (Root role),
involves signing or verifyin... | 4888a09740560d760bfffe9eecd50bfa67ff0613 | 10,711 |
def _DX(X):
"""Computes the X finite derivarite along y and x.
Arguments
---------
X: (m, n, l) numpy array
The data to derivate.
Returns
-------
tuple
Tuple of length 2 (Dy(X), Dx(X)).
Note
----
DX[0] which is derivate along y has shape (m-1, n, l).
DX[1] ... | 4aff05c2c25089c9f93b762a18dad42b0142db09 | 10,712 |
def load_spectra_from_dataframe(df):
"""
:param df:pandas dataframe
:return:
"""
total_flux = df.total_flux.values[0]
spectrum_file = df.spectrum_filename.values[0]
pink_stride = df.spectrum_stride.values[0]
spec = load_spectra_file(spectrum_file, total_flux=total_flux,
... | 31d1cbbee8d999dac5ee0d7f8d4c71f7f58afc3b | 10,713 |
def included_element(include_predicates, exclude_predicates, element):
"""Return whether an index element should be included."""
return (not any(evaluate_predicate(element, ep)
for ep in exclude_predicates) and
(include_predicates == [] or
any(evaluate_predicate(elem... | 00e0d66db26e8bca7e3cb8505596247065422cb6 | 10,714 |
def _insertstatushints(x):
"""Insert hint nodes where status should be calculated (first path)
This works in bottom-up way, summing up status names and inserting hint
nodes at 'and' and 'or' as needed. Thus redundant hint nodes may be left.
Returns (status-names, new-tree) at the given subtree, where ... | 956fe03a7f5747f93034501e63cc31ff2956c2d6 | 10,715 |
def make_sine(freq: float, duration: float, sr=SAMPLE_RATE):
"""Return sine wave based on freq in Hz and duration in seconds"""
N = int(duration * sr) # Number of samples
return np.sin(np.pi*2.*freq*np.arange(N)/sr) | 622b03395da5d9f8a22ac0ac30282e23d6596055 | 10,716 |
def _widget_abbrev(o):
"""Make widgets from abbreviations: single values, lists or tuples."""
float_or_int = (float, int)
if isinstance(o, (list, tuple)):
if o and all(isinstance(x, string_types) for x in o):
return DropdownWidget(values=[unicode_type(k) for k in o])
elif _matche... | f5a57f2d74811ff21ea56631fd9fb22fea4ae91f | 10,717 |
def get_conditions():
"""
List of conditions
"""
return [
'blinded',
'charmed',
'deafened',
'fatigued',
'frightened',
'grappled',
'incapacitated',
'invisible',
'paralyzed',
'petrified',
'poisoned',
'prone',
... | 816ccb50581cafa20bdefed2a075a3370704cef4 | 10,718 |
def negative_predictive_value(y_true: np.array, y_score: np.array) -> float:
"""
Calculate the negative predictive value (duplicted in :func:`precision_score`).
Args:
y_true (array-like): An N x 1 array of ground truth values.
y_score (array-like): An N x 1 array of predicted values.
R... | 28f1d4fce76b6201c6dbeb99ad19337ca84b74c5 | 10,719 |
def flat_list(*alist):
"""
Flat a tuple, list, single value or list of list to flat list
e.g.
>>> flat_list(1,2,3)
[1, 2, 3]
>>> flat_list(1)
[1]
>>> flat_list([1,2,3])
[1, 2, 3]
>>> flat_list([None])
[]
"""
a = []
for x in alist:
if x is None:
... | 5a68495e507e9a08a9f6520b83a912cf579c6688 | 10,720 |
from typing import List
def do_regression(X_cols: List[str], y_col: str, df: pd.DataFrame, solver='liblinear', penalty='l1',
C=0.2) -> LogisticRegression:
"""
Performs regression.
:param X_cols: Independent variables.
:param y_col: Dependent variable.
:param df: Data frame.
... | 8a65d49e64e96b3fc5271545afe1761382ec1396 | 10,721 |
def gaussian_smooth(var, sigma):
"""Apply a filter, along the time dimension.
Applies a gaussian filter to the data along the time dimension. if the
time dimension is missing, raises an exception. The DataArray that is
returned is shortened along the time dimension by sigma, half of sigma on
... | 809ec7b135ab7d915dd62ad10baea71bfd146e34 | 10,722 |
import logging
def make_ood_dataset(ood_dataset_cls: _BaseDatasetClass) -> _BaseDatasetClass:
"""Generate a BaseDataset with in/out distribution labels."""
class _OodBaseDataset(ood_dataset_cls):
"""Combine two datasets to form one with in/out of distribution labels."""
def __init__(
self,
... | c1c26206e352932d3a5397f047365c8c5c8b7fa7 | 10,723 |
def _title_case(value):
"""
Return the title of the string but the
first letter is affected.
"""
return value[0].upper() + value[1:] | 037bce973580f69d87c2e3b4e016b626a2b76abb | 10,724 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.