content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def EventType() -> str:
"""{ref}`nonebot.adapters.Event` 类型参数"""
return Depends(_event_type) | e8da20934427961b5dbe414683f7a4942e728565 | 3,609,410 |
from typing import Optional
def decode(
reference: LR,
reader: MapReader,
observer: Optional[DecoderObserver] = None,
config: Config = DEFAULT_CONFIG
) -> MapObjects:
"""Translates an openLocationReference into a real location on your map.
Args:
reference:
... | 7e80957fb891586cabccb7b8807cd6a3121262f5 | 3,609,411 |
import re
def tri_lexique_relation(conllu,lexique,relation):
"""
entrée : un conllu issu de read_file(), un lexique, une relation de dépendance
sortie :
- un dico {phrase du conllu : les suites de mots présentes dans le lexique, pour cette phrase}
- un dico {phrase du conllu : les suites de mots absentes du lexi... | 8bf910dcbd16ee62644646eec32a31e4abac08df | 3,609,412 |
def geomap_rscale(xyin,xyref,center=None):
"""
Set up the products used for computing the fit derived using the code from
lib/geofit.x for the function 'geo_fmagnify()'. Comparisons with results from
geomap (no additional clipping) were made and produced the same results
out to 5 decimal places.
... | e001fd9cbb74497088136186479418e95860b68b | 3,609,413 |
def _resegment_wrongly_merged_cells(im_next, im_labels_curr, merged_labels, mask):
"""
Correct an error in tracking for a single cell at one time point.
If two cells appear to merge when they shouldn't, this takes their
positions in the previous timepoint and uses them to generate new
seeds for a w... | b3b844d42a62f782e338880a7e94968f0fe0ba7b | 3,609,415 |
def get_events_by_location(location):
""" Gets events using a given members id.
"""
response = client.get(
f"/events/search/?q=technology&location.address={location}&sort_by=-date"
)
events = response["events"]
return events | b7bfe7039182820bacbd6963227cae64a3319a27 | 3,609,416 |
from functools import reduce
def wrap_onspace(text, width):
"""
A word-wrap function that preserves existing line breaks
and most spaces in the text. Expects that existing line
breaks are posix newlines (\n).
"""
return reduce(lambda line, word, width=width: '%s%s%s' %
(line,... | 57203550d4e3c02b6282ad8d62e14a562dc9c6a9 | 3,609,417 |
def symmetrical_relevance(x, y, z):
"""Calculate the symmetrical relevance (SR(X;Y;Z) = I(X;Y;Z) / H(X;Y|Z))
between three arrays.
Parameters
----------
x : array-like, shape (n,)
The first array.
y : array-like, shape (n,)
The second array.
z : array-like, shape (n,)
... | 134b408f37773fd43500897f3b4e0c6ab5fa5fda | 3,609,418 |
import re
def _get_numbers_from_string(string):
"""
Return a list of numbers (strings) that appear in parameter string.
Match integers, decimals and numbers such as +1, 2e9, +2E+09, -2.0e-9.
"""
numbers = re.findall(r"[-+]?(?:(?:\d+\.\d+)|(?:\d+))(?:[Ee][+-]?\d+)?", string)
return numbers | 970d57aaec18bdc6ab4a9c55f6445fbbc74998d7 | 3,609,419 |
def filter_by_response(words, guess, response):
""" Parses the Wordle guess response and filters out invalid words """
for idx,chr in enumerate(guess):
if response[idx] == ".":
words = [word for word in words if not chr in word]
elif response[idx] == chr.upper():
words = ... | 77a678f6603fb16e34a5b74a3350e560efa4f82d | 3,609,420 |
def GetVersion(vm):
"""Returns the version of the memcached server installed."""
results, _ = vm.RemoteCommand('memcached -help |grep -m 1 "memcached"'
'| tr -d "\n"')
return results | ba0a16d7e9f8f7702d6f5f41595a6a47a39e0f6b | 3,609,421 |
def do_mixup(x, mixup_lambda):
"""Mixup x of even indexes (0, 2, 4, ...) with x of odd indexes
(1, 3, 5, ...).
Args:
x: (batch_size * 2, ...)
mixup_lambda: (batch_size * 2,)
Returns:
out: (batch_size, ...)
"""
out = (x[0 :: 2].transpose(0, -1) * mixup_lambda[0 :: 2] + \
... | 93794ae5249afd49d0a88bb8c31066de51bbebf7 | 3,609,423 |
def grid_create_from_coordinates_periodic_3d(longitudes, latitudes, heights,
lon_corners=False, lat_corners=False, z_corners=False,
corners=False, domask=False):
"""
Create a 3 dimensional periodic Grid using longitudes, l... | 7206d59f804dee8270759e9aec75e2968bebb692 | 3,609,424 |
from typing import Optional
from typing import Dict
def read_labels_yaml(
csvpath: PathType, prefix: Optional[str] = None
) -> Dict[str, DictConfig]:
"""Read labels from csvfile in YAML format."""
labels = pd.read_csv(csvpath)
cells = OmegaConf.create()
for label in labels.iterrows():
lab... | 36b840e3c6e616009d4f2180846c1100183473ce | 3,609,426 |
def exec_container(c, d, t, n, s='http://portainer:9000/api', e='1'):
"""Execute command within container.
Execute a command within a running container.
Args:
c: Container id
d: List containing command
t: Authorization token
n: Container swarm node
s: Portainer serv... | 86dd7c638051dcb905d3f1538e357f09243f33b6 | 3,609,427 |
from typing import Dict
from typing import Tuple
from typing import Optional
def _map_rest_error(json_data: Dict[str, str]) -> Tuple[StatusCode, Optional[str]]:
"""
Map a Databricks REST API error (from the returned JSON) into a
status code and a message.
:param json_data: the JSON returned from the ... | b7bdc7af56f4263365d5347816bf3a799104011d | 3,609,428 |
def abs_energy(x):
"""
Returns the absolute energy of the time series which is the sum over the squared values
.. math::
E = \\sum_{i=1,\ldots, n} x_i^2
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this feature
:return type: fl... | a7ac52ec68192990358ed9a5ebacf0d59f34a7dc | 3,609,429 |
def write_bytes(path: str, content: bytes) -> Effect[HasFiles, OSError, None]:
"""
Get an `Effect` that writes to a file
Example:
>>> class Env:
... files = Files()
>>> write_bytes('foo.txt')(b'content of foo.txt')\\
... .discard_and_then(read('foo.txt'))\\
.... | f156cdac9553817e4212c97be785e5bbad30141c | 3,609,430 |
def get_sentiment_compound(value):
"""
function get value and return whether it's Positive, Negative or Neutral
:param value: floating number
:return: whether value is Positive, Negative or Neutral
"""
# decide sentiment as positive, negative and neutral
if value > 0:
sentiment_compo... | 7feae8fd085efb9a2e684844a25ab1a1d9b3dad0 | 3,609,431 |
def get_value_mappings(src_table, dest_table, src_field, dest_field):
"""
This function translates values between src_field and dest_field.
E.g. the value primary_condition for condition_type_concept_id needs to be translated to
the value primary_procedure for procedure_type_concept_id
:param src_ta... | a63de53d893fbe55453964288dec7c1f754a73cb | 3,609,432 |
from functools import reduce
def run_map(generator, mapper) -> list:
"""
Map function caller for each line in each file
:param generator: file and line generator
:param mapper: map function to be called for each line in the files
:return: generator of key value pairs returned by the map function
... | 468467f9274572d82b8843449ffe9691b68331cc | 3,609,433 |
from typing import Iterable
from typing import Set
def get_all_nodes(edges: Iterable[Edge]) -> Set[BaseNode]:
"""Return the set of nodes connected to edges."""
nodes = set()
for edge in edges:
if edge.node1 is not None:
nodes |= {edge.node1}
if edge.node2 is not None:
nodes |= {edge.node2}
... | 38393c91c284ae01ddf3a2f1654a5aee0fb094d2 | 3,609,434 |
def get_collection_latest(parser, token):
"""
{% get_latest_from_collection collection_url num as latest_forecast %}
Returns the most recent 'num' items from the specified collection.
"""
bits = token.split_contents()
if len(bits) == 5:
return CollectionLatestNode(bits[1], bits[2],... | d6a76221b1fa87560bfd0e604701bc5d4c1ec655 | 3,609,435 |
import base64
import requests
def docker_registry_authenticate(www_authenticate):
"""
returns a dictionary of headers to add as part of original request
including access_token
takes the Www-Authenticate header from the 401 response of a
registry request
like 'Bearer realm="https://192.168.204.... | 536453b743f41223030a7d07778d1dceb09c6ab5 | 3,609,436 |
def apply(request, pk):
"""
Let a user apply to a proposal. Called after confirmapply.
:param request:
:param pk: id of a proposal.
"""
prop = get_cached_project(pk)
if prop.Status < 4:
raise PermissionDenied('This proposal is not public, application is not possible.')
if get_a... | 8b02b219f988162c88078605dc8ec22ab319892e | 3,609,437 |
def heatmap(data, row_labels, col_labels, ax=None,
cbar_kw={}, cbarlabel="", **kwargs):
"""
Create a heatmap from a numpy array and two lists of labels.
Parameters
----------
data
A 2D numpy array of shape (N, M).
row_labels
A list or array of length N with the label... | c24ecca19da3855c008c55c90fc2bb5d4ebbb737 | 3,609,438 |
def svn_client_propset3(*args):
"""svn_client_propset3(char const * propname, svn_string_t const * propval, char const * target, svn_depth_t depth, svn_boolean_t skip_checks, svn_revnum_t base_revision_for_url, apr_array_header_t changelists, apr_hash_t revprop_table, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_e... | b05cf35f5ad3edd7592df0a693570e539301bd68 | 3,609,439 |
from typing import List
import traceback
def logger(func):
""" logger """
def wrapper(*args, **kwargs):
try:
print(f'start {func.__name__}, args: {args}, kwargs: {kwargs}')
result = func(*args, **kwargs)
print(f'finish {func.__name__}, result: {result}')
... | 99b566c50585bf4514c43b76405fcf1dd43ff948 | 3,609,440 |
def chebfit(x, y, deg, rcond=None, full=False, w=None):
"""
Least squares fit of Chebyshev series to data.
Fit a Chebyshev series ``p(x) = p[0] * T_{0}(x) + ... + p[deg] *
T_{deg}(x)`` of degree `deg` to points `(x, y)`. Returns a vector of
coefficients `p` that minimises the squared error.
Pa... | 81c20a14055893a3139e222d60e932f7f52d11fb | 3,609,441 |
def load_numpy(file_name):
"""Loads numpy binary file as array"""
file_name = replace_ext(file_name, 'npy')
try:
array = np.load(file_name)
except IOError as e:
raise IOError(
f"Cannot read file {file_name}"
) from e
return array | bec0a8dfd8547df88418476f0ea02d95e5bd5c9a | 3,609,442 |
def draw_on_road(img_undistorted, Minv, left_line, right_line, binary, pers_image):
"""
Draw both the drivable lane area and the detected lane-lines onto the original (undistorted) frame.
Args:
img_undistorted: original undistorted color frame
Minv: (inverse) perspective transform matrix us... | 96c20fc9fa751759b93baca3b21604c61eb309bb | 3,609,444 |
def gram_schmidt_columns(X):
"""
Apply Gram-Schmidt orthogonalization to obtain basis vectors.
"""
B = np.zeros(X.shape)
B[:, 0] = (1/np.linalg.norm(X[:, 0]))*X[:, 0]
for i in range(1, 3):
v = X[:, i]
U = B[:, 0:i] # subspace basis which has already been orthonormalized
p... | cefec14e3709b2c3bf606fe07d0fcc142ed29782 | 3,609,445 |
def put_pm_to_pandas_data(data: dict) -> dict:
"""
Change the +- to \pm for latex display.
Note: to have the pandas frame display the table string correctly use the escapte=False as in:
latex_table: str = df.to_latex(index=False, escape=False, caption='caption goes here', label='label_goes_here')
... | 50193af607b8321601f35350283386021509b1bd | 3,609,447 |
def bd_gcj(lon, lat):
"""Convert BD09 coordinates to GCJ02 (fast estimation)."""
result = lib.prcoords_bd_gcj({'lon': lon, 'lat': lat}, 0)
return (result.lon, result.lat) | 711a8018949075361c04b3626ae75567117b98c3 | 3,609,448 |
def export_saved_form_data_entries(request, form_entry_id=None, theme=None):
"""Export saved form data entries.
:param django.http.HttpRequest request:
:param int form_entry_id: Form ID.
:param fobi.base.BaseTheme theme: Subclass of ``fobi.base.BaseTheme``.
:return django.http.HttpResponse:
"""... | 86bd61d807008578329ab1fdd7308798d90ff58a | 3,609,449 |
from typing import Dict
from typing import Any
import json
def set_blob_tags_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Sets the tags for the specified Blob.
Args:
client (Client): Azure Blob Storage API client.
args (dict): Command arguments from XSOAR.
Ret... | e414c6b53b36dca2b47fc1689455fde92bf5c5cd | 3,609,450 |
import functools
import operator
def get_multipliers(*params):
"""
Determines the overall multiplier for a pokemon of specified type(s) attacking another pokemon of specified type(s)
Accepts the types as any one of the following:
A string with an attacker move/type, followed by '->', followed by a... | c75a66456477426dadc28ce84f952c14bc6622d2 | 3,609,451 |
def calculate_roi():
"""
Calculate returning on investment for 4 years.
"""
request_parameters = request.get_json()
arguments, errors = CalculateRoiForm().load({
'months': request_parameters.get('months'),
'money_per_month': request_parameters.get('economy').get('money_per_month'),
... | 1ba5e929ad71aa42e811b597ff9b251bbeafdbe0 | 3,609,452 |
def safe_filename(filename, replace=' '):
"""文件名过滤非法字符串
"""
replace_illegal_str = str.maketrans(
ILLEGAL_STR, replace * len(ILLEGAL_STR))
new_filename = filename.translate(replace_illegal_str).strip()
if new_filename:
return new_filename
raise Exception('文件名不合法. new_filename={}'.... | 1df9a49f1288ab0533ae49a0e041875fafc72a94 | 3,609,453 |
import copy
def prepare_chart_data(val_list, factors):
"""
combine value and sample info together, grouping, collapse
by order_index
"""
factors = copy.deepcopy(factors)
# combine values and samples, just by position in the array
for idx, e in enumerate(factors):
e['value']... | 950839ab6ee30e7a278de66527b1db3d4c5b5441 | 3,609,454 |
def black_on_red(string, *funcs, **additional):
"""Text color - black on background color - red. (see sgr_combiner())."""
return sgr_combiner(string, ansi.BLACK, *funcs, attributes=(ansi.BG_RED,)) | 2e2e035baac1fb9c2d070b9c93f04db9cd2875f3 | 3,609,455 |
import typing
from pydantic_factories import ModelFactory
def create(input_block: LinearBackboneModel, output_dim: int,
rnn_layers: typing.List[int], rnn_dropout: float=0.0, bidirectional: bool=False,
linear_layers: typing.List[int]=None, linear_dropout: float=0.0):
""" Vel creation function... | 87f67f2a671abe61f2c8f068037bfd59d674f9af | 3,609,456 |
def nrvocale(text):
"""Scrieti o functie care calculeaza cate vocale sunt intr-un string"""
count = 0
for c in text:
if c in ['a', 'e', 'i', 'o', 'u']:
count = count + 1
return count | 083d0bd8e8954a795fe36abaf567472561a9e13f | 3,609,458 |
def GetATMValueSummary(atm_value):
""" Summarizes the atm_value
params: atm_value = value object of type atm_value_t
returns: string with the summary of the type.
"""
format_str = "{0: <#020x} {1: <16d} {2: <#020x} {3: <16d}"
out_string = format_str.format(atm_value, unsigned(atm_value.a... | 70b0c2c303beead4e31c1286b75712057d04c904 | 3,609,459 |
import pathlib
def abst_path(path):
"""Returns a PurePath for a string representation, after checking a
path string is from the root."""
p = pathlib.PurePath(path)
assert p.is_absolute()
return p | b86ecd8585575e3642ddd1ff54de91eb1cd5d6d9 | 3,609,461 |
def fpga_read(addr):
"""
read and return FPGA register content (one byte)
input:
addr : address of the register relatively to the beginning
FPGA memory address
output:
v : register content
"""
check_running_onjog()
if jogio_utils.robotPlatform == "JOG":
... | f172bcae5f53aff775802f727fe2f351dc2618f6 | 3,609,462 |
def visualize_reconstruction_and_att(img, img_size, vertices_full, vertices, vertices_2d, camera, renderer, ref_points, attention, focal_length=1000):
"""Overlays gt_kp and pred_kp on img.
Draws vert with text.
Renderer is an instance of SMPLRenderer.
"""
# Fix a flength so i can render this with pe... | 4e5e5b556d4e6eb2a693f4d371fa5b404aa23728 | 3,609,463 |
from typing import Concatenate
def yolo_body(input_shape, anchors_mask, num_classes):
"""
YoloV4 FPN and head network building
:param input_shape: image input shape
:param anchors_mask: anchor masks
:param num_classes: number of category classes
:return: Model
"""
inputs = Input(input_... | 4a0b8d3f2d9578f338ff6e144b6a77fbf2b230f9 | 3,609,464 |
def find_matrix_min(matrix):
""" find matrix minimal values
:param ndarray matrix:
:return float, [(int, int)]:
>>> np.random.seed(0)
>>> mx = np.round(np.random.random((3, 4)), 3)
>>> mx
array([[0.549, 0.715, 0.603, 0.545],
[0.424, 0.646, 0.438, 0.892],
[0.964, 0.383... | d26a2737a6da014f4dd720daeb674a9effb09f6c | 3,609,465 |
def new_cluster(number_of_stars=1000, radius=None):
"""
Return a new cluster of stars with the given radii and a salpeter mass
distribution.
"""
if radius is None:
radius = (0.5 / number_of_stars) | nbody_system.length
particles = new_plummer_model(number_of_stars)
particles.mass = ... | a57664806c0750ca8084520011ced224921130b8 | 3,609,466 |
def compute_centerlines(params):
""" Compute the centerlines for a surface model.
"""
## Check input parameters.
#
if not params.surface_model:
logger.error("No surface model has been specified.")
return
if not params.centerlines_output_file:
logger.error("No centerline... | b5587edc32e9f360fa5d22078dcb0eaa3f71dd86 | 3,609,467 |
def type_user(update: Update, context: CallbackContext) -> int:
"""Prompts user to type username"""
# user has entered the function through the main menu
language = context.user_data["bot_lang"]
msg = context.bot_data["texts"][language]["type_user"]
if update.callback_query:
update.callback... | 30ffdb749f6a2a4cb81b6c5267545a148503c63a | 3,609,468 |
import mpmath
import typing
def default_val(utype):
""" Returns a generic default value for a given type"""
if utype is int:
return 0
elif utype is float:
return 0.
elif utype is mpmath.mpf:
return mpmath.mpf("0.0")
elif utype is str:
return ""
elif utype is boo... | aa2fc3cbba5db3ddee6ff20fa86a53f28d9381bc | 3,609,469 |
def nvl(value, default):
""" Evaluates if value es empty or None, if so returns default
Parameters:
value: the evalue to evaluate
default: the default value
Returns:
value or default
"""
if value:
return value
return default | 67df45a6e63c107dcef99fc7bdbaa7064b695f66 | 3,609,470 |
def get_data_lazy(image: ImageWrapper, c_index: int = 0) -> da.Array:
"""Get n-dimensional dask array, with delayed reading from OMERO image."""
size_z = image.getSizeZ()
size_t = image.getSizeT()
size_x = image.getSizeX()
size_y = image.getSizeY()
pixels = image.getPrimaryPixels()
@delayed... | 12b990bc1f7fb2a355463c2c1543605c3169a0b2 | 3,609,471 |
def verify_crm_thresholds(dut, family, thresholdtype=None, highthreshold=None, lowthreshold=None, cli_type=""):
"""
To verify the CRM Threshold parameters
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut:
:param family:
:param thresholdtype:
:param highthreshold:
:param l... | 3e29cc301aae1ded583be28c07ead508dbb1c59f | 3,609,472 |
from typing import Union
from pathlib import Path
from typing import Dict
from typing import List
from typing import Counter
def load_crowdsourced_xlsx_to_predictions(
data_path: Union[Path, str], questions_to_ids: Dict[str, str]
) -> Dict[str, List[str]]:
"""
Load in the crowdsourced "fixed spelling" dat... | e7756ec0de63df3b8e2630280e0def27aaf20fe3 | 3,609,473 |
from datetime import datetime
def get_group_by_date_query_set(query_set, start_date=None, end_date=None, specific_year=True):
"""
:param query_set: Query before annotation
:param start_date: <Date>
:param end_date: <Date>
:param specific_year: To filter query_set with date__range else filter with ... | b080bdd710d5390ce934368cf51ab20c59eb6ffc | 3,609,474 |
def index(request, template_name='appname/example_list.html'):
"""Index view."""
qs = Example.objects.all()
try:
page = int(request.GET.get('page', 0))
except ValueError:
raise Http404
return object_list(
request,
queryset=qs,
template_object_name='example',... | 20d14742cc94a861aa8274e00174c817b7a4db08 | 3,609,475 |
def UseExceptions(*args):
"""UseExceptions()"""
return _gdal.UseExceptions(*args) | 43f07f56a0fdc866f6495116ad68f4f32d9c68a5 | 3,609,476 |
from .models import DepartmentUser
from datetime import datetime
def alesco_data_import(fileobj):
"""Import task expects to be passed a file object (an uploaded .xlsx).
"""
LOGGER.info('Alesco data for DepartmentUsers is being updated')
wb = load_workbook(fileobj, read_only=True)
ws = wb.worksheet... | 05de3fc8a4851e028fdb82a6de24843c4120dbed | 3,609,477 |
def derive_aggregation(dim_cols, agg_col, agg):
"""Produces consistent aggregation spec from optional column specification.
This utility provides some consistency to the flexible inputs that can be provided
to charts, such as not specifying dimensions to aggregate on, not specifying an
aggregation, and... | 402c92a14b81d0e07ab4d36ccfd0854d0059d666 | 3,609,478 |
def redefine_strides(f):
"""Redefine attribute strides in dparray returned by specified function"""
def wrapper(*args, **kwargs):
res = f(*args, **kwargs)
if not isinstance(res, dparray):
return res
strides = dpnp.asnumpy(res).strides
res._dparray_strides = strides
... | 7986c27f98b6728931e3b562aaf9754a427333f6 | 3,609,479 |
import click
def no_prompt_option(fn):
""" No prompt
"""
append_params(fn, [
click.Option(
("-y", "--yes"),
help="Do not prompt before running operation.",
is_flag=True),
])
return fn | 01ea7a1a75db5c3d904cdd621a8a8f36cc57171b | 3,609,480 |
def c10data_to_bas(c10data):
"""Given a C10Data Object, returns a bstring containing the equivalent
BASIC program"""
if c10data.filetype != 0:
raise Exception(f'{c10data.filename} has a filetype of'
f'{c10data.filetype}, expected 0')
if c10data.binary_mode != 0:
r... | e4f55a7781b4e13f15d72390a8bfdf296f7dfeed | 3,609,481 |
def Keywords(lang_id=0):
"""Returns Specified Keywords List
@param lang_id: used to select specific subset of keywords
"""
if lang_id == synglob.ID_LANG_DJANGO:
return [(1, KEYWORDS)] | acaa9ef4cc85da81b544edeb746fee99ae880843 | 3,609,482 |
def create_list_from_file(input_file):
"""Read a file into a list of lists where the nested list is split on whitespace."""
file_list = []
with open(input_file) as inputfile:
for line in inputfile:
file_list.append(line.strip().split(' ', 1)) # the check sum and file name are sepa... | 44008af32ead4ceff3597e8c479c100a12c7de15 | 3,609,483 |
def llik_gamma(x, s=None, pool=None, max_iters=10000, tol=1e-7,
extrapolate=True, **kwargs):
"""Return marginal log likelihood of Gamma expression model for each
column of x
x - Anndata (n, p)
s - size factor (n,) (default: total molecules per sample)
"""
return _map_llik(_llik_gamma, x, s, p... | b7e5925832b283a99c2a274010fb33743329eb4f | 3,609,484 |
import torch
def predict_sliding_(net, image, tile_size, classes, scale=1):
"""
Parameters
----------
net : nn.Module
image : torch.Tensor
shape [batch_size, c, h, w]
tile_size: tuple or list
max size of image inputted to the net
scale : scalar
Return
-----... | b878876687dad25583a989a0556f5c91928504ff | 3,609,485 |
import time
def wait_until_reachable(ip, timeout=None):
"""等待直到节点可达
Args:
ip: 主机IP
timeout: (Default value = None)
Returns:
Bool: 状态
"""
if not timeout:
while True:
if ping(ip):
print("{}已ping通".format(ip))
break
... | c9175b8c054f9e90741f08858a27e8633a25b7da | 3,609,486 |
import tqdm
def pool_worker(target, inputs, num_worker=None, verbose=True):
"""Run target function in multi-process
Parameters
----------
target : func
function to excute multi process
inputs: list
list of argument of target function
num_worker: int
number of worker
ve... | 4e6807bedb744858d5f6ed01855d43e0278c4761 | 3,609,487 |
def _qnwtrap1(n, a, b):
"""
Compute univariate trapezoid rule quadrature nodes and weights
Parameters
----------
n : int
The number of nodes
a : int
The lower endpoint
b : int
The upper endpoint
Returns
-------
nodes : np.ndarray(dtype=float)
A... | f12d6963dbde7a0c2a8b16f5772cd11c47796f90 | 3,609,488 |
def process_header(cols):
""" Splits the proposed header from the command line on commas, and checks
for the appropriate number of columns (passed as cols). If this number
is incorrect, a warning is given.
If the number of columns in the header is too few, the cells are
padded.
... | 56f6d7ae9601a41b070a660f50db003c7fd00f54 | 3,609,489 |
import pywt
from scipy import signal
def dominant_wavenumber(field, grid, n_scales=120, smoothing=(21, 7)):
"""Dominant zonal wavenumber at every gridpoint of field.
Implements the procedure of Ghinassi et al. (2018) based on a wavelet
analysis of the input field.
- `n_scales` determines the number ... | e90e311d63a9e274d8aac3e35993e8519d65ff3f | 3,609,490 |
import hashlib
def hash_password(password):
"""
Normal MD5, except add c if a byte of the digest is less than 10.
"""
password_md5 = hashlib.md5(password.encode("utf-8")).hexdigest()
for i in range(0, len(password_md5), 2):
if password_md5[i] == "0":
password_md5 = password_md5... | c806cbe22b99cd861ef4c9d19f971e6d61216c72 | 3,609,491 |
def to_latlon(easting, northing, zone_number, northern=None):
"""
Main function to convert UTM to latitude-longitude.
Takes XY and returns latlon basically.
Arguments:
easting (float or array): list of easting (X) coordinates
northing (float or array): list of northing (Y) coordinates
zo... | 3c008d2f298a9d940b8869633cd2e67af27d4605 | 3,609,494 |
def _suitable_minimum_unit(minimum_unit: Unit, suppress: list[Unit]) -> Unit:
"""Return a minimum unit suitable that is not suppressed.
If not suppressed, return the same unit:
>>> from human_readable.times import _suitable_minimum_unit, Unit
>>> _suitable_minimum_unit(Unit.HOURS, [])
<Unit.HOURS: ... | b84e1f58a040f1c8c606c89c55a1e34c4322088b | 3,609,495 |
def test_inside_lambda():
"""
>>> obj = test_inside_lambda()()
>>> next(obj)
1
>>> next(obj)
2
>>> next(obj)
Traceback (most recent call last):
StopIteration
"""
return lambda:((yield 1), (yield 2)) | f737fce5c04b1bb7a9b7b8a15edc60571732c2d8 | 3,609,496 |
from datetime import datetime
def check_version_format(version):
"""
Checks if a version number is well formed, eg:
YYYY-MM-DDTHH:mm:ss
"""
try:
datetime.datetime.strptime(version, "%Y-%m-%dT%H:%M:%S")
return True
except Exception:
raise HTTPError(406,
... | 37430e75eab841a68fa9ecced659049492f0dc7a | 3,609,497 |
from datetime import datetime
def buy():
"""Buy shares of stock"""
transaction = "BUY"
# if requested via post
if request.method == "POST":
# saving the user input values
name = request.form.get("symbol")
if not name:
return apology("Please enter a 4 letter ticker... | 66f1e74d858404437ca6644b7a5eb2f0bd3a36bf | 3,609,498 |
def get_properties_node(character_node):
"""
Returns HIKProperty2State node of the given HumanIk Character node
:param character_node: str
:return: str
"""
if not is_character_definition(character_node):
raise Exception(
'Invalid character definition node! Object "{}" does n... | 20949be3fb93ab994affddcad8cf87c8806cf4f4 | 3,609,499 |
def isnetid(s):
"""
Returns True if s is a valid Cornell netid.
Cornell network ids consist of 2 or 3 lower-case initials followed by a
sequence of digits.
Examples:
isnetid('wmw2') returns True
isnetid('2wmw') returns False
isnetid('ww2345') returns True
isnetid('w2345') r... | d4ddd91a9a7a7a4e2e7de778525718ec41c42cbc | 3,609,500 |
def delete_column(idf, list_of_cols, print_impact=False):
"""
:param idf: Input Dataframe
:param list_of_cols: List of columns to delete e.g., ["col1","col2"].
Alternatively, columns can be specified in a string format,
where different column names are separ... | 020ffa98855bdfa3de934122cbd6df79bc2c00e6 | 3,609,501 |
def generate_sql_verification_data(sql_results_instance):
"""Generates the verification text for a given result sql.
Keyword arguments:
sql_results_instance -- the sql results returned from athena
show_columns -- boolean for whether to show column names or not in the results
"""
results_string ... | ac2a880c6f4e2138f2d229aee96d42b81fa6e73b | 3,609,502 |
from pathlib import Path
import glob
def filter_paths(paths, excluded_paths):
"""Filter out path matching one of excluded_paths glob
Args:
paths: path to filter.
excluded_paths: List for glob of modules to exclude.
Returns: An iterable of paths Python modules (i.e. *py files).
"""
... | 8b8e9e19ebc0a47d84e1b55a497438b961af6764 | 3,609,503 |
def get_user_data(username):
"""Returns user data."""
user = User.query(User.username_lower == username.lower()).get()
if user:
user.data["metadata"]["last_updated"]=user.last_updated
return jsonify(data=user.data) if user else jsonify(error=404) | f01106c6c06fc32411ab5e89677933a8f9a040f1 | 3,609,504 |
def filter_roidb(roidb):
"""
Remove roidb entries that have no usable RoIs.
"""
def is_valid(entry):
# Valid images have:
# (1) At least one foreground RoI OR
# (2) At least one background RoI
overlaps = entry['max_overlaps']
# find boxes with sufficient over... | 31ba6a3921e2fc2aabb2e42c6af8ba2bc3566c9b | 3,609,505 |
def _extract_keywords(tweets):
"""...
Args:
tweets: List of tweets.
"""
neg, neu, pos = {}, {}, {}
for tweet in tweets:
for word in tokenizer.tokenize(RE_RUS_LETTERS.sub(u"", tweet["text"].lower())):
keyword = morph.parse(word)[0].normal_form
if keyword in ... | 1b2fb14d010e56695df2586856859c16fff04f56 | 3,609,506 |
from typing import Tuple
import torch
def getDiscriminatorModels() -> Tuple[torch.nn.Module, torch.nn.Module]:
"""
Prepares the CycleGAN discriminator models based on the given configuration.
Returns
-------
Tuple[torch.nn.Module, torch.nn.Module]
clean discriminator, distorted discrimina... | a79e5a4933e5ee66b625d08dce69204b5ae7d59b | 3,609,508 |
def merge_runs_by_tag(runs, tags):
"""
Collect the (step, value) tuples corresponding to individual tags for all runs.
Therefore the result might look like this:
<tagA>
+ step:
- <run-1-steps>
- <run-2-steps>
+ value:
- <run-1-values>
- <run-2-values>
.... | 90440ec8d718692978e617920eac52e0ea43bfce | 3,609,509 |
import math
def compute(formula, key, amount=1):
"""Function that computes the amount of fuel needed to create the
component KEY. Uses the formula input to follow the process chain."""
# If you reach FUEL, just return how much <fuel> you need
if key == "FUEL":
return amount
# Count how m... | 9c48f342f5771c8922ea19c101c613e34f884f4f | 3,609,510 |
import numpy
def moment(array,substract_one_in_variance_n=True):
"""
Calculate the first four statistical moments of a 1D array
:param array:
:param substract_one_in_variance_n:
:return: array with: m0 (mean) m1 (variance) m2 (skewness) m3 (kurtosis)
"""
a1 = numpy.array(array)
m0 = a1... | 9eae3d87b76ece9f6d351fe17de2bf439a447718 | 3,609,511 |
def best(z, i, down, values):
""" find best number (first possible downwards or upwards) that leads to z == zero at end"""
for digit in (range(9, 0, -1) if down else range(1, 10, 1)):
z_after = run(z, digit, i, values)
if i == 13: # at the end of the number, z must be zero
if z_afte... | cc440547058e398fc126ab59dec031a0808eda50 | 3,609,512 |
from typing import List
from typing import Tuple
def Gbk_presel(best_gain: List[int], cand1: int, cand2: int, gcode0: int) -> Tuple[int, int]:
"""
# (i) [0] Q9 : unquantized pitch gain
# (i) [1] Q2 : unquantized code gain
# (o) : index of best 1st stage vector
# (o) : index of best 2nd stag... | 1c88fd0c667199647ec9680071ec2ce620dea567 | 3,609,513 |
import struct
def getCommandString(commandCode):
"""Returns a readable string representation of a message code
"""
return struct.pack('<L', commandCode) | 1e0c63a13f9a727cc4aac7a6d24eacad958b0040 | 3,609,514 |
from typing import Union
from typing import Optional
def from_graph(graph: nx.Graph,
prob: Union[float, int] = 0.1,
rng: Optional[np.random.Generator] = None) -> nx.Graph:
"""Generates mutated graph with the given mutation probability.
Parameters
----------
graph
... | 4d5b37ae33d718671af92bb1c00996a4b036b0b0 | 3,609,516 |
def get_preprocessed_data_set(data_path):
"""Preprocess the data set and return it. Because a list of targets and the paths
to the images are needed later, the class ImageFolderWithTargetListAndPaths
is used. Preprocessing follows standard ResNet-preprocessing.
Args:
data_path: path to folder... | a57e434e986a3ab875506fd2cc3d15814f6bbae5 | 3,609,517 |
from typing import List
from typing import Tuple
def parse_meta_staff_elem(
staff_elem: Element, resolution: int, measure_indices: List[int]
) -> Tuple[List[Tempo], List[KeySignature], List[TimeSignature], List[Beat]]:
"""Return data parsed from a meta staff element.
This function only parses the tempos,... | 8e1fbef69d4be59af67b3a252e46c0c56e679ee2 | 3,609,518 |
def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if val is None:
return None
elif isinstance(val, string_types):
return import_from_string(val, setting_name)
elif isinstance(val, (li... | 8ceee3d8e42db5de5e1bc08d89b82c8244981a82 | 3,609,520 |
def get_root_url(g, website_url):
"""Given website url, get its root node."""
return (
g.V(website_url)
.hasLabel("website")
.in_("links_to")
) | 662eca8a6d1e6ea1e4e19d8807c3467154a8e715 | 3,609,521 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.