content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import hashlib
def get_checksum(file_name: str) -> str:
"""Returns checksum of the file"""
sha_hash = hashlib.sha224()
a_file = open(file_name, "rb")
content = a_file.read()
sha_hash.update(content)
digest = sha_hash.hexdigest()
a_file.close()
return digest | 6bb506accc6aa7826976a2d8033116dcff2f4a55 | 3,631,400 |
from sys import path
def find_tool(name, additional_paths = [], path_last = False):
""" Attempts to find tool (binary) named 'name' in PATH and in
'additional-paths'. If found in path, returns 'name'. If
found in additional paths, returns full name. If the tool
is found in several direc... | f43dfaab2044832703072943bbc0545c8f636e74 | 3,631,401 |
def sync_grains(name, **kwargs):
"""
Performs the same task as saltutil.sync_grains module
See :mod:`saltutil module for full list of options <salt.modules.saltutil>`
.. code-block:: yaml
sync_everything:
saltutil.sync_grains:
- refresh: True
"""
return _sync_sing... | ae8847df3ce84cf63748ded81c79fb9286e9d356 | 3,631,402 |
import torch
from typing import Union
from typing import Tuple
def masked_topk(
input_: torch.FloatTensor,
mask: torch.BoolTensor,
k: Union[int, torch.LongTensor],
dim: int = -1,
) -> Tuple[torch.LongTensor, torch.LongTensor, torch.FloatTensor]:
"""
Extracts the top-k items along a certain dim... | bdf84849f24deb23e183e825227c98e1c9db03f6 | 3,631,403 |
def bessel_kve(v, z, name=None):
"""Computes exponentially scaled modified Bessel function of the 2nd kind.
This function computes `Kve` which is an exponentially scaled version
of the modified Bessel function of the first kind.
`Kve(v, z) = Kv(v, z) * exp(abs(z))`
Warning: Gradients with respect to the fi... | 1c580585811391b007d2c37b6d08e85d9098b3f0 | 3,631,404 |
def cvReleaseConDensation(*args):
"""cvReleaseConDensation(PyObject obj)"""
return _cv.cvReleaseConDensation(*args) | ba8ebc2bc39d6d4792831c7f4025ace8a24d72d6 | 3,631,405 |
def solution(num_buns, num_required):
"""
Each choice of num_required-1 of the num_buns determines a missing key.
Therefore, we use binom[num_buns,num_required-1] different keys.
Each key is used in each num_buns-num_required+1 bunny.
Therefore, each key is repeated num_buns-num_required+1 times.
... | 4ff53d7c9e2b8bbfe348440bb702f965879bd6b6 | 3,631,406 |
import urllib
from datetime import datetime
import ssl
import socket
import json
def check_SSL_certificate(url, verbose):
""" Check SSL certificate expiration date of a server hostname """
hostname = urllib.parse.urlparse(url).hostname
port = urllib.parse.urlparse(url).port
if verbose == 1:
... | d8d1c3218a111d2f850c6bfa50b46a20dddb84b8 | 3,631,407 |
from datetime import datetime
def isToday(date_str):
"""
Check whether the last_checkt_time is today.
:param date:
:return:
"""
today = datetime.datetime.today()
date = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M')
return today.year == date.year and today.month == date.month a... | 2e80d602a1370583b0ee2e7c404f6838ac9e2db3 | 3,631,408 |
from mpl_toolkits.mplot3d.axis3d import Axis
def mpl_3d_remove_margins():
"""
Remove thin margins in matplotlib 3d plots.
The Solution is from `Stackoverflow`_.
.. _Stackoverflow:
http://stackoverflow.com/questions/16488182/
"""
if not hasattr(Axis, "_get_coord_info_old"):
d... | 10c208ecc11859ab34c66648adcefa23e98ff9d9 | 3,631,409 |
import os
import subprocess
import json
import requests
def try_compute_data(s3, webhook, old_data):
"""
Try to run the scraper and return course data. If something goes
wrong, raise `ScrapeError`. Otherwise, invoke the provided
`Webhook`. `old_data` is the previous course data or `util.Unset`.
""... | f98cb4c0f2a88a0f349c5c63a5db02aa88896c44 | 3,631,410 |
def get_chinese_relation_name(request, user1, user2):
"""
Gets what user1 called user2 in Chinese
Response:
{'status': Http status,
'title': string
}
"""
try:
title = get_chinese_relation(user1, user2)
return Response({
'title': title
})
... | 162a243792db781b03e07b290b84fb4a8c05e907 | 3,631,411 |
import matplotlib.pyplot as plt
def projplot(theta, phi, fmt=None, **kwargs):
"""projplot is a wrapper around :func:`matplotlib.Axes.plot` to take into account the
spherical projection.
You can call this function as::
projplot(theta, phi) # plot a line going through points at coord (th... | 615b9865308adb5eb3a2c647ffbd1e3d813c961f | 3,631,412 |
def compress_vertex_list(individual_vertex: list) -> list:
"""
Given a list of vertices that should not be fillet'd,
search for a range and make them one compressed list.
If the vertex is a point and not a line segment, the returned tuple's
start and end are the same index.
Args:
indivi... | a98f8b101219215f719b598ed8c47074a42ecb13 | 3,631,413 |
def update_context_with_user_data(update: Update, context: CallbackContext) -> tuple:
"""Update context.user_data with UserProfile data."""
# Update needed only when context.user_data is empty
if context.user_data:
return update, context
if hasattr(update.callback_query, 'message'):
chat... | 64cf6f6a18ce75b332cee910ab48728f9d154a14 | 3,631,414 |
def multiply_images( images, normalize_result = False, color_mode = MODE ):
"""Multiplica N imagens
Args:
images: lista de imagens
normalize_result: indica truncamento(False) ou normalização(True), default=False
color_mode = 'color color_mode' da imagem resultante, defaul='RGB'
... | 2328b363bbac8377d029269ff48b2eb919eefbe0 | 3,631,415 |
from torch.optim import lr_scheduler
def setup_harn(**kwargs):
"""
CommandLine:
python ~/code/netharn/netharn/examples/ggr_matching.py setup_harn
Args:
dbname (str): Name of IBEIS database to use
nice (str): Custom tag for this run
workdir (PathLike): path to dump all the ... | 2c73ded2db56cdde6d91a1b3391a90890f9e7e2d | 3,631,416 |
def sanitize_comment(comment):
"""Sanitize malicious tags from posted comments.
Takes an HTML comment string, returns that comment with malicious tags removed.
Defaults to bleach's default set of allowed tags:
['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul']
... | f92fbb9c967b3e95b41325cd00ea8f2732fe5440 | 3,631,417 |
import requests
def get_api_result(mode, extra_arguments={}):
""" Build JSON request to SABnzbd """
arguments = {'apikey': 'apikey', 'output': 'json', 'mode': mode}
arguments.update(extra_arguments)
r = requests.get('http://%s:%s/api' % (SAB_HOST, SAB_PORT), params=arguments)
return r.json() | 84b388b72611541b2eb486de5155f70ec2aa8833 | 3,631,418 |
async def get_exchange_info(exchange):
""" Fetches and returns relevant information about an exchange for historical data fetch.
Args:
exchange (str): The name of the exchange.
Returns:
str: JSON data with market exchange information.
"""
# Loads the market.
ex = getattr(ccxt_... | ef6a30a1e899e74c01a72cf8cc34ada7f2ca3173 | 3,631,419 |
def create_top_key_words_all(data_res, query, filter, filter_values):
"""Returns keywords graph as dcc.Graph component
Only displays it when all data is retrieved"""
dff_res = pd.DataFrame(data_res['data'])
dff_res['result'] = 'direct'
dff_res = data_preprocess.filter_data_by_time(dff_res, filter... | 804cadf9cf926d30203e8a733df66c5c663584d5 | 3,631,420 |
import re
def proccess_grains(grains_data, model_code, host_name, ip=None):
""" new_data 增加 model_code + "_HOSTNAME"""
all_data = grains_data.get("data")
data = all_data.get(host_name)
selinux = data.get("selinux", None)
dns = data.get("dns", None)
if dns:
dns = dns.get("nameservers")
... | 439c31846cad1d3283967a6320d647a3976bea00 | 3,631,421 |
def V2(params, fs, hs, ops, opsH, vector, shots=2**13, backend=Aer.get_backend('aer_simulator') ):
"""
Calculate the matrix A
"""
N = params.shape[0]
v = np.zeros(N)
for k in range(N):
v[k] = V_k(params, fs, hs, ops, opsH, vector, k, shots, backend )
return v | 46427c53b68c6626fcd2a0bb00031d5d62cb931d | 3,631,422 |
def cachedeterministic(parser, token):
"""
This will cache the contents of a template fragment for a given amount of
time, just like {% cache .. %} except that the key is deterministic and not
mangled or run through MD5.
Usage::
{% cachedeterministic [expire_time] [key] %}
.. s... | 1f7955a09fbc6a14ebe8e98ca4049b0febb35931 | 3,631,423 |
from typing import List
async def generate_acl6(participant: Participant) -> List[str]:
"""Generate a Participant-Specific IPv6 ACL."""
peer_acl = sorted(DEFAULT6.copy())
init_lines = (
f"no ipv6 access-list ipv6-{participant.asn}-in",
f"ipv6 access-list ipv6-{participant.asn}-in",
)
... | 32aaeb586b44b3fd4bcfd3b171e509761958ebd8 | 3,631,424 |
import random
import time
def make_veth_signed_order(
asset_infos, # pylint: disable=redefined-outer-name
pydex_client, # pylint: disable=redefined-outer-name
exchange_address, # pylint: disable=redefined-outer-name
):
"""Convenience function for creating a new instance of a signed order"""
def... | 2e064678df9b1e5756c77debd1ba249f1268c32c | 3,631,425 |
def normalize(vec):
"""Return unit vector for parameter vec.
>>> normalize(np.array([3, 4]))
array([ 0.6, 0.8])
"""
if np.any(vec):
norm = np.linalg.norm(vec)
return vec / norm
else:
return vec | 9987224b84a30aee4e64afee8170cc763cfea955 | 3,631,426 |
def get_x_coordinate(width, year_index):
"""
Given the width of the canvas and the index of the current year
in the YEARS list, returns the x coordinate of the vertical
line associated with that year.
Input:
width (int): The width of the canvas
year_index (int): The index of the cur... | e880be55ed530dd39257c0dae06d9301cadc869d | 3,631,427 |
import argparse
def add_rnaseq_args():
"""
Arguments for RNAseq pipeline
"""
parser = argparse.ArgumentParser(
description='RNA-seq pipeline')
parser.add_argument('-b', '--build-design', dest='build_design',
action='store_true',
help='Create design for fastq files')
par... | 327e79e26b44933b82f3b31a607112db0e650ce8 | 3,631,428 |
def get_downloader(start_date,
end_date,
granularity='daily',):
"""returns a downloader closure for oanda
:param start_date: the first day on which dat are downloaded
:param end_date: the last day on which data are downloaded
:param granularity: the frequency of price data,... | 2f6b94df6253b6f9c1e7fd335bd45b1fe7238422 | 3,631,429 |
def stick_together(seg, factor, connectivity=1):
"""
For every segment which are immediate neighbors, determine the number
of neighboring pixels and the volume of the smaller of the two
segments. If n_neighbors / volume**(2/3) > factor, stick the two
segments together. This is based on the heuristic... | a2406bd26132ebe2f278cc2f3463787db1629d38 | 3,631,430 |
def spkacs(targ, et, arg3, arg4, obs):
"""spkacs(SpiceInt targ, SpiceDouble et, ConstSpiceChar * arg3, ConstSpiceChar * arg4, SpiceInt obs)"""
return _cspyce0.spkacs(targ, et, arg3, arg4, obs) | 59d9734f84f4b4a3fcfad413bfa2088a76db3ef2 | 3,631,431 |
from typing import Optional
def replicated_all_reduce_(t: Tensor,
op: CollectiveOperator = CollectiveOperator.Add,
group: Optional[CommGroup] = None) -> Tensor:
"""Reduces tensor `t` across replicas inplace on `t`.
Args:
t (Tensor): Tensor to be r... | e3f5c33ef6dd27ef147690552399e5968d3faf7d | 3,631,432 |
def main():
"""Main function."""
runner = IcePartialRunner()
return runner.start() | 5a7e65f77f5fe6f8976e5a909aa53d0b63ef1c71 | 3,631,433 |
from typing import Dict
from typing import Any
import requests
def get_kip_main_page_body(kip_main_info: Dict[str, Any]) -> str:
"""Gets the RAW HTML body of the KIP main page"""
kip_body_request: requests.Response = requests.get(
CONTENT_URL + "/" + kip_main_info["id"], params={"expand": "body.view"... | 86c402ff311b230aa385cf727aae3d30bd500eac | 3,631,434 |
def load_model_tf(checkpoint_path):
"""
Restores custom model class which imitates keras' Model behaviour
"""
model = Model()
model.load(checkpoint_path)
return model | 4a26d63f3c13439597e3f86daa2222c4de21fe19 | 3,631,435 |
def _get_project_folder(name: str) -> str:
"""
Returns the full folder path of the named project.
Args:
name (str): The name of the project.
Returns:
(str): The path of the project folder.
"""
reg_data = _get_registry_data()
return reg_data[name]["location"] | 399a45e0895f12d8b51004a83aa82b7789661968 | 3,631,436 |
def dcos_service_url(service):
"""Return the URL of a service running on DC/OS, based on the value of
shakedown.dcos.dcos_url() and the service name.
:param service: the name of a registered DC/OS service, as a string
:return: the full DC/OS service URL, as a string
"""
return _gen_url("/service... | 916d5ed5f78efc69f46e22c433dbf2376de8b68e | 3,631,437 |
def get_configuration(resource_type, resource_id, configuration_capture_time):
"""Get configurationItem using getResourceConfigHistory API
in case of OversizedConfigurationItemChangeNotification
"""
result = AWS_CONFIG_CLIENT.get_resource_config_history(
resourceType=resource_type,
resou... | 6cf92171d12b3059e1ee6630dea58e1ad477b6cd | 3,631,438 |
def scenario_development_one_hot_encoded(sources, scenarios, territory="Europe"):
"""
Creates a dataframe with the operation of a production facility encoded to its activity in the given
years
:param sources: List or string of carbon sources
:param scenarios: List of Desired scenarios
:param ter... | f6eeb093a5b67a413bdd2b762c8f283d35bfe826 | 3,631,439 |
def urlparse(d, keys=None):
"""Return a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d | 260079c2e223de8c5211faa5cdab530c30fac07d | 3,631,440 |
def URFeaturizer(input_shape, hparams, **kwargs):
"""Auto-select an appropriate featurizer for the given input shape."""
if input_shape[1:3] == (224, 224):
return URResNet(input_shape, hparams, **kwargs)
else:
raise NotImplementedError(f"Input shape {input_shape} is not supported") | 412422db5611c5efdc142196df080baa2f65bb9a | 3,631,441 |
def week_of_year(datetime_col):
"""Returns the week from a datetime column."""
return datetime_col.dt.week | c1bf4e0cd5d4aeddf2cff9a1142fcb45b17d1425 | 3,631,442 |
def _NamespaceKeyToString(key):
"""Extract namespace name from __namespace__ key.
Raises an ApplicationError if the key is not of the form '__namespace__'/name
or '__namespace__'/_EMPTY_NAMESPACE_ID.
Args:
key: a key for a __namespace__ instance.
Returns:
namespace specified by key.
"""
key_path... | febb6e084916e645b0eb7c39b0bc01b7463ecb7d | 3,631,443 |
import crypt
def novo_usuario(usuario,senha,root):
"""Cria e insere um usuário no banco"""
if("True" in root):
estado=1
else:
estado=""
dados={"login":usuario,"senha":crypt.crypt(senha),"root":bool(estado)}
try:
colecao.insert_one(dados)
#sucesso ao criar um usuário... | a93f732b7a529cc0ddf03deb178e2fe34eaf183a | 3,631,444 |
def fill_dict(_dict, **kwargs):
"""A helper to fill the dict passed with the items passed as keyword
arguments if they are not yet in the dict. If the dict passed was
`None` a new dict is created and returned.
This can be used to prepopulate initial dicts in overriden constructors:
class MyFo... | 7e9cd1bb7b15633696d82ded89f39868bb77524c | 3,631,445 |
def list_live_assessment_results(request_ctx, course_id, assessment_id, user_id=None, **request_kwargs):
"""
Returns a list of live assessment results
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param course_id: (required) ID
:type course_id... | 871a592f97828c68cb844ab09c844ebca351ecb3 | 3,631,446 |
def extract_format_data(matrix):
"""Extract format information from the upper-left corner.
Parameters:
matrix (ndarray): 2D array containing the QR matrix.
Returns:
Tuple (error_correction_level, mask_pattern).
Raises:
QRDecodeError: If the format information can not be decode... | 44fb1c4e1c305bee84dbec218fa675cb32b85bc9 | 3,631,447 |
def decrypt_and_print_message(args):
"""Try to decrypt and print a message."""
for key in args.keys:
for nounce in range(args.nounce_lower, args.nounce_upper):
if _decrypt_chacha20poly1305(args.message, nounce, key):
return 0
return 1 | 919a391862d727dac3596f07ad5df33e6fc08199 | 3,631,448 |
def readCylWFSRaw(fn):
"""
Load in data from WFS measurement of cylindrical mirror.
Assumes that data was processed using processHAS, and loaded into
a .fits file.
Scale to microns, remove misalignments,
strip NaNs.
If rotate is set to an array of angles, the rotation angle
which minimiz... | 3302806ba302c87c55160569d5bebcd4a0fcc6d3 | 3,631,449 |
def normalize(df, df_ref=None):
"""
Normalize all numerical values in dataframe
:param df: dataframe
:param df_ref: reference dataframe
"""
if df_ref is None:
df_ref = df
df_norm = (df - df_ref.mean()) / df_ref.std()
return df_norm | 56c96f43c98593a5cf21425f23cfd92a7f6d6fe3 | 3,631,450 |
def get_shapes(ndim):
"""
produce a bunch of tensor shapes of order `ndim`.
Args:
ndim: The tensor order.
Returns:
list[tuple[int]]: A list of shapes.
"""
if ndim == 3:
shapes = unique_permutations((8, 64, 128))
some_combs = sum((list(zip(shapes, unique_permutations(pshape)))
... | 05afb6198a9c2291c4645e4de47728800431db34 | 3,631,451 |
def gen_stimuli(M, N):
"""
This function generates the stimuli (taken from actual data)
"""
a = (np.random.randn(1, M) * 100).astype(np.float32)
B = (np.random.randn(M, N) * 100).astype(np.float32)
y = custom_vecmatmul(a, B)
return a, B, y | b9fec03e16fb45469e7e708d5a3ca8f5e8fe7ca5 | 3,631,452 |
def agentXML(request, identifier):
"""
Return a representation of a given agent
"""
if 'premis' in request.path:
identifier = identifier.replace('.premis', '')
try:
agentObject = Agent.objects.get(agent_identifier=identifier)
except Agent.DoesNotExist:
re... | 4dabb9676f0389b170461a4a617975b09decb131 | 3,631,453 |
from dmlc_tracker import opts
def dmlc_opts(opts):
"""convert from mxnet's opts to dmlc's opts
"""
args = ['--num-workers', str(opts.num_workers),
'--num-servers', str(opts.num_servers),
'--cluster', opts.launcher,
'--host-file', opts.hostfile,
'--sync-dst-d... | 2a83684512fa49d624e2e99169d1e600a45b5cdc | 3,631,454 |
from typing import Optional
from typing import Sequence
def get_virtual_border_routers(filters: Optional[Sequence[pulumi.InputType['GetVirtualBorderRoutersFilterArgs']]] = None,
ids: Optional[Sequence[str]] = None,
name_regex: Optional[str] = None,
... | af55f1ed6b5713451599c8c0da40d35fa48cc61f | 3,631,455 |
import math
def cal_angle(center, point):
"""
利用向量点乘 ,计算center为顶点,center->point 与 x 轴 的夹角
:param center: 顶点 tuple
:param point: x轴外边上一点 tuple
:return:angle 角度
"""
center = center[:2]
point = point[:2]
vec1 = (point[0] - center[0], point[1] - center[1])
dis_of_vec1 = math.sqrt(... | 7295a4ce7834621385a1fcb63535af957d81443c | 3,631,456 |
def PermutationGroup(gens=None, gap_group=None, domain=None, canonicalize=True, category=None):
"""
Return the permutation group associated to `x` (typically a
list of generators).
INPUT:
- ``gens`` - list of generators (default: ``None``)
- ``gap_group`` - a gap permutation group (default... | fcff1b525590544d108accc51780fde7b61d0428 | 3,631,457 |
def lunar_diameter(tee):
"""Return the geocentric apparent lunar diameter of the moon (in
degrees) at moment, tee. Adapted from 'Astronomical
Algorithms' by Jean Meeus, Willmann_Bell, Inc., 2nd ed."""
return deg(1792367000/9) / lunar_distance(tee) | e13e514c449f89b5fb10c1f927f3460a22a0a888 | 3,631,458 |
def findCongressPerson(name, nicknames_json):
"""
Checks the nicknames endpoint of the NYT Congress API
to determine if the inputted name is that of a member of Congress
"""
congress_json = [x['nickname'] for x in nicknames_json if x['nickname'] == name]
if len(congress_json) > 0:
return... | d03dc1f55c970379b283f78cfd23e393e494bd48 | 3,631,459 |
from typing import Tuple
def make_canonical_transform_np(
n_xyz: np.ndarray,
ca_xyz: np.ndarray,
c_xyz: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Returns translation and rotation matrices to canonicalize residue atoms.
Note that this method does not take care of symmetries. If you provide ... | 59c0a5ca06f3f0d612cc25ce453e201c4daff184 | 3,631,460 |
def get_data_for_result_table(all_answers):
"""
Generate simple data for result table (question, answer status true/false).
@param all_answers: dict with pairs question_id and list of answers for question.
@return: dict with all data for result table.
"""
result_data = {}
for question_id, a... | c9bdd9920698ed758d27ceb2bcf04e143f705bd4 | 3,631,461 |
def _validate_positive_int(value):
"""Validate value is a natural number."""
try:
value = int(value)
except ValueError as err:
raise ValueError("Could not convert to int") from err
if value > 0:
return value
else:
raise ValueError("Only positive values are valid") | ddc2087d69c96fa72594da62192df58555b25029 | 3,631,462 |
def transpose(table):
"""
Returns a copy of table with rows and columns swapped
Example:
1 2 1 3 5
3 4 => 2 4 6
5 6
Parameter table: the table to transpose
Precondition: table is a rectangular 2d List of numbers
"""
result = []... | fe84714d3e09deb22058fd75ac3333c2206f77c3 | 3,631,463 |
def predict_posterior_marginals(
F, features, mean, kernel, chol_fact, pred_mat, test_features,
test_intermediates=None):
"""
Computes posterior means and variances for test_features.
If pred_mat is a matrix, so will be posterior_means, but not
posterior_variances. Reflects the fact that... | 702ec32d43566e8e17a19f597ed0dd90b28d85d8 | 3,631,464 |
def rule_ContributesLight_possessions_can_light_person(x, world) : # maybe should handle concealment at some point?
"""A person contributes light if any of their posessions contribute light."""
if any(world[ContributesLight(o)] for o in world[Contents(x)]) :
return True
else : raise NotHandled() | d67c50903e1c7b50b6e6ec2c6369b91db50a494c | 3,631,465 |
import os
def update_keras_bn_ops_trainable_flag(model: tf.keras.Model, trainable: bool, load_save_path: str) -> tf.keras.Model:
"""
helper method to update Keras BN ops trainable state in a given keras model.
:param model: Keras model to be updated with BN ops trainable flag
:param trainable: bool f... | 347aa5ebc8bff4d1b65b6c696607293eb091b5ba | 3,631,466 |
def xml():
""" Return an XML response with an HTTP 200 OK status """
data: str = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
<lastmod>2005-01-01</lastmod>
<changefreq>monthly</changefreq>
... | 4b4391ff9b22570885e4056ba62f4dbe84724c18 | 3,631,467 |
from typing import Iterable
import pathlib
def read_device_files(directory_paths: Iterable[pathlib.Path]) -> DeviceFileInfo:
"""Read data from files contained on an mbed enabled device's USB mass storage device.
If details.txt exists and it contains a product code, then we will use that code. If not then we ... | e11c2dee5db2fa957bc9794a87414d72b708a85e | 3,631,468 |
def max_rl(din):
"""
A MAX function should "go high" only when all of
its inputs have arrived. Thus, AND gates are
used for its implementation.
Input: a list of 1-bit WireVectors
Output: a 1-bit WireVector
"""
if len(din) == 1:
dout = din[0]
else:
... | b65710967a8a785e1ca0679252ac69c140b4c560 | 3,631,469 |
def compute_success(
classifier: "CLASSIFIER_TYPE",
x_clean: np.ndarray,
labels: np.ndarray,
x_adv: np.ndarray,
targeted: bool = False,
batch_size: int = 1,
) -> float:
"""
Compute the success rate of an attack based on clean samples, adversarial samples and targets or correct labels.
... | 0e8f44038b8d661912393edb6b248ff93356f180 | 3,631,470 |
def set_up_basic_stubs(app_id):
"""Set up a basic set of stubs.
Configures datastore and memcache stubs for testing.
Args:
app_id: Application ID to configure stubs with.
Returns:
Dictionary mapping stub name to stub.
"""
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
ds_stub ... | 197d1c94cbca97ed0b8f4663280a2feb6518b00e | 3,631,471 |
from typing import Callable
from typing import List
def _load_init_model_weights(
model_fn: Callable[[],
tff.learning.Model]) -> List[tff.learning.ModelWeights]:
"""Load model weights to warm-start HypCluster."""
state_manager = tff.program.FileProgramStateManager(FLAGS.warmstart_root_d... | 9abfb5e155ab6408da36d21a04556e6094866ff2 | 3,631,472 |
import requests
def process_request(url, auth):
"""Perform an http request.
:param url: full url to query
:type url: ``str``
:param auth: username, password credentials
:type auth: ``tuple`` || ``None``
:returns: ``dict``
"""
content = requests.get(url, auth=auth)
if content.statu... | 051c60e03458e3c38d93dfd65d15f355ec284c12 | 3,631,473 |
def close_channel(sender_addr, receiver_addr,channel_name):
"""
:param sender_addr: String, the sender address
:param receiver_addr: String, receiver's address
:param channel_name: String, channel name
:return:
"""
sender, receiver = split_channel_name(channel_name)
ch = Channel(sender, ... | ee7bd2311f7ef7c3ad4abb0c7701116208079ef2 | 3,631,474 |
from typing import Collection
from typing import Tuple
from typing import Iterator
from typing import Set
def get_proj_edges(edges: Collection[Tuple[int, int]]) -> Iterator[Tuple[int, int]]:
"""Obtain projective edges from a collection of edges of a dependency tree."""
adj_set: dict = defaultdict(set)
for... | 6c822140e2627046ee8f36769fd14cda14829a5f | 3,631,475 |
from typing import Union
from typing import Any
def convertClrs(clr: Union[dict[Any, Union[str, Color]], Color], conversion: str) -> Union[str, tuple, dict, None]:
"""
Convert color values to HEX and vice-versa
@clr: Color value to convert.
@conversion: Type of conversion to do ('RGB' or 'HEX')
"""
if isinsta... | 70329d19984f970fcaee86ca9403615a2995e9a9 | 3,631,476 |
def fuzzy_op(x, a, y, b, op):
"""Operation of two fuzzy sets.
Operate fuzzy set ``a`` with fuzzy set ``b``,
using +, * or any other binary operator.
Parameters
----------
x : 1d array, length N
Universe variable for fuzzy set ``a``.
a : 1d array, length N
Fuzzy set for ... | c4b10f024fd7c4bfb0ec4faaedef1f57c62527f7 | 3,631,477 |
def check_int(item):
"""
:param item: txtcrtl containing a value
"""
flag = True
try:
mini = int(item.GetValue())
item.SetBackgroundColour(wx.WHITE)
item.Refresh()
except:
flag = False
item.SetBackgroundColour("pink")
item.Refresh()
return flag | c5ded12ef242a4286fe1b0e9af160dfc9698b5af | 3,631,478 |
def load_h5py(path):
"""Loads datasets from a file.
params:
path: A string, which is a path to the dataset
return: A dictionary, which contains the dataset
"""
dataset = {}
with h5py.File(path, 'r') as hf:
if 'train_x' in hf:
dataset['train_x'] = hf['train_x'][:]
... | 9bc12ee86249a20931c0f5a83ad0cc7910f55ced | 3,631,479 |
def from_timedelta(val):
"""escape a python datetime.timedelta"""
sec = int(val.total_seconds())
hour = sec // 3600
sec = sec % 3600
mns = sec // 60
sec = sec % 60
msec = val.microseconds
return _time(hour, mns, sec, msec) | f618a82b9253f27bb8c0574c697ee3e35f7d9d22 | 3,631,480 |
def stringify_column(df: DataFrame, column: str) -> DataFrame:
"""Takes dataframe and column that contains array structures. Stringify that column values."""
array_to_string_udf = udf(array_to_string, StringType())
df = df.withColumn(column, array_to_string_udf(df[column]))
return df | d0496053279c39e4decd349b649ddd899277719a | 3,631,481 |
import platform
def get_os():
"""
Get operating system.
:return: operating system
:rtype: str or unicode
"""
return platform.platform() | 104c8547c751388a2ea4be675be1fa44758d61d0 | 3,631,482 |
def powerLaw(y, x):
"""
'When the frequency of an event varies as power of some attribute of that
event the frequency is said to follow a power law.' (wikipedia)
This is represented by the following equation, where c and alpha are
constants:
y = c . x ^ alpha
Args
--------
y: array w... | 39ad30d5f0c150df06faa41bbcd960352c708b6a | 3,631,483 |
def _separate_talairach_levels(atlas_img, labels, verbose=1):
"""Separate the multiple annotation levels in talairach raw atlas.
The Talairach atlas has five levels of annotation: hemisphere, lobe, gyrus,
tissue, brodmann area. They are mixed up in the original atlas: each label
in the atlas correspond... | 1d05eab354eada01322bfd2fb79bcdeaeaf4ab34 | 3,631,484 |
def merge(a, b):
"""
Hierarchical merge of dictionaries, lists, tuples and sets.
If b is None, it keeps a, otherwise it merges with a.
In case of ambiguities, b overrides a
it returns is a deepcopy, not a reference of the original objects.
"""
if isinstance(b, dict) and isinstance(a, dict):... | 5ae3533ded3018a8e7789d0b50cf150c19c4a6d5 | 3,631,485 |
def block_inception_a(blk, net):
"""Builds Inception-A block for Inception v4 network."""
# By default use stride=1 and SAME padding
s = net.add(Split('%s/Split' % blk, 4))
br0 = conv2d(net, '%s/Branch_0/Conv2d_0a_1x1' % blk, 96, 1, src=s)
conv2d(net, '%s/Branch_1/Conv2d_0a_1x1' % blk, 64, 1, src=s)... | c09d1d0c3c2465f9cd273a611ea16871635a6bea | 3,631,486 |
def mgas(sg, sp, gpotential, potential, xv, dt, kappa=1.0, alpha=1.0):
"""
Evolve satellite gas mass due to tidal stripping, by an amount of
[m - m(l_rp)] * dt / t_dyn
where m is the satellite gas mass; m(l_rp) is the satellite gas mass
within ram pressure radius l_rp; dt is the timestep size;... | 4d8b823a0814bf78f3e30c20bfbab17d0d5b87e5 | 3,631,487 |
import random
def genpass(pwds_amount=1, paswd_length=8):
""" Returns a list of 'pwds_amount' random passwords, having length of 'paswd_length' """
return [ ''.join([chr(random.randint(32, 126)) for _ in range(paswd_length)]) for _ in range(pwds_amount)] | d5d4e38cc334f44e837c72f265a391bf72f5bd5f | 3,631,488 |
import os
def collect_fastq_data_irma(fc_root, fc_proj_src, proj_root=None, pid=None):
"""Collect the fastq files that have to be removed from IRMA
return a tuple with files and total size of collected files"""
size = 0
file_list = {'flowcells': defaultdict(dict)}
fc_proj_path = os.path.join(fc_ro... | a56c4fcc50d1bee2698138624befcf883df1ba76 | 3,631,489 |
def _gini(x):
"""
Memory efficient calculation of Gini coefficient in relative mean difference form
Parameters
----------
x : array-like
Attributes
----------
g : float
Gini coefficient
Notes
-----
Based on http://www.statsdirect.com/help/default.htm#nonparametri... | 581f12e46544df307b8f53f2f4261779b7069d67 | 3,631,490 |
def _AddListFieldsMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
# Ensure that we always list in ascending field-number order.
# For non-extension fields, we can do the sort once, here, at import-time.
# For extensions, we sort on each ListFields() call, though
# we could do better i... | 10f7d51ea1d65562c330a75922fc7dcbc6f5f729 | 3,631,491 |
def render_edit_view(request, form_name, nid):
"""according resource primary key,render edit view
Arguments:
request {object} -- wsgi http request object
form_name {str} -- resources type name
nid {int} -- resources id
Returns:
html -- html template
"""
... | d69d0f2f45351077253b750fe0e197951c1fe853 | 3,631,492 |
def decrypt_default_password(message):
"""
You Can Use this for internal data (Aka Non-User controlled data) that needs to be encrypted.
:param message:
:return:
"""
if type(message) == bytes:
f = Fernet(getkey(Settings.ENCRYPTION_PASSWORD))
decrypted = f.decrypt(message)
... | 2d9b087db80a0645bae88564373642a900e5ea28 | 3,631,493 |
def getfeed(user):
"""Test post
:user: Stuff from the interwebs
:returns: stuff to the interwebs
"""
response = jsonify({'result_count': 'This is ' + user + '\'s feed!'})
response.headers.add('Access-Control-Allow-Origin', '*')
return response | 687e9d723f8a2037aeafbf457411134bab5f54d2 | 3,631,494 |
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
# i... | c18270860e090810a1a7d7aabbd1d2f2957609a2 | 3,631,495 |
def variables_and_orphans(i, o):
"""
Extract list of variables between i and o nodes via
dfs traversal and chooses the orphans among them
Parameters
----------
i : list
Input variables.
o : list
Output variables.
"""
def expand(r):
if r.owner and r not in... | 34ec8ba9b92442462c15d00e0401a71b12de6551 | 3,631,496 |
def get_collected_quotas():
"""获取我的收藏"""
form = PaginationForm().validate_for_api()
per_page = current_app.config['COUNT_DEFAULT']
current_uer = get_current_user()
paginate = paginate_data(current_uer.not_deleted_collected_quotas, form.page.data, per_page)
return jsonify(paginate) | 802ed5593163fbc5c4bffd30d1a8dc2685709438 | 3,631,497 |
from typing import List
def main(
gcal_calendar: str,
google_secret: str,
oauth_port: int,
tw_tags: List[str],
tw_project: str,
resolution_strategy: str,
verbose: int,
combination_name: str,
custom_combination_savename: str,
do_list_combinations: bool,
):
"""Synchronize cal... | 20779ca8560fa84097cd4fc553442fa7a64ab132 | 3,631,498 |
import requests
def image_from_url(url):
"""
Download image from url
:param url: url of image
:return: image Pillow object
"""
response = requests.get(url)
return Image.open(BytesIO(response.content)) | d666ba001045eb7bb34d3c37930c97739d9c01d6 | 3,631,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.