content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_extreme(extreme, range_minimum, range_maximum):
"""
extreme : should be min or max
range_minimum::int : minimum value you want your extreme to be
range_maximum::int : maximum value you want your extreme to be
"""
if isinstance(extreme, str):
if extreme == "":
e... | d44d15310c83b1e2fcf03939cd1e7625f68f0b11 | 58,021 |
import torch
def predict(image_path, model, limit=5, gpu=False):
"""
Predict the class (or classes) of an image using a trained deep learning model.
:param image_path: string
:param model: model
:param limit: int Top K results that should be returned
:param gpu: bool
:returns: np.array, li... | e1da70ce9868139270dbf7772bbda0df0b402330 | 58,023 |
import tqdm
def morph_stc(stcs, subject_ids, subject_dir):
"""Morph stc inplace onto generic brain"""
morphed_stcs = []
for i, (stc, subject_id) in tqdm(enumerate(zip(stcs, subject_ids)),
total=len(stcs)):
try:
morph = mne.compute_source_morph(stc, ... | b26b0b73ebd214b6896bba132c8b43baae350230 | 58,024 |
def py2_strencode(s):
"""Encode a unicode string to a byte string by using the default fs
encoding + "replace" error handler.
"""
if PY3:
return s
else:
if isinstance(s, str):
return s
else:
return s.encode(ENCODING, ENCODING_ERRS) | 9aa76af9e96e69cb1cd7765ad22cb9ccd5a46d79 | 58,025 |
import shutil
def rename(path: str, target: str):
"""Copy path to target."""
return shutil.move(path, target) | 00f46f2557f4e0e7bd07610889a8c2deb028f24a | 58,026 |
def compute_moments(log_both, logit_rho, log_scale, phi, pi, theta, psi):
"""Compute the means and variances implied by the paramters."""
rho = special.expit(logit_rho)
vol_mean = np.exp(log_both) / (1 - rho)
vol_var = ((2 * np.exp(log_scale) * rho * vol_mean + np.exp(log_scale)**2
* np... | 0eea3c59c6d6d4be21ac0860c987760f40cd98af | 58,027 |
def render_latex(root_node, width=0, **options):
"""Render a node tree as a LaTeX document.
"""
options = make_options(**options)
return _cmark.render_latex(root_node, options, width) | a4f18f9474cd0d0aa56f51d3525c51d26c7fc9be | 58,028 |
import socket
def check_port_occupied(port, address="127.0.0.1"):
"""
Check if a port is occupied by attempting to bind the socket
:return: socket.error if the port is in use, otherwise False
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((address, port))
ex... | 5919e228c835ceb96e62507b9891c6a1ce5948fa | 58,029 |
import timeit
def heap_remove(N, num):
"""Run a single trial of num heap remove requests. Make sure that num < N."""
return 1000*min(timeit.repeat(stmt='''
for _ in range({}):
heapq.heappop(h)'''.format(num),
setup = '''
import heapq
h = []
for i in range(0,2*{},2):
heapq.heappush(h, i)'''.for... | 19101cd920904a2384aaec62b23dc169bdfe6dae | 58,030 |
def inverseExtend(boundMethod, *args, **kargs):
"""Iterate downward through a hierarchy calling a method at each step.
boundMethod -- This is the bound method of the object you're interested in.
args, kargs -- The arguments and keyword arguments to pass to the
top-level method.
You can call t... | a511470f6cd3d86de19cc95e489498e649bea7a5 | 58,032 |
import gettext
def p_sign_up(
username,
password,
password2,
code,
email=None,
mobile_phone_number=None):
"""
普通用户注册函数
:return:
"""
data = {}
if current_user.is_authenticated:
data['msg'] = gettext("Is logged in")
data["msg_type"]... | 5b8ccd13ebb483c9198e7576816d89b4d6898b1a | 58,033 |
def is_intent_completed(
s_i: int,
option_id: option_utils.Options,
s_f: int,
intent_id: Intents,
) -> IntentStatus:
"""Determines if a (state, option, state) transition completes an intent.
Args:
s_i: (Unused) The integer representing the taxi state.
option_id: (Unused) The integer rep... | 96ab19f7527b8cadfdbaf148c2871a80d984c418 | 58,034 |
def inv_monitor_nonlinearity(x, x_gamma_function):
"""Monitor colour displaying is not linear but follows x^gamma function.
Convert monitor scale back to linear image float values.
parameters:
- x: image as numpy.ndarray (floats in [0,1])"""
# clip values that are too small or too large
x[... | 4969a49da207abaa0e17847f9bc5381608416a03 | 58,035 |
def jpg_image_to_array(image_path):
"""
Loads JPEG image into 3D Numpy array of shape
(width, height, channels)
"""
with Image.open(image_path) as image:
im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
im_arr = im_arr.reshape((image.size[1], image.size[0], 1))
return im_... | 8c188c2199dd1a074d1c1eb9ac032280ab6cd713 | 58,036 |
def dict2func(d):
"""Converts all strings in a dictionary to their
corresponding functions (if applicable)"""
res = dict()
for k, v in d.items():
if isinstance(v, dict):
res[k] = dict2func(v)
else:
res[k] = str2func(v)
return res | ddb74e6d6e877a85d6881354e0064596efd2f27d | 58,037 |
def _midpoints_1d(arr, frac=0.5, axis=-1):
"""Return the midpoints between values in the given array.
If the given array is N-dimensional, midpoints are calculated from the last dimension.
Arguments
---------
arr : ndarray of scalars,
Input array.
frac : float,
Fraction of the ... | b95d376a98dbfa5fc98a5892686f39df557cc65b | 58,038 |
def _run_once_sucessfully(f):
"""
Decorator that uses a cache to flag an action as already executed, and check to
ensure that it hasn't been executed before running (in the event of retries,
multiple failures).
:param f: a function/method to run only once.
"""
def inner(self, *args, **kwarg... | bf1cc23ca7dd7f8aac994acdc15778dd520d02cc | 58,039 |
def get_source_tag (aligned_dict, src_word_tag_dict):
"""Get the aligned (source) tag for each word in each sentence of target language from a source language"""
tar_tag_dict = {} # create a dict to store predicted tag for tar language
print("get source tag")
for sentence_cnt in aligned_dict.keys():
... | ccd4fe0a2a0d1a13c553c7392f7876979729de1c | 58,040 |
import torch
import math
def cal_GauProb(mu, sigma, x):
"""
Arguments:
mu (BxMxC) - The means of the Gaussians.
sigma (BxMxC) - The standard deviation of the Gaussians.
x (BxC) - A batch of data points (coordinates of position).
Return:
probabilities (BxM): proba... | 6625878d6dd199b106bbb48336fc52f52e8c1f4f | 58,041 |
from typing import Dict
def determine_postAST_from_filename(filenamesplit) -> Dict:
"""determine postAST from filenamesplit"""
basepf_split, postAST = filenamesplit, ""
if all([i in basepf_split for i in ("post", "AST")]):
if any(s in basepf_split for s in ["LC"]):
if "postAST_LC" in ... | 3787dcef3ae65538f2fe66f98be60cc0f71f7790 | 58,042 |
def getPrivacyList(disp, listname):
"""
Requests specific privacy list listname. Returns list of XML nodes (rules)
taken from the server responce.
"""
try:
resp = disp.SendAndWaitForResponse(Iq("get", NS_PRIVACY, payload=[Node("list", {"name": listname})]))
if isResultNode(resp):
return resp.getQueryPayload... | 3c8dc760df11907793b768459b16f62499c0709a | 58,043 |
def modified_fisher_transform(r: float, n: int) -> float:
"""Returns a Fisher's z modified by dividing it by the standard error."""
z = atanh(r)
inverse_standard_error = sqrt(n - 3)
return z * inverse_standard_error | 8b4b652c87be85536459f9aa4a93f9e8f89880a5 | 58,044 |
import html
def indicator(color, text, id_value):
"""
Builds a new Dash div styled as a container, with borders and background.
:param str color: background color of the container (RGB or Hex colors).
:param str text: name to be plotted inside the container.
:param str id_value: identifier of the... | 7cbb68cbe09b07eb8a549825f80129c3b6720fc6 | 58,045 |
def pack(fmt, *args):
"""
Return string containing values v1, v2, ... packed according to fmt.
See struct.__doc__ for more on format strings.
"""
try:
o = _cache[fmt]
except KeyError:
o = _compile(fmt)
return o.pack(*args) | 61d8bbfe5c210045bfc3fb2196b5a5291f47aa6a | 58,046 |
def require_context(f):
"""Decorator to require *any* user or admin context.
This does no authorization for user or project access matching, see
:py:func:`authorize_project_context` and
:py:func:`authorize_user_context`.
The first argument to the wrapped function must be the context.
"""
... | 83fac830883968bf62b4e04ea3dad3ef4c619caf | 58,047 |
def get_reg_info(*args):
"""get_reg_info(char regname, ulonglong mask) -> char"""
return _idaapi.get_reg_info(*args) | 77790803e8b21b1a6b063f9f496579b64757b5a3 | 58,048 |
def pretty(data, corner = '+', separator='|', joins='-'):
"""
Parameters :
~ data : Accepts a dataframe object.
~ corner : Accepts character to be shown on corner points (default value is "+").
~ separator : Accepts character to be shown in place to the line separating two values (default value... | 812fb5d255c5e44c1d026d307e2a39c7b3c31f14 | 58,049 |
import torch
def double_observation(f: torch.Tensor) -> torch.Tensor:
"""Double observation vector as (A, B, C, D) --> (A, A, B, B, C, C, D, D)
Args:
f: Observation vectors (n_batch, ...)
Returns:
Observation vectors (2*n_batch, ...)
"""
return torch.repeat_interleave(f, 2, dim=0... | 06f8e9acf3f62cd0d75a0a69451625fe4bdc8659 | 58,050 |
import csv
def write_rows(rows, filename, sep="\t"):
"""Given a list of lists, write to a tab separated file"""
with open(filename, "w", newline="") as csvfile:
writer = csv.writer(
csvfile, delimiter=sep, quotechar="|", quoting=csv.QUOTE_MINIMAL
)
for row in rows:
... | 41e04ee6203baf7db2d08722aed76dfacbc9e838 | 58,051 |
import collections
def context():
"""A mock for the lambda_handler context parameter."""
Context = collections.namedtuple('Context', 'function_name function_version')
return Context('TestFunction', '1') | b7d65ca7ff87aea1bd22e87dba4cb2d0e5ec411d | 58,052 |
def get_pa_type_factory(pa_type):
"""return type factory"""
if pt.is_int8(pa_type):
return pa.int8
elif pt.is_int16(pa_type):
return pa.int16
elif pt.is_int32(pa_type):
return pa.int32
elif pt.is_int64(pa_type):
return pa.int64
elif pt.is_uint8(pa_type):
... | 01063af85f556fdd2e67d1935c75b54532d25b84 | 58,053 |
def iscircular(linked_list):
"""
Determine wether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
"""
if linked_list.head is None:
return False
... | 874073d433f1a3069ca250379b4855303f5a6510 | 58,054 |
def controller_encryption_exists(handle, controller_type, controller_slot,
server_id=1):
"""
Checks if encryption is enabled on the controller
Args:
handle (ImcHandle)
controller_type (str): Controller type
'SAS'
contro... | 02d17aebbf7508a94308f37c524bd056b96d531f | 58,055 |
import torch
def make_one_mask_target(cfg, mode, input, sampled_proposal, sampled_assign, truth_box, truth_mask):
"""
Deprecated.
Was used for generating mask for MaskRcnn
"""
sampled_mask = []
mask_crop_size = cfg['mask_crop_size']
for i in range(len(sampled_proposal)):
_, D, H, ... | 0e9ddf14b5fe8c4d0b453b6c64b9859ae5e8dcc8 | 58,056 |
import tqdm
def chamfer_hausdorff_dists_block_wise(X0, X1, sub_batch_size=10000):
"""
Compute one-sided Chamfer and Hausedorf distances and Chamfer and Hausedorf distances in the block-wise manner.
"""
def chamfer_hausdorff_oneside_dists(X0, X1):
b0 = X0.shape[0]
b1 = X1.shape[0]
... | ce047cf3e61965d5e5c9a08cf5fe64b5b3c7a2a5 | 58,057 |
def sample_with_replacement(population, k, n=None):
"""
Return a sample of size k with replacements chosen from the population.
If n is set, an array of size n containing samples of size k is returned.
:param population:
:param k: size of the sample
:param n: number of samples
:return: n (o... | 00a2f17276812c4e775e13d8e3391aece9c65047 | 58,058 |
def cartesian_regions_to_slices(regions):
"""
Convert a sample region(s) string, consisting of a comma-separated list
of (colon-or-hyphen-separated) pixel ranges into Python slice objects.
These ranges may describe either multiple 1D regions or a single higher-
dimensional region (with one range pe... | b1ec8ec783f5ea380fd665888131733d0b4b1833 | 58,059 |
import typing
def build_charge_table(charges: typing.List[Charge], page_number: int)\
-> FlexibleColumnWidthTable:
"""
This function builds a Table containing itemized billing information
:param typing.List[Charge] charges: the rows on the invoice
:param int page_number: Current page number... | 79039651de64081662350b2cc27e0bbe77958c1d | 58,060 |
def count_occurence_of_character_in_neighbour_squares(x, y, board, character):
"""
returns the number of neighbours of (x,y) that are bombs. Max is 8, min is 0.
"""
num_rows = len(board[0])
num_cols = len(board)
squares = neighbour_squares(x, y, num_rows, num_cols)
character_found ... | 1d9e2ef22e1f61c51845417e9c036943e66283a5 | 58,062 |
from typing import Sequence
from typing import List
from typing import Set
def remove_overlapping_lane_seq(lane_seqs: Sequence[Sequence[int]]) -> List[Sequence[int]]:
"""
Remove lane sequences which are overlapping to some extent
Args:
lane_seqs (list of list of integers): List of sequence of lan... | b9489dfd7c592c1a41a323627bb974b92f3257ab | 58,063 |
def _generate(n, pi, mu, random_state=None):
"""
Generate samples from an EMM.
Parameters
----------
n : int
Sample size.
pi : array
Mixing weight of the individual exponential distribution in the EMM.
mu : array
Mean of the individual exponential distribution in the... | e8a78b16d1b84669189a986fa51c1d2b71fca6c4 | 58,065 |
def _auth_handler():
"""
Requrired JWT method
"""
return None | 9ec5301d6e32c7b3016a92ba9ae89d22fed3bad5 | 58,066 |
def validate_experimental(context, param, value):
"""Load and validate an experimental data configuration."""
if value is None:
return
config = ExperimentConfiguration(value)
config.validate()
return config | a486f76a5c9006fbdd765c7c682bea237a445d90 | 58,067 |
def todatadict(data):
"""Reorganize tuple of dicts into single dict where keys are defined by ID
and NAME, values are numerical data corresponding to RPKM values
:param data: tuple of dicts from loaded cleaned data
:returns: dict containing reorganized data
"""
full = nest(get(0), dict.keys, tu... | 5b95ac1030cccf405a38bd8e00114c53598ca317 | 58,068 |
def HKL2string(hkl):
"""
convert hkl into string
[-10.0,-0.0,5.0] -> '-10,0,5'
"""
res = ""
for elem in hkl:
ind = int(elem)
strind = str(ind)
if strind == "-0": # removing sign before 0
strind = "0"
res += strind + ","
return res[:-1] | 325ddfcb2243ce9a30328c5b21626a4c93a219de | 58,069 |
def evaluate_models(dataset,
p_values,
d_values,
q_values,
training_portion=0.66):
"""
Fucntion to tune hyperparameters of arima model
Parameters
----------
dataset : array or list
All dataset.
p_values : in... | 931129f351fcd749b2e9c80c61a4ec5632285e14 | 58,070 |
import plan2scene.texture_prop.graph_generators as graph_generators
def get_graph_generator(conf: ConfigManager, graph_generator_def: Config, include_target: bool):
"""
Creates graph generator given the graph generator configuration.
:param conf: Config manager.
:param graph_generator_def: Graph gener... | 4b60d7e00fd16a447a956db8e77c7847cde65966 | 58,071 |
import base64
import six
import requests
import json
from datetime import datetime
def fetch_refreshed_token(refresh_token):
""" Fetches a new access token using refresh token """
payload = {'grant_type': 'refresh_token', 'refresh_token': refresh_token}
auth_headers = base64.b64encode(six.text_type(CLIENT... | c3a42504c345b630728cab253e6de2ee0e4d3937 | 58,074 |
import re
def splitAtUppercase(a_string):
"""assumes a_string is a string
returns a list of strings, a_string split at each uppercase letter"""
pattern = "([A-Z])"
string_list = re.split(pattern, a_string)
return string_list | 5cbf4673ee46db81b8acfb30bfe64a44d10d0d9a | 58,075 |
def send_sms(destination, message):
"""
Sends an sms message using AWS SNS.
Args:
destination (str): Required. The sms number to send to.
message (str): Required. The message to be sent.
Returns:
The AWS response.
"""
client = boto3.client('sns', region_name='eu-west-1... | 50bbfa763c11e57de378a819a107c3b7a4720706 | 58,076 |
from typing import List
def should_expand_range(numbers: List[int], street_is_even_odd: bool) -> bool:
"""Decides if an x-y range should be expanded."""
if len(numbers) != 2:
return False
if numbers[1] < numbers[0]:
# E.g. 42-1, -1 is just a suffix to be ignored.
numbers[1] = 0
... | fcd5a8e027120ef5cc52d23f67de4ab149b19a2c | 58,077 |
def get_all_bababooeys() -> list:
"""
Returns all permutations of "bababooey" with acceptable character substitutions.
:return: list of all bababooeys
"""
substitutions = {
'b': '🅱️',
'o': '0',
'e': '3',
}
char_possibilities = []
for c in 'bababooey':
su... | a6275d64cf3c498a5472d594941615575b86b25f | 58,078 |
def from_inches(unit, val):
"""Convert val in inches to unit."""
return _FROM_INCHES[unit](val) | 1ac86745f83e333fc6eff27c2fcc980521ad1727 | 58,079 |
def zyx_to_yxz_dimension_only(data, z=0, y=0, x=0):
"""
Creates a tuple containing the shape of a conversion if it were to happen.
:param data:
:param z:
:param y:
:param x:
:return:
"""
z = data[0] if z == 0 else z
y = data[1] if y == 0 else y
x = data[2] if x == 0 else x
... | 2477976f795f5650e45214c24aaf73e40d9fa4eb | 58,080 |
def _get_params(deep: bool) -> str:
"""
Get parameters for this estimator.
:param deep: If True, will return the parameters for this estimator and
contained subobjects that are estimators.
:type deep: bool
:param return: Parameter names mapped to their values.
:type return... | f8904a8db8f791b97f485a5cd98285aee9eed6b9 | 58,081 |
def mse_l1_sparsity(x, x_hat, concepts, sparsity_reg):
"""Sum of Mean Squared Error and L1 norm weighted by sparsity regularization parameter
Parameters
----------
x : torch.tensor
Input data to the encoder.
x_hat : torch.tensor
Reconstructed input by the decoder.
concepts : tor... | cabb269caf826348909ccf42f3d26582ae02777b | 58,082 |
def CalculateChi10p(mol):
"""
#################################################################
Calculation of molecular connectivity chi index for path order 10
---->Chi10
Usage:
result=CalculateChi10p(mol)
Input: mol is a molecule object.
... | 340227613b9e561802c0fbc40bfe8e4c6d49af31 | 58,083 |
def binary_log_loss(Y, P):
"""
Compute negative log loss
"""
N = len(Y)
# Clip values very close to 1 or 0
P = np.clip(P, EPS, 1 - EPS)
# Negative log likelihood function
mask0 = (Y == 0) # label = 0 observations
mask1 = (Y == 1) # label = 1 observations
nll = -(np.log(P[mask1]... | 1f2a5d6b714d32851e8388e1162f9c37e9169ac4 | 58,084 |
def run_policy(
policy_and_value_net_apply,
observations,
lengths,
params,
state,
rng,
vocab_size,
observation_space,
action_space,
rewards_to_actions,
):
"""Runs the policy network."""
policy_input = _prepare_policy_input(
observations, vocab_size, observation_space, a... | be76524d40758f0083657e62b7a9230b81cddd41 | 58,085 |
def make_vagrant_unit_factory(branch):
"""
This returns the factory that runs the Vagrant unit tests.
"""
f = BuildFactory()
f.addStep(Git(repourl="git://github.com/mitchellh/vagrant.git",
branch=branch,
mode="full",
method="fresh",
... | 74b058410fcecafeabee3589d96730849a522a79 | 58,086 |
def _find_non_suppressed_predicates(predicates, validity_intervals):
"""Returns the predicates that are left after suppression operations.
:param predicates: A sequence of predicates in the form of TimedPropertyGraph objects.
:param validity_intervals: The intervals during which corresponding predicates ho... | 69aa7b419624e911ca9dc05bc071989f78ee6cfb | 58,087 |
def handle_market_cap(request):
"""
Generate response to intent type MarketCapIntent with the current market cap of the ticker.
:type request AlexaRequest
:return: JSON response including market cap of the ticker
"""
ticker = request.get_slot_value(slot_name="stockTicker").upper()
# Query D... | a46d9aee35581abd8766fd59c7cc207ac0376687 | 58,088 |
import six
import json
def _safe_match_string(value):
"""Sanitize and represent a string argument in MATCH."""
if not isinstance(value, six.string_types):
if isinstance(value, bytes): # should only happen in py3
value = value.decode('utf-8')
else:
raise GraphQLInvalidA... | 7e6c06af244379b274fcf71ce97d1291808ace84 | 58,090 |
def first_supported_filter(test, runner):
"""Get the first filter supported by the server
Arguments:
test (Node): reference to Node object
runner (Runner): reference to Runner object
Returns:
(dict): single (first) request filter
"""
return single_supported_filter(test... | a5b00124ad48f429ba9ef435661fcb2f63ad9d52 | 58,091 |
import functools
def remotable_classmethod(fn):
"""Decorator for remotable classmethods."""
@functools.wraps(fn)
def wrapper(cls, context, *args, **kwargs):
if NovaObject.indirection_api:
result = NovaObject.indirection_api.object_class_action(
context, cls.obj_name(), ... | 5f5e25b294df7e755c8ed6b921150552474be7dd | 58,092 |
def gen_anonymous_varname(column_number: int) -> str:
"""Generate a Stata varname based on the column number.
Stata columns are 1-indexed.
"""
return f'v{column_number}' | f0e150300f7d767112d2d9e9a1b139f3e0e07878 | 58,093 |
def min_version(the_module, min_version_str: str = "") -> bool:
"""
Convert version strings into tuples of int and compare them.
Returns True if the module's version is greater or equal to the 'min_version'.
When min_version_str is not provided, it always returns True.
"""
if min_version_str:
... | 2ab3d5c3a9b2fd1c938ddd3f7967d8df7c5b6c77 | 58,095 |
def inspect_file_attrs(f_path_or_f_obj):
"""
List out the attributes of some HDF5 file object.
If a path is provided, then it will open the file in
read mode.
Examples:
.. code-block:: python
import h5py
from support.hdf5_util import inspect_file_attrs
file_path = "e... | a7ede3aac50c93a048bc188e2e6795586ec3eac2 | 58,097 |
def strip_name(s):
""" Strips the name per RE_STRIP_NAME regex.
>>> strip_name('Login')
'Login'
>>> strip_name('LoginHandler')
'Login'
>>> strip_name('LoginController')
'Login'
>>> strip_name('LoginPage')
'Login'
>>> strip_name('LoginView')
... | 6cc3956bcb9e4696a1a434ccb654ac519d24b443 | 58,098 |
def api_queuelist():
""" Api Method that return the number of remaining itens in queue """
return str(len(link_queue)) + '\n' | 48d21f6420dd8065f796f0697cad26dd416592a1 | 58,099 |
def create_city_map(n: int) -> set:
"""
Generate city map with coordinates
:param n: defines the size of the city that Bassi needs to hide in,
in other words the side length of the square grid
:return:
"""
return set((row, col) for row in range(0, n) for col in range(0, n)) | fd30b936647bae64ccf2894ffbb68d9ad7ec9c6b | 58,100 |
def merge_layers(input_layer: str = None,
merge_layer: str = None,
merging_attributes: str = """[]""",
output_name: str = None,
context: str = None,
gis=None) -> str:
"""
Combines two inputs of the same feature data type into a n... | a5d263e8ece9ff3ba3999dd0927dba25abb580b5 | 58,101 |
def delete_all_users(): # noqa: E501
"""Delete all users
Delete all users # noqa: E501
:rtype: object
"""
try:
DbUser.objects.delete()
res = {}
status = 200
except Exception as error:
status = 500
res = Error("Internal error", status, str(error))
re... | 679b012ce23875fc2ed5f9454414d06fd029d6cd | 58,103 |
def nullable(datatype):
"""Return the signature of a scalar value that is allowed to be NULL (in
SQL parlance).
Parameters
----------
datatype : ibis.expr.datatypes.DataType
Returns
-------
Tuple[Type]
"""
return (type(None),) if datatype.nullable else () | fe5935d1b4b1df736933455e97da29a901d6acb1 | 58,104 |
def calculate_optimal_capacities_tree(mu,sigma,gamma,K):
""" Calculate the optimal capacities for the five node tree network without allowing
to close the loop. These capacities can be calculated explicitly using the method of Lagrange multipliers (see Eq. 9)"""
flow_correlations = np.array([4*mu**2+2*sigma... | b4f74dbb9cebd666c6281f7436c9e24f19c83436 | 58,105 |
def dustVel_phi(f):
"""
Cylindrical tangential component of the dust velocity in the x-y plane
"""
return sutil.polar_phi_hat(f, 'u_dustVel') | 71a242d79ce7fc958c8d2f16c6a730bd901b2b38 | 58,106 |
def build_facets(data):
""" Data from facets-serves.json
Data structure:
{ "services" : [
{"(type)": "quolab...ClassName",
"id": "<name>"}
] }
"""
deprecated = {"casetree", "cache-id", "indirect"}
services = [service["id"] for service in data["services"]
if ... | 1b617180a3a5d3115c5300b91eebb3d6ca079942 | 58,108 |
from typing import Dict
def make_country_dict(
csv_file:str = 'data/country_list.csv') -> Dict[str, str]:
"""Make a dictionary containing the ISO 3166 two-letter code
as the key and the country name as the value. The data is read
from a csv file.
"""
country_dict = {}
with open(csv_fi... | 0334a2b2c918f407d1df682f56c14943f1e66c43 | 58,109 |
import random
def get_samples_for_activation(class_names, X_val, Y_val):
"""get_samples_for_activation.
Returns sample images from the given data.
Sample images contain one image per class in the dataset.
:param class_names: class names of the dataset.
:param X_val: features of the dataset.
:... | 8d8a105cefb4e1b875e47f7010b32e9567c4ab60 | 58,111 |
def plot_pcolormesh(axis1,axis2,facedata,data,name,name2,surlabel,xlabel,ylabel,rotate):
"""
Plots parameter values for each cell using the pcolormesh function. Uses the corner point values output by corner_point_vals()
"""
if info==True:
print ('Making pcolormesh (colored_cells) of %(name)s sur... | 536010bcbe648e58bbde99e7893885a48a6080ab | 58,113 |
import platform
def host_arch_target():
"""
Converts the host architecture to the first part of a target triple
:return: Target host
"""
host_mapping = {
"armv7l": "arm",
"ppc64": "powerpc64",
"ppc64le": "powerpc64le",
"ppc": "powerpc"
}
machine = platform.m... | 7cae48c32e03cecb42e29279a93013ad3529c978 | 58,114 |
import torch
def prepare_img_cv2(img, dims):
"""
prepare image for forward pass.
returns a Tensor
"""
# type check
if not isinstance(img, np.ndarray):
raise TypeError("expected <np.ndarray>. got <{}>".format(type(img)))
img_dims = (img.shape[1], img.shape[0])
_img = (lett... | 2fbd5e2748229cd3916c89585dc4a0000f133fcc | 58,115 |
import regex
def safe_filename(filename, replacement="_"):
"""
Replace unsafe filename characters with underscores. Note that this does not
test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as... | 0b7eff36482832a2a4615013be67a2a3fad7370b | 58,116 |
def most_words():
"""Return the session where most words were written"""
session_dict = {}
with open(trackdata_path, 'r') as t_d:
t_data = t_d.readlines()
for line in t_data:
t_ses = line.strip().split(', ')
session_id = t_ses[0]
session = Session(session_... | 8acc3332baf277000ecb0cc474843675f76087b4 | 58,117 |
import requests
import json
def ocr_space_url(overlay=False, api_key='must specify your own apikey', language='eng'):
""" OCR.space API request with remote file.
Python3.5 - not tested on 2.7 Register here to get free api key: -> https://ocr.space/ocrapi
:param url: Image url.
:param overlay: Is O... | ff16f026262383ccfca4b3de91d2b1fa09bbde32 | 58,118 |
from typing import List
def get_reputation_data_statuses(reputation_data: List) -> List[str]:
"""
collects reported statuses of reputation data
Args:
reputation_data: returned data list of a certain reputation command
Returns: a list of reported statuses
"""
reputation_statuses = [sta... | 2c41344f2970243af83521aecb8a9374f74a40ac | 58,119 |
def get_users_groups(db_session):
"""
Fetch current db users and groups.
"""
all_users = db_session.execute(sa.select([users]))
all_groups = db_session.execute(sa.select([groups]))
old_user_admin = [user for user in all_users if user.user_name == OLD_USER_ADMIN]
old_user_users = [user for us... | 707839c17e343a72867062c5531508353494be09 | 58,120 |
def is_number(val):
"""Check if a value is a number by attempting to cast to ``float``.
Args:
val: Value to check.
Returns:
True if the value was successfully cast to ``float``; False otherwise.
"""
try:
float(val)
return True
except (ValueError, TypeErr... | 89728d3d199c3ef5885529da5a2d13dd94fa590f | 58,121 |
def _GetBuildTestStatus(build_dict):
"""Get the build test status for the given build.
Fetch the build test status file from the builder for the build number,
specified in the build info dictionary given by |build_dict|.
Args:
build_dict: Build info dictionary.
Returns:
Build Test Status dictionary... | 94bf7ddf418b1f4d844de03ebd5f9d42c4fd22cc | 58,122 |
def test_do_svr():
"""
Test calling the Support Vector Regressor,
Fit the weight on the training set
Input
------
X: dataframe, n*m, n is number of data points,
m is number of features
y: experimental electrical conductivity
Returns
------
svr: objective, the ... | decbd49007bd7384190dc861f1c77d420298c756 | 58,123 |
def get_mean_coords(
aln_1, coords_1: np.ndarray, aln_2, coords_2: np.ndarray
) -> np.ndarray:
"""
Mean of two coordinate sets (of the same shape)
"""
mean_coords = np.zeros((aln_1.shape[0], coords_1.shape[1]))
for i, (x, y) in enumerate(zip(aln_1, aln_2)):
if x == -1:
mean_c... | f8d0c5dfe17484148378b45fbeaa2c598d5d71ac | 58,124 |
def Nabla_continuous(k_space,s_space=None,kfield=None):
"""
This function returns the differential operator represented in Fourier
space.
i 2 \pi \vec{k}
"""
if(about.hermitianize.status):
print 'It is not recommended to calculate derivatives in'
print 'Fourier s... | 7b88060e58fb3c3c000d8e2139797cfe0320e637 | 58,125 |
def get_local_name(element):
"""
Just the element name with the schema URI (if any) removed
@type element: Element
@param element: The XML element
@rtype: string
@return: the base name of the element or None if it could not be determined
"""
if element is None:
ret... | cef42ed650b2798c623f220686364f257e5f385f | 58,126 |
def read_csv(path, *args, **kwargs):
"""Emulates `pd.read_csv` from Pandas, but as a Beam PTransform.
Use this as
df = p | beam.dataframe.io.read_csv(...)
to get a deferred Beam dataframe representing the contents of the file.
"""
return _ReadFromPandas(pd.read_csv, path, args, kwargs) | c5f3e510c957997fb242c8541fedd3e699529878 | 58,127 |
def CheckPlayerWin(copy, available_numbers, size, player_icon, board):
"""Check if the player can win, if they can return the number that would block it"""
#duplicate = a dupilacate list of the current board
#duplicate_numbers = a duplicate list of the available numbers
for x in range(size):
... | 803d85163ca02762232a0eab199e2bb234b2df98 | 58,128 |
def compute_beta(T, S, z, rn_b0=rn_b0, rn_lambda2=rn_lambda2, rn_mu2=rn_mu2, **_):
"""
Compute the haline contraction
"""
Ta = T - T0
Sa = S - S0
beta = 1 / rho0 * rn_b0 * (1 - rn_lambda2 * Sa - rn_mu2 * z)
return beta | ebeeabad5dad3a848df9be6df8ca21b8d246484c | 58,129 |
def format_rfc3339(datetime_instance):
"""Formats a datetime per RFC 3339."""
return datetime_instance.isoformat("T") + "Z" | ad60a9e306e82554601efc1ae317296a59b009b0 | 58,130 |
def delete_employee(request, pk):
"""
View that enables to delete an employee
"""
EmployeeInput.objects.filter(id=pk).delete()
return redirect('/add_employees/') | 5d83ea573111584d39117a540114f643d2ec4f22 | 58,131 |
import random
async def exchange_random_row(individual_1: list, individual_2: list) -> list:
"""Exchange Random Row
This function is used for making the crossover between two individuals, in picks a random row an exchange it between the two
given individuals.
Args:
individual_1 (list): The ... | d029ee3084c89f6c4e42e0941997ffea6f3a3e67 | 58,132 |
def parse_arguments(args: list) -> Namespace:
"""Parses the arguments passed on invocation in a dict and return it"""
parser = ArgumentParser(description="A tool to combine multiple merge tools")
parser.add_argument('-b', '--base', required=True)
parser.add_argument('-l', '--local', required=True)
... | 1bdad99ba963bc00c37c40322c71eafd4cc8ce8e | 58,133 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.