content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def sell_open(id_or_ins, amount, price=None, style=None):
"""
卖出开仓
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
:param int amount: 下单手数
:param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。
... | ec0557b2bb01e6cc138a61c5b1dc81d2c63150fd | 3,599,655 |
async def async_setup_scanner(
opp: OpenPeerPower, config, async_see, discovery_info=None
):
"""Set up the MySensors device scanner."""
if not discovery_info:
return False
new_devices = mysensors.setup_mysensors_platform(
opp,
DOMAIN,
discovery_info,
MySensorsDev... | f75fd09a9f90368ec81f06d84621c7561b591ba7 | 3,599,656 |
def get_all_bbox_masks_with_stride(mask, stride_factor):
"""
Find the bbox and corresponding masks
"""
bbox_mask = np.zeros_like(mask)
bounding_boxes, _ = get_bbox(mask)
y_size, x_size = bbox_mask.shape
for x, y, h, w in bounding_boxes:
x_min = x - stride_factor
x_max = x + h... | d4c366a7a0784eb8701a17f01edafbaa76f78bc4 | 3,599,657 |
def get_metrics():
"""Returns a list of specified metrics, wrapping up losses as metrics"""
metrics = [metric_from_dict(m) for m in config.classify.metrics()]
metrics = [LossToMetricWrapper(m) if issubclass(type(m), tf.keras.losses.Loss) else m for m in metrics]
return metrics | 1e475643fe1c0e2974c5df8e76add7e1ff26a6bd | 3,599,658 |
import logging
def add_results_to_json(js, nbest_hyps, char_list):
"""Function to add N-best results to json
:param dict js: groundtruth utterance dict
:param list nbest_hyps: list of hypothesis
:param list char_list: list of characters
:return: N-best results added utterance dict
"""
# c... | 146d241f674fb21d396aa57885d21e4548bcf9e9 | 3,599,659 |
def get_timediff(dataset,
start_time,
end_time):
"""
Usage: [arg1]:[Pandas DataFrame],[arg2]:[column-start_time],[arg3]:[column-end_time]
Returns: DataFrame with additional column [Duration in seconds]
"""
dataset['secs_diff_' + start_time + '_' + end_time] = (datas... | 8fff531201953cd637027c0b6ac76e9ae45dc380 | 3,599,660 |
import math
def augmentation_complete_tf2(im_x,
rotation=[0, 360],
gain=[0.8, 1.0, 1.2],
gamma=[0.5, 1.0, 2],
zoom=[0.9, 1.0, 1.1],
gaussian_noise=None,
bias=None... | 4f01eb2a5f1b2e4d28dc3e7f250854982421150e | 3,599,661 |
from typing import List
from typing import Optional
from datetime import datetime
def parse_datestamp(datestamp: str, *, strict: bool = False) -> date:
"""Return the date that maps to datestamp.
If strict is True, a full datestamp is expected (year/month/day):
"2019/11/11" => 2019/11/11
Otherwi... | ac88e6be149565383000edfd4c145cc6a35b055b | 3,599,662 |
from .core import AbstractSimpleExtractor
from typing import Any
def is_simple_extractor(obj: Any) -> bool:
"""
Determine the object if it is a simple extractor, return :obj:`True` if it is.
"""
# Local Folder
return isinstance(obj, AbstractSimpleExtractor) | 513b1d9f5c7c6db98a7c10a6348c09374e2fb9bb | 3,599,663 |
def invert(d):
"""Dict of lists -> list of dicts."""
if d:
return [dict(zip(d, i)) for i in zip(*d.values())] | 1ac60d7c294e159836be3f6c83817ad7de4f7125 | 3,599,664 |
def materialize(self):
"""Materializes the implicit notifications of an observable sequence as
explicit notification values.
Returns an observable sequence containing the materialized notification
values from the source sequence.
"""
source = self
def subscribe(observer):
def on_n... | 0af5e1107d5185368b03e6308ad2971ec9d0c315 | 3,599,665 |
def get_format_style(deck) -> str:
""" Возвращает соответствующий класс стиля формата колоды """
matching = {0: 'unknown',
1: 'wild',
2: 'standard',
3: 'classic'}
return matching[deck.deck_format.numerical_designation] | 79fd7febf913deb684c5499768cdb11621952a6e | 3,599,666 |
def get_day_query_info():
"""
get the day query info of product rt during latest 7 days
:return:
"""
all_rt_heat_metric_list = get_rt_day_query_count()
day_query_rt_dict = {}
for each_rt in all_rt_heat_metric_list:
query_list = []
dataset_id = each_rt["key"]
query_cou... | 53857fab0fd1bd7ca82f8c8f64d15a6fa50e41e4 | 3,599,667 |
def get_logp_diff_fn(apply_flat, noise_scale, parallel):
"""Returned function computes `log p(theta'|X,y) - log p(theta|X,y)`."""
lvar = noise_scale**2
def logp_diff_fn(theta, theta_prime, x, y):
preds, preds_prime = apply_flat(theta, x), apply_flat(theta_prime, x)
diff = 0.5 * jnp.sum((y - preds) ** 2 ... | 4433544b89d95f67b5f9f7b06a70805d57f690ed | 3,599,668 |
def mock_feed_metadata(anchore_db):
"""
Fixture for delivering mock feed and feed group metadata for metadata ops
:param anchore_db:
:return:
"""
feed_names = []
with session_scope() as db:
for f in mock_feeds:
feed_names.append(f['name'])
feed = FeedMetadata... | e62d730404bad7b685c729b88bcb04a318950c88 | 3,599,669 |
def custom_filter(image):
"""
Allows the user to modify the image by multiplying each of the RGB values of each pixel by their input number.
"""
red_constant = float(input ("Multiply the R value of each pixel by: "))
green_constant = float(input ("Multiply the G value of each pixel by: "))
blue... | c1a23f13f7d5cdf49b7c9a4c1b9a84fa4cb56051 | 3,599,670 |
def cart2pol(x, y, z=None):
"""Convert Cartesian coordinates to polar.
x: number or sequence
y: number or sequence
z: number or sequence (optional)
returns: theta, rho OR theta, rho, z
"""
x = np.asarray(x)
y = np.asarray(y)
rho = np.hypot(x, y)
theta = np.arctan2(y, x)
i... | d42c55cb86e23215fdb804832e2870e92fa1ed64 | 3,599,671 |
def mean_ecliptic_longitude(t='now'):
"""Returns the mean ecliptic longitude."""
T = julian_centuries(t)
result = 279.696680 + 36000.76892 * T + 0.0003025 * T ** 2
result = result * u.deg
return Longitude(result) | d0bf2ad13382e720f58d3871b05c5f5456331e05 | 3,599,672 |
def load_presets(lang):
"""Read presets files, set global presets variable and return dictionary with preset classes."""
global presets
class_dict = {}
for f in PRESETS_DIR.rglob("*.yaml"):
presets_yaml = read_yaml(f)
# Skip preset if it is not valid for lang
if lang:
... | 03e26390f3baae79074cfa479aaded4173965cc8 | 3,599,673 |
def _j(pp, n=100, intervals=10, dmin=0.0, dmax=None, d=None):
"""
J function: Ratio of hazard functions for F and G.
Parameters
----------
pp : :class:`.PointPattern`
Point Pattern instance.
n : int
Number of empty space points (random points).
int... | 1e76732b15dc2dd739fe2b70bfa15474d009f795 | 3,599,674 |
from typing import Optional
import torch
def random_rotation(
dtype: Optional[torch.dtype] = None, device=None, requires_grad=False
):
"""
Generate a single random 3x3 rotation matrix.
Args:
dtype: Type to return
device: Device of returned tensor. Default: if None,
uses th... | cd245691abf4afee7536c666be56e2882fc5effe | 3,599,675 |
import copy
def covModel1D_to_covModel3D(cov_model_1d):
"""
Converts a covariance model in 1D to a omni-directional covariance model in 3D.
:param cov_model_1d: (CovModel1D class) covariance model in 1D
:return cov_model_3d: (CovModel2D class) covariance model in 3D (omni-directional,
... | 2a3e7cecef957ce66d4d41b7f338471368f4ea80 | 3,599,676 |
def getKlauder(f,t,T=5.0):
"""
Retrieves a Klauder Wavelet with upper frequency f[0] and lower frequency f[1].
See: http://www.subsurfwiki.org/wiki/Ormsby_filter
"""
assert len(f) == 2, 'Klauder wavelet needs 2 frequencies as input'
k = np.diff(f)/T
f0 = np.sum(f)/2.0
wav = np.real(np.... | b87289cccd644e85703897230c259391b659253d | 3,599,677 |
def is_transaction_successful(money_inserted, cost_of_the_drink):
"""Returns True when the transaction is successful, or False if money inserted is insufficient."""
# Checking if money put in is enough to but the drink user requested.
if money_inserted >= cost_of_the_drink:
# Calculating change and ... | ef9bc584e8860e0c8f915967d6b207cdd16cfaff | 3,599,678 |
def _find_best_feature_split(X, y, max_features, split_score_function,
min_samples_split, min_samples_leaf,
split_threshold_mode, random_state):
"""
Finds the best single feature to split on and the split threshold to use.
Parameters
----------
... | 0a3a0ddaddc2a34622f2b472499b90a153fe7d00 | 3,599,679 |
def create_line_strip(point_list: PointList,
color: Color, line_width: float=1):
"""
Create a multi-point line to be rendered later. This works faster than draw_line because
the vertexes are only loaded to the graphics card once, rather than each frame.
:Example:
>>> import a... | 5b6eff4cec5f41a4b1fd5a8d1ebd07330f01b8b8 | 3,599,680 |
from re import U
from re import X
def run(space_step,
final_time,
generator="numpy",
sorder=None,
with_plot=True):
"""
Parameters
----------
space_step: double
spatial step
final_time: double
final time
generator: string
pylbm generato... | 93d2687f516304a4afce8ab56ce5ee0ce3079cb8 | 3,599,681 |
import json
def unpack_msrest_error(e):
"""Obtains full response text from an msrest error"""
op_err = None
try:
op_err = json.loads(e.response.text)
except (ValueError, TypeError):
op_err = e.response.text
if not op_err:
return str(e)
return op_err | f55b08443b0f97f967de837732159b82fd8b5a60 | 3,599,682 |
def get_thread_id(pid):
"""Read thread group id designated in /proc/<pid>/status.
"""
return proc_readlines(pid, 'status')[2][6:-1] | 5468a96e1896c8f848333c27deafa039370c99e2 | 3,599,683 |
def get_dependent_files(g, id):
"""returns the files which are dependent on the given symbol, lib, or file id"""
target_node = g.get_node(id)
if target_node is None:
return None
if target_node.type == dagger.graph_consts.NODE_LIB:
edge_type = dagger.graph_consts.FIL_LIB
elif target... | 9715b2583489cff8dc72dfe426d4ae19f6d7f822 | 3,599,684 |
import torch
def scale_torch(img):
"""
Scale the image and output it in torch.tensor.
:param img: input rgb is in shape [H, W, C], input depth/disp is in shape [H, W]
:param scale: the scale factor. float
:return: img. [C, H, W]
"""
if len(img.shape) == 2:
img = img[np.newaxis, :, ... | 84bbe39e43b48bdbefc8c39ba17e6c08f83cb6ca | 3,599,685 |
def map_file(topics_id, timespan_maps_id):
"""
The map files are actually stored on S3. We proxy this through out server, rather than directly making a call to
the S3 URL, in order to be flexible and to get the mimetype correct.
:param topics_id:
:param timespan_maps_id:
:return:
"""
as... | f7c70eaa2a9a313c8ed3981b45da430c92967d06 | 3,599,686 |
from datetime import datetime
def datetime_str_to_datetime(datetime_str):
"""
This converts the strings generated when matlab datetimes are written to a table to python datetime objects
"""
if len(datetime_str) == 24: # Check for milliseconds
return datetime.strptime(datetime_str, '%d-%b-%Y %H... | 84960880bccfb21bdb2dc1a15b0bd09ef358187c | 3,599,687 |
import torch
def batched_inference(models, embeddings,
rays, ts, N_samples, N_importance, use_disp,
chunk,
white_back,
**kwargs):
"""Do batched inference on rays using chunk."""
B = rays.shape[0]
results = defaultdict(... | baffc6e64e3cbe46c3a3372d5b577396c820c04d | 3,599,688 |
def GenerateId_Hex(hash_sha512, input_file):
"""
Implement asset id of input file for hex format (with ':' delimiter)
@param hash_sha512: string to encode
@param input_file: input file to encode
"""
string_id = _as_hex_str(hash_sha512, ':')
return string_id | f9fa7fbc669131f6ce0405abce885c9521ed4671 | 3,599,689 |
from numpy.core import isfinite
import types
def gisfinite(x):
"""like isfinite, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isfinite and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This fu... | 022fd88387aa701c5acd90bff788a1015d8dcf5e | 3,599,690 |
from typing import List
import re
def get_banner_ids(logfile: str = None) -> List[str]:
"""Gets all banner ids from a log file.
You need to open the details of all banners for this to work.
:param logfile: A path to a logfile
"""
log = _read_logfile(logfile)
ids = re.findall(r"OnGetWebViewPag... | 1b6fd7c9782285caa785c8c26cc76b5a09ee4288 | 3,599,692 |
def downcast_variables_dataframe(df):
"""
Method to downcast the variables in a DataFrame
Parameters
----------
df : pd.DataFrame
DataFrame to downcast
Returns
-------
pd.DataFrame
"""
df_downy = df.copy()
# Downcast dataset
df_downy[df_downy.select_dtypes(inclu... | 0aa3a6d1abead5051f9ee5a7cff88dc6f4f8b2e0 | 3,599,693 |
import threading
import functools
def mutex(func): # type: (TCallable) -> TCallable
"""Enforce exclusive access on a decorated function."""
lock = threading.Lock()
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper around `func` which uses a lock to provide exclusive access to t... | d8ee1902a397cc2f200f3cd64f5015f2e85b5dca | 3,599,694 |
def mangle(prefix, name):
"""Make a unique identifier from the prefix and the name. The name
is allowed to start with $."""
if name.startswith('$'):
return '%sinternal_%s' % (prefix, name[1:])
else:
return '%s_%s' % (prefix, name) | 6d949e61a87c6667fdfb262376e476aea64bde4b | 3,599,695 |
def replay_entry(plugin, item_id, **kwargs):
"""
First executed function after replay_bridge
"""
return list_root(plugin, item_id) | 894b6941571de82ab6ce4cb0daad4871062835b0 | 3,599,696 |
def de_normalize_minmax(x_scale, x, min_r, max_r):
""" Transforms a min-max normalized and
scaled vector back to its un-normalized
form.
"""
x_t = [((i - min_r)/(max_r - min_r)) for i in x_scale]
x_inv = [(i*(max(x) - min(x)) + min(x)) for i in x_t]
return x_inv | d1a2bd2740552eae2c4bc0b94f2093de7ed03b70 | 3,599,697 |
def app():
"""Flask application fixture."""
app = flask.Flask(__name__)
return app | 27300632fb18315529cd199b2771a7441baae9d4 | 3,599,698 |
import torch
def update_ntk_inv(ntk, ntk_inv, keep_indices):
""" A little bit faster implementation. Uses the fact that ntk is a symmetric matrix. """
S = set(keep_indices)
remove_indices = [i for i in range(ntk.shape[0]) if i not in S]
A12 = ntk[keep_indices][:, remove_indices]
A22 = ntk[remove_... | 26b62e0c1bca79643930ee822f34cfdd74e977fd | 3,599,699 |
def pseudo_rev(t, kf, kb, prod, major, minor, backend=None):
"""Analytic product transient of a reversible pseudo first order reaction.
Product concentration vs time from pseudo-first order reversible kinetics.
Parameters
----------
t : float, Symbol or array_like
Time.
kf : number or ... | 2e1b7091fcec3fc0517445ababe0f60cbe1c7677 | 3,599,700 |
def to_acc_pubkey(data: ValPubKey) -> AccPubKey:
"""Converts a validator pubkey into an account pubkey.
Args:
data (ValPubKey): validator pubkey
Raises:
ValueError: if provided string is not Bech32
Returns:
AccPubKey: account pubkey
"""
vals = bech32_decode(data)
i... | f991c7e02b38c08bb71f32ebebe9d61be8e5831b | 3,599,701 |
import base64
import binascii
def get_basic_authorization(headers: dict) -> tuple[str, str]:
"""
Extracts the authentication credentials from a Basic authentication scheme.
:param headers: Dictionary of the headers.
:type headers: dict
:return: Authentication credentials.
:rtype: tuple[str, ... | f83b4799d18dc545264d447b338f37c4f1c21dbe | 3,599,704 |
def is_in_system(system: Orbiter, target_name: str) -> bool:
"""Return true if there is a space object with the target name anywhere in the parm system."""
# We found the target name in the system!
if system.name == target_name:
return True
# If the names don't match, and no orbiters, then the... | d0f166de19067338f3654d10fedd7c2cf3174a30 | 3,599,705 |
def get_successful_move_actions(actions: DataFrame[SPADLSchema]) -> DataFrame[SPADLSchema]:
"""Get all successful ball-progressing actions.
These include successful passes, dribbles and crosses.
Parameters
----------
actions : pd.DataFrame
Actions, in SPADL format.
Returns
-------... | 692f550967202e56ebaf2075e40bbec8188a8273 | 3,599,706 |
def obtener_cantidad_turistas_y_ciudades_origen_en_ciudad_en_rango_anios(PaisDestino, AnioInicio, AnioFin): #OK
"""
Dado un pais y un rango de años obtiene la cantidad total de personas que llegan a esa ciudad separando por años, paises y ciudades de origen
Dado un pais, una ciudad, un mes y un rango de año... | 0e08bec08437a0b9c0862aa620547bc59071f35e | 3,599,707 |
import logging
def evaluate(*, p_eval_step, params, eval_ds: tf.data.Dataset,
num_eval_steps: int):
"""Evaluate the params an return a dictionary with the metrics."""
logging.info("Gathering evaluation metrics.")
eval_metrics = []
eval_iter = iter(eval_ds) # pytype: disable=wrong-arg-types
for... | 1da62df7af3c8c44408d78a1d7de05a6b8e046c8 | 3,599,708 |
import glob
def dse_build_design_space(max_partition_num):
# type: (int) -> int
"""
Build and partition the design space
Return the partition number
"""
if SINGLE_PARTITION:
max_partition_num = 1
builder_py = must_use_pyc('{0}/optimizers/'.format(MERLIN_COMPILER_HOME) +
... | 9424695e8c298f9ab515fb0e765e9803b7c7db7b | 3,599,709 |
def fastprint(text, show_prefix=False, end="", flush=True):
"""
Print ``text`` immediately, without any prefix or line ending.
This function is simply an alias of `~fabric.utils.puts` with different
default argument values, such that the ``text`` is printed without any
embellishment and immediately... | 4d28eb647651fc1b936726c15b7356e370e32561 | 3,599,710 |
def find_strongest_common_ancestor(els):
"""
Return the deepest common ancestor of all elements, provided that
at least 2/3 of the elements have this ancestor.
>>> import lxml.html
>>> doc = lxml.html.fromstring('<table><tbody><tr><td>A</td><td>B</td></tr></tbody></table>')
>>> find_strongest_c... | 6fe8d88d3989b8494fefb3881ad6e3ab74f05119 | 3,599,711 |
def make_shell_context():
"""
Creates a python REPL with several default imports
in the context of the app
"""
return dict(app=app) | 2d1b22b2447846694236ddc8ac41363377a25e3c | 3,599,712 |
def glyph2vertices(glyph, n_segments=5):
"""
Sample glyph outline vertices checking points on the curve and control points for conic and cubic bezier arcs as
described in: https://www.freetype.org/freetype2/docs/glyphs/glyphs-6.html
Vertex coordinates are scaled such that the vertical advance is 1 unit... | 660998f75b1fffcb11ba158407af321aa7aaf452 | 3,599,713 |
def calc_prefix_color(*args):
"""
calc_prefix_color(ea) -> color_t
Get prefix color for line at 'ea'
@param ea (C++: ea_t)
@return: Line prefix colors
"""
return _ida_lines.calc_prefix_color(*args) | 1ec3bd3ed96c2b8b1e46090cfb3c6786595b53d1 | 3,599,714 |
import torch
def get_col_mins_efficient(X, Y, b):
"""
Computes the l2 distance to the closest x or each y.
:param X: (n1, d) tensor
:param Y: (n2, d) tensor
Returns n1 long array of L2 distances
"""
mins = torch.zeros(Y.shape[0], dtype=X.dtype, device=X.device)
n_batches = len(X) // ... | af3382009edb39ec00cd75ce67cbc6395d5eb861 | 3,599,715 |
def open_create_obj_modal(obj_type):
"""Opens create object modal for selected type."""
selenium_utils.open_url(url.dashboard())
obj_modal = dashboard.Dashboard().open_create_obj_modal(obj_type=obj_type)
return obj_modal | 7a9a345b3068f994d4082b5db38fa8f6f4b8bed2 | 3,599,716 |
def time_to_sec(time_str: str) -> int:
"""Convert time in string format to seconds.
Skipping seconds since sometimes the last column is truncated
for entries where >10 days.
"""
total_sec = 0
if '-' in time_str:
# parse out days
days, time_str = time_str.split('-')
total... | e08667cc35a3d85dc30ea3eb63e5d91f2ba99252 | 3,599,718 |
def get_coordinates(label):
""" given a label returns the coordinates associated with that label/region.
The coordinates are precomputed from training points. The coordinate of a label equals to the median
latitude and longitude of all training points in that region.
Args:
label (int): label or region id associ... | 80fc0e45b8096d7c48e70cf32ef6dcc3eb33d0da | 3,599,719 |
import functools
def mobilized(normal_fn):
"""
Replace a view function with a normal and mobile view.
For example::
def view():
...
@mobilized(view)
def view():
...
The second function is the mobile version of view. The original
function is over... | c7e23f233e10ddeabaca083367a99bd6d5bfc7bf | 3,599,720 |
def init_layers_mf(Y, Z, kernels, num_outputs=None, Layer=SVGP_Layer):
"""
Creates layer objects from initial data
:param Y: Numpy array of training targets
:param Z: List of numpy arrays of inducing point locations for each layer
:param kernels: List of kernels for each layer
:param num_output... | c2936de4b9517912aa8a6afb2b0b4aec8f09cfaa | 3,599,721 |
def procrustes(X, Y, scaling=True, reflection='best'):
"""
This function is taken from here:
https://stackoverflow.com/a/18927641.
It aligns a shape defined by Y to a shape defined by X.
# Y_transformed = b * YT + c
Procrustes analysis determines a linear transformation (translation,
refle... | 3324bf9487c747cfffa004d1b95bd7a9ec4cdb90 | 3,599,722 |
def perform_cva(ds, base_times=None, comp_times=None, reduce_comp=False,
vege_var='tcg', soil_var='tcb', tmf=2):
"""
Takes a xarray dataset/array of tasselled cap greeness and brightness
values, as well as a a tuple of base years (e.g. 1990, 2010) that are
averaged together to form a ba... | c6cb565f25c26d72ff1a0fd6f13838e93540246c | 3,599,723 |
from typing import Optional
def get_event_invoke_config(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEventInvokeConfigResult:
"""
Resource Type definition for AWS::Lambda::EventInvokeConfig
"""
__args__ = dict()
__args__['id'] = ... | df7e0ed209aa8991eabfbdd63dfe3fd85dc2e2b8 | 3,599,724 |
def deco1(func):
"""docstring for deco1"""
@wraps(func)
def wrapper():
return func()
return wrapper | 33fa3c8354f64a9d9430e82623bdb5b8c3f84fde | 3,599,725 |
def keras_mxnet_symbol(func):
"""Decorator function used with all Keras API implementation. This
decorator helps to establish the symbolic graph for the result MXNet symbol
generated in the operator function.
# Arguments
func: Decorated function reference.
"""
@wraps(func)
def func... | 19bbbce3e620daa713d1946a0375f9488a185658 | 3,599,726 |
def extract_names(filename):
"""
Given a file name for baby.html, returns a list starting with the year string
followed by the name-rank strings in alphabetical order.
['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]
"""
# +++your code here+++
with open(filename, "r") as f:
fi... | 8a00e099b7da57f409f04a9f2f723dca0002818b | 3,599,728 |
import urllib
import requests
def gas(bot, trigger):
"""Fetches gas prices for provided query/location."""
query = trigger.group(2)
if not query:
return bot.reply("You need to give me a location!")
quoted_query = urllib.parse.quote_plus(query)
try:
url = SEARCH_ENDPOINT.format(q... | 97cc8d29af99ff88f561eea594bc8bda052e6f6b | 3,599,729 |
def hhmm_to_seconds(hhmm: str) -> int:
"""
Converts hours and minutes into seconds.
Arguments:
hhmm: The time in hh:mm format.
Returns:
If the argument is a valid format it returns the time in seconds.
"""
if len(hhmm.split(':')) != 2:
print('Incorrect format. Argument must be ... | 656b21241ce9c79ebb75fc9c20f09d781f70cd0f | 3,599,730 |
def get_string_value(value_format, vo):
"""Return a string from a value or object dictionary based on the value format."""
if "value" in vo:
return vo["value"]
elif value_format == "label":
# Label or CURIE (when no label)
return vo.get("label") or vo["id"]
elif value_format == "... | 0efaa0850a63076dd0334bc54f2c96e4f352d6ae | 3,599,731 |
def create_msearch_payload(host, st, mx=1):
"""
Create an M-SEARCH packet using the given parameters.
Returns a bytes object containing a valid M-SEARCH request.
:param host: The address (IP + port) that the M-SEARCH will be sent to. This is usually a multicast address.
:type host: str
:param ... | cb0da629716e992dd35a5b211f26cae3ad949dcb | 3,599,732 |
def ustrip(text):
"""Strip Unicode extended whitespace from a string."""
return text.strip(unicode_extended_whitespace) | 4af1f734e9d73523f304d56630fc26ac8c5649e7 | 3,599,733 |
from pathlib import Path
def valid_folder(path_):
"""
Returns True if path_.match any of the conditions. False otherwise.
conditions assigned:
- "_*"
"""
# ignores dunders, __pycache__
conditions = (
"_*",
)
p = Path(path_)
return not(any(p.m... | a0ddff2667eea34d7b00e3aac8623e65140894f9 | 3,599,734 |
def _balance(target, weight):
"""Assume `cross_entropy(ignore_index=-100)`.
Args:
target (Tensor[H, W]): input tensor.
weight (Tensor[H, W]): probability of BG.
"""
negative_mask = target.eq(0)
limit = 3 + 3 * target.gt(0).sum().item()
if negative_mask.sum().item() > limit:
... | fd59351331319d10b89f70ef816fb9f922e61046 | 3,599,735 |
def newgpg(ui, **opts):
"""create a new gpg instance"""
gpgpath = ui.config("gpg", "cmd")
gpgkey = opts.get(r'key')
if not gpgkey:
gpgkey = ui.config("gpg", "key")
return gpg(gpgpath, gpgkey) | 43f5d58f994d6de635f47817dc7212c541952af5 | 3,599,736 |
import requests
from bs4 import BeautifulSoup
def get_google_image_link(word):
"""
Function returns a url for the movie image in google search resoults
Returns second image as first is a search_url
:param word: search word
:return: url
"""
url = 'https://www.google.com/search?q=' + word + ... | 54b7e4626d0825dee6baaecc6a41ddb14c384797 | 3,599,737 |
def get_values_from_line(line):
"""Get values of an observation as a list from string,
splitted by semicolons.
Note 1: Ignore ';' inside \"...\". E.g. consider \"xxx;yyy\" as one value.
Note 2: Null string '' for NA values.
"""
raw_list = line.strip().split(';')
i = 0
values = []
whi... | 585c6c9484f6ad145f7265613dc189351cc2d556 | 3,599,738 |
import httpx
import json
async def download_github_issue(
client: httpx.AsyncClient,
owner: str,
repo: str,
issue_number: int,
) -> Maybe[GithubIssueRaw]:
"""
Download a single file from its identifier.
- Returns `SimpleError` if the issue was not found
- Returns a `GithubIssueRaw` ot... | 1fc0984b551392db17b4f7f666603e5b4d6fc03b | 3,599,739 |
import inspect
def burst(nbursts=2):
"""Wait `nbursts` calls before calling the wrapped function with a list of
accumulated arguments.
Note: the return value of the wrapped function will be None when it's not
actually called, i.e. in between bursts.
Can be applied to a function and a method.
... | f78a037afe97f987fab463506141424ef6509e19 | 3,599,740 |
def load_model(detector_path, classifier_path, gpu, num_classes):
"""Load model."""
detector = Res18UnetCenterNet()
chainer.serializers.load_npz(
detector_path,
detector
)
classifier = MobileNetV3(out_ch=num_classes)
chainer.serializers.load_npz(
classifier_path,
... | b8d7630a6fbd78d1ebf8999405811df0ee434037 | 3,599,741 |
def ask_string(question, default=''):
"""Ask the user to enter something.
Example:
>>> ask_string("What's your name?", default='No Bo Dy') # doctest: +SKIP
:: What's your name? (Default: No Bo Dy)
> Odysseus
You chose: Odysseus
'Odysseus'
"""
... | 1c93db4fbc19320933323c51870e621084920e7b | 3,599,743 |
def np_mat_to_rot6d(np_mat):
""" Get 6D rotation representation for rotation matrix.
Implementation base on
https://arxiv.org/abs/1812.07035
[Inputs]
flattened rotation matrix (last dimension is 9)
[Returns]
6D rotation representation (last dimension is 6)... | a7b7b00667803096242d41af6971f1fce2ff27b5 | 3,599,744 |
def oauth_callback():
"""Callback for OAuth1a authorization."""
# Get verifier from GET arguments
oauth_verifier = request.args.get('oauth_verifier', None)
if oauth_verifier is None:
abort(400, 'oauth_verifier arguments are missing.')
# Request access token and token secret
args = [OAU... | 561d6c9e7950c97b98378bcb8a6ccc8bad5c2791 | 3,599,745 |
def grib_get(gribid,key, ktype=None):
"""
@brief Get the value of a key in a grib message.
The type of value returned depends on the native type of the requested key.
The type of value returned can be forced by using the type argument of the
function. The type argument can be int, float or str.
... | 4acd8bfaab72e51942b85c2e8feb0500c17ce43d | 3,599,746 |
from summit_core import voc_dir as rundir
from summit_core import core_dir, Plot, Config
from summit_core import connect_to_db, TempDir, create_daily_ticks, add_or_ignore_plot
from summit_voc import Base, GcRun, summit_voc_plot, get_dates_peak_info
from datetime import datetime
import datetime as dt
from summit_voc imp... | 264aad030ff630f4d2c0e737497b0b1723f4622c | 3,599,747 |
def comparehits_bin_min(image_bin,featureimage_bin,max_sum=10,startx = 0 ,endx = 0,move_px = 1):
"""
查找特征图像出现的位置
要求传入二值化图像
返回 出现位置的起始位置 和 差异
"""
find_list = []
h, w = image_bin.shape[:2]
h_f, w_f = featureimage_bin.shape[:2]
bc_min = max_sum
start_px = -1
if endx==0 : endx... | 53233fc1d8bc36f6e9b121b9bc29d11380cbff57 | 3,599,749 |
import torch
def map2central(cell, coordinates, pbc):
"""Map atoms outside the unit cell into the cell using PBC.
Arguments:
cell (:class:`torch.Tensor`): tensor of shape (3, 3) of the three
vectors defining unit cell:
.. code-block:: python
tensor([[x1, y1, ... | 5ab75804efa182516ec4e99ec6707e65f205b842 | 3,599,750 |
def get_left_strip(chonk):
"""
Compute the left vertical strip of a 2D list.
"""
return [chonk[_i][0] for _i in range(len(chonk))] | dfc57a0776e5ab97a808a75170634fa6a072d9d3 | 3,599,752 |
def capture(sync_fn, *args, **kwargs):
"""Run ``sync_fn(*args, **kwargs)`` and capture the result.
Returns:
Either a :class:`Value` or :class:`Error` as appropriate.
"""
try:
return Value(sync_fn(*args, **kwargs))
except BaseException as exc:
return Error(exc) | cf8432521f19bcea5c1d51191c020cbdc3abc0c2 | 3,599,753 |
def filter_waveforms(stream,f1,f2):
"""
Bandpass filter waveforms
INPUTS
stream - list of obspy streams, one for each station/channel combo, each 60 s long
f1 - lower bandpass limit in Hz
f2 - upper bandpass limit in Hz
OUTPUTS
stream - same list of streams, but filtered
""... | 6a563a987e50d668a164c7020449dd2ce5cf28a8 | 3,599,754 |
def is_lambda_decorator(tree, fname=None):
"""Test tree whether it decorates a lambda with ``fname``.
A node is detected as a lambda decorator if it is a ``Call`` that supplies
exactly one positional argument, and its ``.func`` is the decorator ``fname``
(``is_decorator(tree.func, fname)`` returns ``Tr... | 1e5f8bf07fc7f6b935db0bdb73244277e80580ac | 3,599,755 |
def enter_outfit_details():
"""Generate a random outfit."""
activities = ["urban hike", "dinner", "brunch", "workout", "concert", "girls night out",
"hiking", "casual date", "stay at home", "beach", "picnic", "date night", "pool"]
select_string = "<select name='activity'><option value='... | 8cfdf1bbeea2480fda2ed66192eb5eebb4a2d261 | 3,599,756 |
def project_world_to_camera(P,X):
"""
P: projection matrix
X: 3D-world points as 3D vectors (not homegeneous)
output: 2D camera/image points
"""
X_w = np.concatenate((X,np.ones((1,X.shape[1]))),axis=0) # homogeneous coords
X_c = np.dot(P, X_w)
X_c /= X_c[2,:] # divided by the third row... | 622cd26aa05693aa4ce0791cb2ea6565a4370774 | 3,599,757 |
import logging
def load_regmap(fp):
""" Returns a panda DataFrame with the register and bitfield definition """
if exists(fp):
df = pd.read_csv(fp, encoding="utf-8")
else:
log_msg = f"regmap path {fp} does not exist"
logging.error(log_msg)
raise Exception(log_msg)
df[R... | bf1761e76ca07e6f38bf02f8922f86ab3d52b9fb | 3,599,758 |
def gradient_table_from_bvals_bvecs(bvals, bvecs, b0_threshold=0, atol=1e-2,
**kwargs):
"""Creates a GradientTable from a bvals array and a bvecs array
Parameters
----------
bvals : array_like (N,)
The b-value, or magnitude, of each gradient direction.
bvec... | 616e61691212a8c0fc88f3031dd94468287b7386 | 3,599,759 |
def _shift_num_right_by(num: int, digits: int) -> int:
"""Shift a number to the right by discarding some digits
We actually use string conversion here since division can provide
wrong results due to precision errors for very big numbers. e.g.:
6150000000000000000000000000000000000000000000000 // 1e27
... | ba459cb419ef19ac2884d8299d4f1a9213832fa3 | 3,599,760 |
import json
def js2str(js, sort_keys=True, indent=4):
"""Encode js to nicely formatted human readable string. (utf-8 encoding)
Usage::
>>> from weatherlab.lib.dataIO.js import js2str
>>> s = js2str({"a": 1, "b": 2})
>>> print(s)
{
"a": 1,
"b": 2
... | 17fac42012b5abae77a00083e183d851baaab5b3 | 3,599,761 |
import torch
def accuracy(output, target, topk=(1,)):
"""
Computes the accuracy over the k top predictions for the specified values of k
Args
output: logits or probs (num of batch, num of classes)
target: (num of batch, 1) or (num of batch, )
topk: list of returned k
... | 4d9e9d5452feb8a35eb3f409b3d74a981222514d | 3,599,762 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.