content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
import os
def _CalculatePerDirectoryCoverageSummary(per_file_coverage_summary):
"""Calculates per directory coverage summary.
Args:
per_file_coverage_summary: A dictionary from file path to coverage summary.
Returns:
A dictionary from directory path to coverage summary.
"""
logging.... | eacf0ba87d8facfcff1d1b6c5f1bb87052053409 | 3,637,700 |
def is_aix():
"""
Simple function to return if host is AIX or not
"""
return salt.utils.platform.is_aix() | e4be83dfefc2a7ce5d97894b7a882808658d470a | 3,637,701 |
def draw_support_spring(
fig,
support,
orientation="up",
color='orange',
show_values=True,
row=None,
col=None,
units="N/m"):
"""Draw an anchored spring shape on a plotly figure.
Parameters
----------
fig : plotly figure
plotly figu... | 73c546289ac02d9021375f553504991bdaa4ca89 | 3,637,702 |
def _collins_crt(r, R, P, p, K):
"""Wrapper of CRT for Collins's resultant algorithm. """
return gf_int(gf_crt([r, R], [P, p], K), P*p) | d84f5ad514872acacc5f7ef626cb05f5df7771f3 | 3,637,703 |
def quantity_remover(my_thing):
"""
removes pint quantities to make json output happy
Parameters
----------
my_thing
Returns
-------
"""
if hasattr(my_thing, 'magnitude'):
return 'QUANTITY', my_thing.magnitude, my_thing.units.format_babel()
elif isinstance(my_thing, ... | 54b2db5b638f297ca503513f79eb4eec4ac2afa2 | 3,637,704 |
def sliced_wasserstein(PD1, PD2, M=50):
""" Implementation of Sliced Wasserstein distance as described in
Sliced Wasserstein Kernel for Persistence Diagrams by Mathieu Carriere, Marco Cuturi, Steve Oudot (https://arxiv.org/abs/1706.03358)
Parameters
-----------
PD1: np.ar... | c8de271435b9b393f7230c13f6eb746e3d566828 | 3,637,705 |
def update_handler(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <https://flask.palletsprojects.com/en/1.1.x/api/#fl... | 5fa052ddbd9e4016645e0ee81be1d8aeaaca7531 | 3,637,706 |
def usercourse(request, course_code):
"""
The function is use for course content
"""
user = request.user
extrainfo = ExtraInfo.objects.select_related().get(user=user) # get the type of user
courseid = Courses.objects.select_related().get(code=course_code)
classes = OnlineClasses.objects.sel... | ab5519f211e4c6e2574536f1a1c5a781d3529e7d | 3,637,707 |
def add_device(config_id, name, device_type_id, device_subtype_id, ip4address, ip6address, properties):
"""Add device to BAM."""
response = get_api()._api_client.service.addDevice(config_id, name, device_type_id, device_subtype_id, ip4address,
ip6address, p... | 84c66b5ab3951b764a8669bb49438eb6101e1355 | 3,637,708 |
def cdf_approx(X): #, smoothness_factor=1):
"""
Generates a ppoly spline to approximate the cdf of a random variable,
from a 1-D array of i.i.d. samples thereof.
Args:
X: a collection of i.i.d. samples from a random variable.
args, kwargs: any options to forward to the cvxopt qp solver
... | 6a9cdc8ef3b8413ea10484ace49c7514241d897d | 3,637,709 |
def cleanse_param_name(name):
"""Converts Chainer parameter names to ONNX names.
Note ONNX identifiers must be a valid C identifier.
Args:
name (str): A Chainer parameter name (e.g., /l/W).
Returns
A valid ONNX name (e.g., param_l_W).
"""
return 'param' + name.replace('/', '_') | 9b7774aabeeab322f53321b91195333359c8ee7b | 3,637,710 |
def calc_checksum_for_ip_change(old_ip_packet, new_ip_packet, old_checksum, is_ipv6=False):
""" ip地址改变之后重新获取校检码
:param old_ip_packet:
:param new_ip_packet:
:param old_checksum:
:param is_ipv6:是否是ipv6
:return:
"""
final_checksum = old_checksum
a = 0
b = 1
# tmpcsum = old_check... | 7bcc7d96b6b8eef9c1ef93ca922ec192194785ff | 3,637,711 |
def get_sender_password():
"""Get sender password
"""
try:
return Setting.objects.get(slug=KEY_SENDER_PASSWORD)
except Setting.DoesNotExist:
return None | 80e0c0843b02f7a27d62727fc6b104a566cc7442 | 3,637,712 |
def standardize_data(df):
"""Standardizes the data by cleaning string values and standardizing column
names.
df: Pandas dataframe to standardize.
"""
# Clean string values in the dataframe.
df = df.applymap(
lambda x: x.replace('"', '').strip() if isinstance(x, str) else x)
# Stand... | 68a00c00003206e1875ca166de02336fb845fce3 | 3,637,713 |
def MatrixExp6(se3mat):
"""Computes the matrix exponential of an se3 representation of
exponential coordinates
:param se3mat: A matrix in se3
:return: The matrix exponential of se3mat
Example Input:
se3mat = np.array([[0, 0, 0, 0],
[0, ... | 5fb0c8ec0a43410c8bb85e98b3edbd8ab23efea0 | 3,637,714 |
import re
def parse_log(content, arg_parser=json_arg_parser):
""" Parse important information from log files.
These log files are small so we are making the logic a little simpler by loading all
the content into memory at once rather than using an iostream.
Args:
content (string): the string ... | 88659c548cdd95bd152ee0a829486301b42956c4 | 3,637,715 |
def _ohlc_dict(df_or_figure, open='', high='', low='', close='', volume='',
validate='', **kwargs):
"""
Returns a dictionary with the actual column names that
correspond to each of the OHLCV values.
df_or_figure : DataFrame or Figure
open : string
Column name to be used for ... | e6512a307217cb79b56942aa8c469a56d3cac8fc | 3,637,716 |
def _s_to_b(value):
"""[string to binary single value]"""
try:
return bytes(value, 'utf-8')
except:
return value | bbabffa2fbd2ec62778a19c8ab3e1fe410b4640f | 3,637,717 |
def get_or_create(
*, db_session, email: str, incident: Incident = None, **kwargs
) -> IndividualContact:
"""Gets or creates an individual."""
# we fetch the individual contact from the database
individual_contact = get_by_email_and_project(
db_session=db_session, email=email, project_id=inciden... | eacc9c048551f430927bdfe8c67a1af5209c0b18 | 3,637,718 |
def stats(request):
"""Return stats as JSON according to different GET query parameters."""
offset = request.GET.get('offset', '0')
limit = request.GET.get('limit', '10')
order_by = request.GET.get('order_by', 'public_backlinks')
return build_stats(offset, limit, order_by) | d252e8654a4a70f4de56e937b14cc449b6e477b6 | 3,637,719 |
def news():
"""
Return the latest version of the news json
"""
# TODO: add options to request like request.args.get('from', default='')
latest_news = get_latest_news(local=CONFIG['PARAMS']['local'] == 'True')
response = app.response_class(response=latest_news, status=200)
return response | ce6230bc3b11e99dcfab8883f77cb0345af4c64c | 3,637,720 |
def zero_crossing(arr, rank=1):
"""Calculates the zero crossing rate"""
if rank == 1:
nzc = tf.cast(tf.count_nonzero(tf_diff_axis(tf.sign(arr))), tf.float32)
else:
nzc = tf.cast(tf.count_nonzero(tf_diff_axis(tf.sign(arr)), axis=rank - 1), tf.float32)
arrlen = tf.cast(arr.shape[rank - 1]... | c7a6271d1cbf299278a06845e753d0e431716df8 | 3,637,721 |
def normalize_command(command):
"""Convert `command` to the string representation.
"""
if isinstance(command, list):
if len(command) == 1:
# This is either a quoted compound shell command or a simple
# one-item command. Pass it as is.
command = command[0]
... | 700559f7b96ba4ea37f639fdc438db5c2ad70c29 | 3,637,722 |
def make_struct(*args, **kwargs):
"""Create a Struct class according to the given format"""
exec _structdef(*args, **kwargs)
return Struct | 2fece3443e516019492af454f3f4b99bba2bd481 | 3,637,723 |
def link_iterable_by_fields(unlinked, other=None, fields=None, kind=None,
internal=False, relink=False):
"""Generic function to link objects in ``unlinked`` to objects in ``other`` using fields ``fields``.
The database to be linked must have uniqueness for each object for the given ... | 08abab5fd1db346e2fedfc9e7a9ad7542e6424a7 | 3,637,724 |
def is_conn() -> bool:
"""是否连接核心网"""
return param.parent.ia != utz.IA_INVALID and param.parent.is_conn | 8e3b06d49473caf43bf97fb133aec49907535777 | 3,637,725 |
def GetConstants():
"""Returns a list of all available constant values used by some Nexpose Criteria"""
return _get_filtered_classes(NexposeCriteriaConstant) | 24be59ec50dada727efdb394c247435111ab4b5f | 3,637,726 |
import json
def getEmpiresForUser(user_email):
"""Fetches empires for the given user.
Even though the empires should be in the data store already, we force fetch them from the server. This is
because it could be a new user and it hasn't synced yet, but also this provides a way for the user to force
their emp... | 9d2e460c726a36b8071cdf6ea2ebeb8b36e468bc | 3,637,727 |
def netflix(es, ps, e0, l=0.0001):
"""Combine predictions with the optimal weights to minimize RMSE.
Ref: Töscher, A., Jahrer, M., & Bell, R. M. (2009). The bigchaos solution to the netflix grand prize.
Args:
es (list of float): RMSEs of predictions
ps (list of np.array): predictions
... | 359ca02bb6c7f9a3d4d25fe2b41a4bcac5fd086f | 3,637,728 |
def create_list(list_data, user_id, status=200):
"""Create a new todo list throught the API"""
res = app.post_json('/v1/users/{user_id}/lists'.format(user_id=user_id),
list_data,
status=status,
expect_errors=status != 200)
return res | f6fa4c0e523b0c1187e927cdab0292037b0cecdb | 3,637,729 |
import fastapi
async def create_movie(
*,
session: aio_session.AsyncSession = fastapi.Depends(
dependencies.get_session),
movie_in: movie_model.MovieCreate,
current_patron: patron_model.Patron = fastapi.Depends( # pylint: disable=unused-argument
dependencies.get_current_active_patron)... | 88c1acca8980788031e9a64d22dd2ca0e629cc5c | 3,637,730 |
import time
import math
def project_gdf(gdf, to_crs=None, to_latlong=False, verbose=False):
"""
https://github.com/gboeing/osmnx/blob/v0.9/osmnx/projection.py#L58
Project a GeoDataFrame to the UTM zone appropriate for its geometries'
centroid.
The simple calculation in this function works well fo... | aed2c42282301d2623c92dd1516f99d953afc1c2 | 3,637,731 |
from .. import __version__
from ..importer import IMPORTED
from .driver import schema_all_drivers
from .executor import schema_all_executors
from .flow import schema_flow
from .meta import schema_metas
from .request import schema_requests
from .pod import schema_pod
def get_full_schema() -> dict:
"""
Return t... | db31d02fc1ef7ef3ed19cefffc3dcd0cdfdbb237 | 3,637,732 |
def power_method(A, x0, n_iter=1):
"""Compute the first singular components by power method."""
for i in range(n_iter):
x0 = A.T @ A @ x0
v = x0 / norm(x0)
s = norm(A @ v)
u = A @ v / s
return u, s, v | 7efc860520535aab42aeda24e15e4d4f5c340901 | 3,637,733 |
def convert_coevalcube_to_sphere_surface_inpdict(inpdict):
"""
-----------------------------------------------------------------------------
Covert a cosmological coeval cube at a given resolution (in physical comoving
distance) to HEALPIX coordinates of a specified nside covering the whole sky
or... | e99f4ca3d6ff1a76ce95c4e929521ccf857148df | 3,637,734 |
def postmsg(message):
"""!Sends the message to the jlogfile logging stream at level INFO.
This is identical to:
@code
jlogger.info(message).
@endcode
@param message the message to log."""
return jlogger.info(message) | b7cad54650fd769ef9c56f8a03e68d0ef9fa485d | 3,637,735 |
def dec_lap_pyr(x, levs):
""" constructs batch of 'levs' level laplacian pyramids from x
Inputs:
x -- BxCxHxW pytorch tensor
levs -- integer number of pyramid levels to construct
Outputs:
pyr -- a list of pytorch tensors, each representing a pyramid level,
... | d0b48660b194c71e34e7f838525d0814081939fb | 3,637,736 |
import os
import logging
def subinit2_readPPdb_checkkeys(PATHS, config, metadata):
"""
Reads the power plant database and determines the required input files (fundamentals and parameters):
1) Read the power plant database from disk
2) Read the database and check the required input files for:
- fuels
- ef... | 67f16f567c04c6765207e452477227e2599ae062 | 3,637,737 |
def mif2amps(sh_mif_file, working_dir, dsi_studio_odf="odf8"):
"""Convert a MRTrix SH mif file to a NiBabel amplitudes image.
Parameters:
===========
sh_mif_file : str
path to the mif file with SH coefficients
"""
verts, _ = get_dsi_studio_ODF_geometry(dsi_studio_odf)
num_dirs, _... | 2defa9d0656bc6c884e6f0591041efdea743db95 | 3,637,738 |
import struct
import array
def write_nifti_header(hdrname, hdr, newfile=True):
#*************************************************
"""
filename is the name of the nifti header file.
hdr is a header dictionary. Contents of the native header
will be used if it is a nifti header.
Returns: 0 if no er... | 8b9239ff96d453f8bcb7a667e62434fa9f1bfbc6 | 3,637,739 |
import struct
def get_array_of_float(num, data):
"""Read array of floats
Parameters
----------
num : int
Number of values to be read (length of array)
data : str
4C binary data file
Returns
-------
str
Truncated 4C binary data file
list
List of flo... | 92a0a4cc653046826b14c2cd376a42045c4fa641 | 3,637,740 |
def AUcat(disk=None, first=1, last=1000, Aname=None, Aclass=None, Aseq=0,
giveList=False):
"""
Catalog listing of AIPS UV data files on disk disk
Strings use AIPS wild cards:
* blank => any
'?' => one of any character
"*" => arbitrary string
If giveList then r... | 501bb5a1eaa82fd162d17478f5bd9b14d8b76124 | 3,637,741 |
def process_threat_results(matching_threats, context):
""" prepare response from threat results """
threats = [ThreatSerializer(threat).data for threat in matching_threats]
response_data = {
"id": context.id,
"hits": threats,
}
status_code = status.HTTP_200_OK
if context.pending... | b6f763f1a2983967dd0ccc68237408bf3871f9ac | 3,637,742 |
def entropy_logits(logits):
"""
Computes the entropy of an unnormalized probability distribution.
"""
probs = F.softmax(logits, dim=-1)
return entropy(probs) | a9806dfbafbe77f74df55b81cc19603826e2d994 | 3,637,743 |
def convert_int_to_str(number: int, char: str = "'"):
"""Converts an ugly int into a beautiful and sweet str
Parameters:
nb: The number which is gonna be converted.
char: The characters which are gonna be inserted between every 3 digits.
Example: 2364735247 --> 2'364'735'247"""
number ... | ae8e2b0e4cc9a332e559e3128c440fff59cf6c78 | 3,637,744 |
def exists(index, doc_type, id, **kwargs):
"""
Returns a boolean indicating whether or not given document exists in Elasticsearch.
http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html
"""
res = request("exists", None, index, doc_type, id, **kwargs)
jsonprint(res)
retu... | fd5488acef16b22b0da7302345eab2de6073523c | 3,637,745 |
def deserialize_cookie(string):
"""Deserialize cookie"""
parts = string.split("#")
length = len(parts)
if length == 0 or length < 3:
return None
if not is_int(parts[2]):
return None
return create_internal_cookie(
unquote(parts[0]),
unquote(parts[1]),
pa... | 9887eb18c4cc91a13048b987ec962deb83a4da2b | 3,637,746 |
def choose(n, k):
"""This is a binomial coeficient nCk used in binomial probablilty
this funtion uses factorial()
Usage: choose(n, k)
args:
n = total number
k = total number of sub-groups """
try:
return factorial(n)/(factorial(k) * factorial(n - k))
except(ValueError, ZeroD... | 3e9fe5212a2ddf680fc6681c0a7d7bd1ec9a4de2 | 3,637,747 |
def BiRNN(x, seq_lens):
"""TODO: full docstring; seq_lens is np_array of actual input seq lens.
Actually seq_lens is a tf.placeholder"""
# data input shape: (batch_size, seq_lens, n_input)
# Define lstm cells with tensorflow
# Forward direction cell
lstm_fw_cell = rnn.BasicLSTMCell(n_hidden, fo... | 603efcb8c664f8793d56222234fa1f381446bdeb | 3,637,748 |
import grp
from typing import cast
def get_os_group(name: _STR_OR_INT_OR_NONE = None) -> grp.struct_group:
"""Get an operating system group object.
Args:
name (:obj:`str` or :obj:`int`, optional): The "group name" or ``gid``.
Defaults to the current users's group.
Raises:
OSE... | 6c359b46cdd2766cbdea7fb5412b1e03a3fbecac | 3,637,749 |
def _process_output(response, context):
"""Post-process TensorFlow Serving output before it is returned to the client.
Args:
response (obj): the TensorFlow serving response
context (Context): an object containing request and configuration details
Returns:
(bytes, string): data to r... | 19805fc9ce122b4c02a596167edbc01398dfa2ab | 3,637,750 |
import sys
import plistlib
def execute_dscl(option="-plist", datasource=".", command="-read", parameters=""):
"""Execute dscl and return the values
Args:
option (str, optional): The option to use. Defaults to "-plist".
datasource (str, optional): The node to query. Defaults to ".".
co... | ae234185cbc48fa71e6a1b43408474255561a1a0 | 3,637,751 |
from bs4 import BeautifulSoup
import requests
def make_soup(text: str, mode: str="url", parser: str=PARSER) -> BeautifulSoup:
""" Returns a soup. """
if mode == "url" or isinstance(mode, dict):
params = mode if isinstance(mode, dict) else {}
text = requests.get(text, params=params).text
el... | 9641a7a0807194c911614e2ac41551b04bdbe22d | 3,637,752 |
import ast
def _merge_inner_function(
class_def, infer_type, intermediate_repr, merge_inner_function
):
"""
Merge the inner function if found within the class, with the class IR
:param class_def: Class AST
:type class_def: ```ClassDef```
:param infer_type: Whether to try inferring the typ (f... | 5c891ba82cb5b41a5b5d311611f5d318d249a31e | 3,637,753 |
def pb_set_defaults():
"""Set board defaults. Must be called before using any other board functions."""
return spinapi.pb_set_defaults() | 30d360a15e4602c64a81900a581a2f4429f7d71e | 3,637,754 |
def count_routes_graph(graph, source_node, dest_node):
"""
classic tree-like graph traversal
"""
if dest_node == source_node or dest_node - source_node == 1:
return 1
else:
routes = 0
for child in graph[source_node]:
routes += count_routes_graph(graph, child, dest... | f952b35f101d9f1c42eb1d7444859493701c6838 | 3,637,755 |
from typing import Dict
def pluck_state(obj: Dict) -> str:
"""A wrapper to illustrate composing
the above two functions.
Args:
obj: The dictionary created from the json string.
"""
plucker = pipe(get_metadata, get_state_from_meta)
return plucker(obj) | d9517346b701f9ff434452992a4f3e8ca3dccf08 | 3,637,756 |
from typing import Callable
from typing import Mapping
from typing import Any
from typing import Optional
def value(
parser: Callable[[str, Mapping[str, str]], Any] = nop,
tag_: Optional[str] = None,
var: Optional[str] = None,
) -> Parser:
"""Return a parser to parse a simple value assignment XML tag.... | dcb2ad9b9e83015f1fd86323a156bbe92d505211 | 3,637,757 |
def compute_Rnorm(image, mask_field, cen, R=12, wid=1, mask_cross=True, display=False):
""" Compute (3 sigma-clipped) normalization using an annulus.
Note the output values of normalization contain background.
Paramters
----------
image : input image for measurement
mask_field : mask map wi... | 7c0b2aebf009b81c19de30e3a0d9f91fcfcebd52 | 3,637,758 |
import six
def inject_timeout(func):
"""Decorator which injects ``timeout`` parameter into request.
On client initiation, default timeout is set. This timeout will be
injected into any request if no explicit parameter is set.
:return: Value of decorated function.
"""
@six.wraps(func)
de... | 479ed7b6aa7005d528ace0ff662840d14c23035c | 3,637,759 |
def test_match_partial(values):
"""@match_partial allows not covering all the cases."""
v, v2 = values
@match_partial(MyType)
class get_partial_value(object):
def MyConstructor(x):
return x
assert get_partial_value(v) == 3 | 826a08066822e701c2077c2b71be48152c401b3f | 3,637,760 |
def assert_sim_of_model_with_itself_is_approx_one(mdl: nn.Module, X: Tensor,
layer_name: str,
metric_comparison_type: str = 'pwcca',
metric_as_sim_or_dist: str = 'dist') ... | 76d9b88063b69b69217f28cb98c985ff92f9b6e0 | 3,637,761 |
def cver(verstr):
"""Converts a version string into a number"""
if verstr.startswith("b"):
return float(verstr[1:])-100000
return float(verstr) | 1ad119049b9149efe7df74f5ac269d3dfafad4e2 | 3,637,762 |
import urllib
def _GetGaeCookie(host, service, auth_token, secure):
"""This function creates a login cookie using the authentication token
obtained after logging in successfully in the Google account.
Args:
host: Host where the user wants to login.
service: Service code where the user wants to login.
... | 9bef7516f6b43c2b744e6bb0a75a488e8aee3934 | 3,637,763 |
async def ping_handler() -> data.PingResponse:
"""
Check server status.
"""
return data.PingResponse(status="ok") | 77d1130aa31f54fbcac351d58b8ae4e4b893c5e9 | 3,637,764 |
import subprocess
def main():
"""Start a child process, output status, and monitor exit."""
args = docopt.docopt(__doc__, options_first=True, version=__version__)
command = " ".join(args["<command>"])
timeout = parse_time(args["--timeout"])
# Calculate the time at which we will kill the child pro... | 2dbf4e514999f4805fe1cb8d36febd80cfb21458 | 3,637,765 |
import os
import csv
def get_columns_sql(table):
"""Construct SQL component specifying table columns"""
# Read rows and append column name and data type to main container
template_path = os.path.join(os.environ['MYSQL_TABLE_TEMPLATES_DIR'], f'{table}.csv')
with open(template_path, newline='') as f:
... | 0cff0f424b0284931951b7d198996328a011ffee | 3,637,766 |
def create_session_cookie():
"""
Creates a cookie containing a session for a user
Stolen from https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django
:param username:
:param password:
:return:
"""
# First, create a new test user
user =... | d4d7eef96e7b0136aa888d362b3278eb24ae91b8 | 3,637,767 |
from pathlib import Path
from typing import Optional
from typing import List
import os
import fnmatch
def is_excluded(src_path: Path, globs: Optional[List[str]] = None) -> bool:
"""
Determine if a src_path should be excluded.
Supports globs (e.g. folder/* or *.md).
Credits: code inspired by / adapted... | 6d3d2ce7a7842cb071cfe2ba8c0635a5864127a7 | 3,637,768 |
from pyquickhelper.loghelper import BufferedPrint
import os
def get_seattle_streets(filename=None, folder="."):
"""
Retrieves processed data from
`Seattle Streets <https://data.seattle.gov/dataset/Street-Network-Database/
afip-2mzr/data)>`_.
@param filename local filename
@param ... | 396dfe59db9ef68528b9aea7328581154fa84444 | 3,637,769 |
def _replace_oov(original_vocab, line):
"""Replace out-of-vocab words with "UNK".
This maintains compatibility with published results.
Args:
original_vocab: a set of strings (The standard vocabulary for the dataset)
line: a unicode string - a space-delimited sequence of words.
Returns:
a unicode ... | 2e2cb1464484806b79263a14fd32ed4d40d0c9ba | 3,637,770 |
def linear_CMD_fit(x,y,xerr,yerr):
"""
Does a linear fit to CMD data where x is color and y is amplitude, returning some fit
statistics
Parameters
----------
x : array-like
color
y : array-like
magnitude
xerr : array-like
color errors
yerr : array-like
... | fb145d5caf48d2ab1b49a17b1e05ddd32e97c3f1 | 3,637,771 |
def _verify_path_value(value, is_str, is_kind=False):
"""Verify a key path value: one of a kind, string ID or integer ID.
Args:
value (Union[str, int]): The value to verify
is_str (bool): Flag indicating if the ``value`` is a string. If
:data:`False`, then the ``value`` is assumed t... | 3d8db518f244e6d09826d29dfcc42769a0015c33 | 3,637,772 |
def _is_tipologia_header(row):
"""Controlla se la riga corrente e' una voce o l'header di una
nuova tipologia di voci ("Personale", "Noli", etc).
"""
if type(row.iloc[1]) is not str:
return False
if type(row.iloc[2]) is str:
if row.iloc[2] != HEADERS["units"]:
return Fal... | 0fdbc6bea8d961fbe990d607a175815ccc475f88 | 3,637,773 |
def validateFloat(
value,
blank=False,
strip=None,
allowRegexes=None,
blockRegexes=None,
min=None,
max=None,
lessThan=None,
greaterThan=None,
excMsg=None,
):
# type: (str, bool, Union[None, str, bool], Union[None, Sequence[Union[Pattern, str]]], Union[None, Sequence[Union[Pat... | e11bbef1b0f53fa803918f9871e9779549e3cdb8 | 3,637,774 |
from typing import Dict
from typing import Any
def send_sms(mobile: str, sms_code: str) -> Dict[str, Any]:
"""发送短信"""
sdk: SmsSDK = SmsSDK(
celery.app.config.get("SMS_ACCOUNT_ID"),
celery.app.config.get("SMS_ACCOUNT_TOKEN"),
celery.app.config.get("SMS_APP_ID")
)
try:
re... | f1117d0543cc84d0429ce67f1415e6ab371ef2a6 | 3,637,775 |
def from_dataframe(df, name='df', client=None):
"""
convenience function to construct an ibis table
from a DataFrame
EXPERIMENTAL API
Parameters
----------
df : DataFrame
name : str, default 'df'
client : Client, default new PandasClient
client dictionary will be mutated wi... | 23d64170f078652e60d65be5346293ea3c4aedb5 | 3,637,776 |
import argparse
def make_parser() -> argparse.ArgumentParser:
"""Make parser for CLI arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"site_name", help="name of the site you want to get data for",
)
parser.add_argument(
"--no-expand-meta",
action="store... | 221338e003fd07b350bb6ff9d3f95cac33a078cc | 3,637,777 |
import os
def get_files_to_parse(relative_path):
"""Walks through given directory and returns all files with ending
with an accepted file extension
Arguments:
relative_path {string} -- path to pull files from recursively
Returns:
List<String> -- list of filenames with fullpath
... | 0cc53815de09e71c14c07b35840a533a16544cd7 | 3,637,778 |
import os
async def stat_data(full_path: str, isFolder=False) -> dict:
"""
only call this on a validated full path
"""
file_stats = os.stat(full_path)
filename = os.path.basename(full_path)
return {
'name': filename,
'path': full_path,
'mtime': int(file_stats.st_mtime*1... | f78a27ac9cbe116c6a04e5a5dbc45e454b26f02b | 3,637,779 |
import os
def start_browser(cfg):
"""
Start browser with disabled "Save PDF" dialog
Download files to data folder
"""
my_options = Options()
if cfg.headless:
my_options.headless = True
my_options.add_argument('--window-size=1920,1200')
my_profile = webdriver.FirefoxProfile(... | 9ad79c1450937f120d69bd8634c81116051fa67e | 3,637,780 |
def filter_list(prev_list, current_list, zeta):
"""
apply filter to the all elements
of the list one by one
"""
filtered_list = []
for i, current_val in enumerate(current_list):
prev_val = prev_list[i]
filtered_list.append(
moving_average_filter(current_val, prev_val... | 842d71f58b07dbe771c7fdd43797f26e75565ef5 | 3,637,781 |
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
for word in dict_list:
if word.startswith(sub_s):
return True
return False | 78900ed757d4a1a94832f5a2f6d19da784935966 | 3,637,782 |
from sys import path
def get_dir_size_recursive(directoryPath):
"""
Returns the size of a directory's contents (recursive) in bytes.
:param directoryPath: string, path of directory to be analyzed
:return: int, size of sum of files in directory in bytes
"""
# Collect directory size recursively
... | c371a6135b8dcda71fb1d51e78872a84afcfcd16 | 3,637,783 |
import yaml
def main():
""" """
try:
# read parameters configuration file yaml
with open(setupcfg.extraParam, "r") as stream:
try:
param = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
# check parameters file
... | 67da82991e8ae5b36dae81c6ac107099a54ab7e4 | 3,637,784 |
def primary_key(field_type):
"""
* Returns the field to be treated as the "primary key" for this type
* Primary key is determined as the first of:
* - non-null ID field
* - ID field
* - first String field
* - first field
*
* @param {object_type_definition} type
*... | 5beef62f9311b013b6c6cbe3c36260783bc61506 | 3,637,785 |
def get_discussion_data_list_with_percentage(session: Session, doi, limit: int = 20, min_percentage: float = 1,
dd_type="lang"):
""" get discussion types with count an percentage from postgresql """
query = """
WITH result AS
(
... | 4842566f7a891ce53cfc8170cc0fb5db2a6b298b | 3,637,786 |
import collections
import torch
import time
def validate(config, model, val_iterator, criterion, scheduler=None):
"""Runs one standard validation pass over the val_iterator.
This function automatically measures timing for various operations such
as host to device transfer and processing time for the batc... | 4f10e68c2e863e11e33f4f49b8378de51ff2b8fe | 3,637,787 |
import os
def fix_path(file_path):
"""fixes a path so project files can be located via a relative path"""
script_path = os.path.dirname(__file__)
return os.path.normpath(os.path.join(script_path, file_path)) | f733b0c0eb12ced5193393013198d89cd774297a | 3,637,788 |
import json
import subprocess
import sys
def cmd(cmd_name, source, args: list = [], version={}, params={}):
"""Wrap command interaction for easier use with python objects."""
in_json = json.dumps({
"source": source,
"version": version,
"params": params,
})
command = ['/opt/res... | be1ebe77c70ce2b377cb64d6d54f043c39dde85a | 3,637,789 |
def geq_indicate(var, indicator, var_max, thr):
"""Generates constraints that make indicator 1 iff var >= thr, else 0.
Parameters
----------
var : str
Variable on which thresholding is performed.
indicator : str
Identifier of the indicator variable.
var_max : int
An uppe... | 319f18f5343b806b7108dd9c02ca5d647e132dab | 3,637,790 |
import re
def parse_manpage_number(path):
"""
Parse number of man page group.
"""
# Create regular expression
number_regex = re.compile(r".*/man(\d).*")
# Get number of manpage group
number = number_regex.search(path)
only_number = ""
if number is not None:
number = nu... | b45edb65705592cd18fd1fd8ee30bb389dbd8dff | 3,637,791 |
def sample_coordinates_from_coupling(c, row_points, column_points, num_samples=None, return_all = False, thr = 10**(-6)):
"""
Generates [x, y] samples from the coupling c.
If return_all is True, returns [x,y] coordinates of every pair with coupling value >thr
"""
index_samples = sample_indices_fro... | a8343291a34ff31a2fc7b86c9b83872e7c787b76 | 3,637,792 |
import ast
def is_suppress_importerror(node: ast.With):
"""
Returns whether the given ``with`` block contains a
:func:`contextlib.suppress(ImportError) <contextlib.suppress>` contextmanager.
.. versionadded:: 0.5.0 (private)
:param node:
""" # noqa: D400
item: ast.withitem
for item in node.items:
if not... | 341d106b62d7940e4d84a359cd2f2ca254d3434e | 3,637,793 |
def random_flip_left_right(data):
""" Randomly flip an image or batch of image left/right uniformly
Args:
data: tensor of shape (H, W, C) or (N, H, W, C)
Returns:
Randomly flipped data
"""
data_con, C, N = _concat_batch(data)
data_con = tf.image.random_flip_left_right(data_con)... | bcdd0dfd35ff7ee0237d585d5a6cd70f92d7df2b | 3,637,794 |
from sys import path
import multiprocessing
import shutil
def run_cnfs(fets, args, sims):
""" Trains a model for each provided configuration. """
# Assemble configurations.
cnfs = [
{**vars(args), "features": fets_, "sims": sims, "sync": True,
"out_dir": path.join(args.out_dir, subdir),
... | 9c35f1df874df88e5d04e342967592f5db78b506 | 3,637,795 |
import argparse
def ParseArgs(argv):
"""Parses command line arguments."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-b', '--bundle-identifier', required=True,
help='bundle identifier for the appli... | 507935ea2ea42dea66bfff545caecb7fc2cded55 | 3,637,796 |
import os
def GetCurrentBaselinePath():
"""Returns path of folder containing baseline file corresponding to the current test."""
currentTestPath = os.path.dirname(os.getenv('PYTEST_CURRENT_TEST').split(":")[0])
currentBaselinePath = baselinePath + "/" + currentTestPath + "/"
return currentBaselinePath | a374c4ca8c487fa84748ab160ef2043e4cbbeef2 | 3,637,797 |
def get_all_lobbyists(official_id, cycle=None, api_key=None):
"""
https://www.opensecrets.org/api/?method=candContrib&cid=N00007360&cycle=2020&apikey=__apikey__
"""
if cycle is None:
cycle = 2020 # I don't actually know how the cycles work; I assume you can't just take the current year?
#... | a2d8267881e871cb54201d243357739e689f187e | 3,637,798 |
def get_sale(this_line):
"""Convert the input into a dictionary, with keys matching
the CSV column headers in the scrape_util module.
"""
sale = {}
sale['consignor_name'] = this_line.pop(0)
sale['consignor_city'] = this_line.pop(0).title()
try:
maybe_head = this_line[0].split()
... | 39fee66b4c92a2cb459722f238e4a3b6e5848f4d | 3,637,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.