content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def json_serialize(item):
"""
A function similar to L{dumps}.
"""
def helper(unknown):
if isinstance(unknown, PlatedElement):
return unknown._asJSON()
else:
raise TypeError("{input} not JSON serializable"
.format(input=unknown))
ret... | 00ea0aa060eaf2335148402770eba173592e1a65 | 25,764 |
def get_sop_instance_uid(dicom):
"""
Return the SOP Instance UID.
Args:
dicom: pydicom Dataset
"""
return dicom.SOPInstanceUID | 18991a81be2e143aecaf59bdf52e51ab2f9a621b | 25,765 |
def remove_filter():
"""
Removes a filter from the process
Returns
-------------
dictio
Success, or not
"""
# reads the session
session = request.args.get('session', type=str)
# reads the requested process name
process = request.args.get('process', default='receipt', typ... | 887c985694fd11e5adeff23e001d9b94f7879ff5 | 25,766 |
def flag_data(vis_windows, flag_windows):
""" Returns flag_windows untouched """
def _flag_data(vis_windows, flag_windows):
return flag_windows
return da.blockwise(_flag_data, _WINDOW_SCHEMA,
vis_windows, _WINDOW_SCHEMA,
flag_windows, _WINDOW_SCHEMA,... | 55f3df8fa6ca30de2cd6c9bac5f55eb4fff0eb36 | 25,767 |
def preprocess_static_feature(
static_feature_dict,
imputation_strategy="median",
standardize=False
):
"""Preprocessing for a dictionary of static features.
Args:
static_feature_dict: Dictionary of float values.
imputation_strategy: "median" or "mean" or "most_frequent" imputation.
standard... | a2bfbfc21afcd1ab03f86f82e72fff480746542e | 25,768 |
from typing import List
def from_emso(platform_code: str, parameters: List[str]=[], start_time: str='',
end_time: str='', depth_min: float=None, depth_max: float=None,
user: str='', password: str='', size: int=10, token: str=''
) -> WaterFrame:
"""
Get a WaterFrame wi... | d8ac4520a3364e92d5e52768e12211989cdc876b | 25,770 |
def _get_all_pivots(Ao, number_of_subsamples):
"""
A dummy case where we return all the subsamples.
"""
return np.arange(1, len(number_of_subsamples)) | 886a32ac34f0eb3acafa15917258e87b68b7323c | 25,771 |
def clang_find_var(tu, name, ts, namespace=None, filename=None, onlyin=None):
"""Find the node for a given var."""
assert isinstance(name, basestring)
kinds = CursorKind.ENUM_DECL,
decls = clang_find_decls(tu, name, kinds=kinds, onlyin=onlyin, namespace=namespace)
decls = list(set(c.get_definition()... | cacdf6426353f99ed66f051c7d118706dc76f134 | 25,772 |
def ShouldRunOnInternalIpAddress(sending_vm, receiving_vm):
"""Returns whether a test should be run on an instance's internal IP.
Based on the command line flag --ip_addresses. Internal IP addresses are used
when:
* --ip_addresses=BOTH or --ip-addresses=INTERNAL
* --ip_addresses=REACHABLE and 'sending_vm' c... | 961fc7343d6c3712d62fd1897f5897c49f6ec66d | 25,773 |
def shn_get_crud_string(tablename, name):
""" Get the CRUD strings for a table """
crud_strings = s3.crud_strings.get(tablename, s3.crud_strings)
not_found = s3.crud_strings.get(name, None)
return crud_strings.get(name, not_found) | 106aba2b964b43d0afec45fa09cb68798bcc6a11 | 25,774 |
def default_invalid_token_callback(error_string):
"""
By default, if an invalid token attempts to access a protected endpoint, we
return the error string for why it is not valid with a 422 status code
:param error_string: String indicating why the token is invalid
"""
return jsonify({config.err... | 70674a70a7b35838b154d2405e991c2653d02d8a | 25,775 |
def bf_generate_dataplane(snapshot=None, extra_args=None):
# type: (Optional[str], Optional[Dict[str, Any]]) -> str
"""Generates the data plane for the supplied snapshot. If no snapshot argument is given, uses the last snapshot initialized."""
return bf_session.generate_dataplane(snapshot=snapshot, extra_ar... | 4134208bfef878e38f0428f8e8d830a7cc7b9377 | 25,776 |
def k_correction_pl(redshift, a_nu):
"""Calculate the k-correction for a power law spectrum with spectral
index (per frequency) a_nu.
:param redshift: Cosmological redshift of the source
:type redshift: float
:param a_nu: Power law index (per frequency)
:type a_nu: float
:return: K-correcti... | e8fb84f3b98f49d4f1bb904eee61916f4a4bc3de | 25,777 |
def make_points_image(pts, mask, radius=5):
"""
Create label image from physical space points
Creates spherical points in the coordinate space of the target image based
on the n-dimensional matrix of points that the user supplies. The image
defines the dimensionality of the data so if the input ima... | dfb94ca6a80e315571c53c1c4b5377f35eec771c | 25,778 |
def map_replacements():
""" create a map of what resources are replaced by others. This is a tree. """
isreplacedby = {} # isreplacedby[x] is the number of things that are replaced by x
replaces = {} # replaces[x] are the number of things that x replaces.
for r in BaseResource.objects.all():
i... | faf4e63bd902325d9c0563e60db0bb1348ed3e38 | 25,779 |
def order_basemaps(key, out):
"""check the apy key and then order the basemap to update the select list"""
# checking the key validity
validate_key(key, out)
out.add_msg(cm.planet.mosaic.load)
# autheticate to planet
planet.client = api.ClientV1(api_key=planet.key)
# get the basemap name... | 491296f3231e093817119cd4ed72f2c90b2e02d8 | 25,780 |
def compute_iou(box1, box2, yxyx=False):
"""Calculates the intersection of union between box1 and box2.
Args:
box1: a `Tensor` whose shape is [..., 4] and represents the coordinates of
boxes in x_center, y_center, width, height.
box2: a `Tensor` whose shape is [..., 4] and represents the coordinates ... | 47c9f9d6a10cc35984640c177ff49d637cf9a656 | 25,782 |
from typing import Union
import warnings
def ensure_pyspark_df(spark_session: SparkSession, df: Union[pandasDF, sparkDF]):
"""Method for checking dataframe type for each onData() call from a RunBuilder."""
if not isinstance(df, sparkDF):
warnings.warn(
"WARNING: You passed in a Pandas DF, ... | 0662665f93791640fed18d2615563e71d0abe1c3 | 25,783 |
from datetime import datetime
def roundTime(dt=None, roundTo=60):
"""
Round a datetime object to any time lapse in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
Example... | 0c949a0c69e2a9db38cff6e83b299d022b095ad3 | 25,784 |
def sample_recipe(user, **params):
"""Create and return a sample recipe"""
recipe_defaults = {
'title': 'simple ricepi shot',
'time_minutes': 10,
'price': 5.0
}
recipe_defaults.update(params)
return Recipe.objects.create(user=user, **recipe_defaults) | 8142b277f193ad76d3bb6d287963c6699001c636 | 25,785 |
def read_nitf_offsets(filename):
"""Read NITF fields relevant to parsing SICD
SICD (versions 0.3 and above) is stored in a NITF container. NITF is a
complicated format that involves lots of fields and configurations
possibilities. Fortunately, SICD only really uses a small, specific
portion of the... | e2e8bb3ee6b32cf8964b1c13b4e8584cc7fd9917 | 25,786 |
from datetime import datetime
def dttime(ts):
"""
将DataTime对象转换为unix时间
:param ts: unix时间
:type ts: float
:returns: datetime.datetime 对象
:rtype: datetime.datetime
"""
return datetime.datetime.fromtimestamp(ts) | 7a3691df61f7fad641445b7b84ea88ae39f6dbb9 | 25,787 |
import copy
def split_import(sc, node, alias_to_remove):
"""Split an import node by moving the given imported alias into a new import.
Arguments:
sc: (scope.Scope) Scope computed on whole tree of the code being modified.
node: (ast.Import|ast.ImportFrom) An import node to split.
alias_to_remove: (ast... | e83f2af8af108f3512e539ab50a8e264ccceb24f | 25,788 |
def load_trace(path):
"""Load the trace located in path.
Args:
path (string): Path to the LTTng trace folder.
Returns:
babeltrace.TraceCollection: a collection of one trace.
"""
trace_collection = bt.TraceCollection()
trace_collection.add_trace(path, 'ctf')
return trace_col... | eed21b6d3ac62104e9661c26cd6d996768562e89 | 25,789 |
def get_repo_paths(config_file_path):
"""
Get a list of repository paths.
Arguments:
config_file_path (str): Path the to config file.
Raises:
(ConfigFileError): Raised if there was an error opening, reading or parsding through the config file.
Returns:
(list<str>): A list ... | 2b79d55d83a40689206213097c1ddb8ed3535e69 | 25,790 |
async def get_bosswins_rank(conn : asyncpg.Connection, user_id : int) -> int:
"""Returns the rank in bosswins for the player given"""
psql = """
WITH ranks AS (
SELECT ROW_NUMBER() OVER (ORDER BY bosswins DESC) AS rank,
user_id, user_name, bosswins
... | f87746fd3e77b6e41922bc9efbe2e9a2fead8b09 | 25,791 |
def detect_objects_yolo(imgs, tensors):
"""This function makes use of multiprocessing to make predictions on batch.
Parameters
----------
imgs : list-like of images
tensors : dict
Contains tensors needed for making predictions.
Returns
-------
boxes: tuple
Tuple of leng... | 41a511e2fea6cb5abe449f995245ba3a76ae38f2 | 25,792 |
def append_id(endpoint, _id):
"""
append '_id' to endpoint if provided
"""
if _id is not None:
return '/'.join([endpoint.rstrip('/'), _id])
return endpoint | 60586a70bc8b9c9b10c1d54f6810c4528c5c0dec | 25,793 |
import time
import statistics
def records() -> dict:
""" Displays TJ's all time bests. """
records = cube.load_file("records")
times, people = records["records"], records["people"]
refresh = False
if "wca_token" in flask.session and "ion_token" in flask.session:
me = cube.api_call("wca", "... | c711634dcd7e06de481fc169d538b03735396cf0 | 25,794 |
import re
def get_info_media(title: str, ydl_opts=None, search_engine=None, result_count=1):
"""
:param title:
:param ydl_opts:
:param search_engine:
:param result_count:
:return:
"""
if ydl_opts is None:
ydl_opts = {
# 'format': 'best[ext!=wav]/best',
... | 03f8be75da183a818961e4fa2c08ac554dac5841 | 25,795 |
def export_post(request, style, format=-1):
"""
:param request:
:param style:
:param format:
:return:
"""
try:
payload = request.get_json(force=True) # post data in json
except:
payload = dict(request.form) # post data in form encoding
if not payload:
retu... | 7d26bffd25c7557453906ba9438b893bc957223f | 25,796 |
def unpack_literal_map_to_sdk_object(literal_map, type_map=None):
"""
:param lytekit.models.literals.LiteralMap literal_map:
:param dict[Text, flytekit.common.types.base_sdk_types.FlyteSdkType] type_map: Type map directing unpacking.
:rtype: dict[Text, T]
"""
type_map = type_map or {}
return... | 1c5de0c99d7e43c0012bdc0ce97c549e0888f4be | 25,797 |
import requests
def get_data(user:str,num_last:int)->int:
"""获取关注者数数据,输出数据增量并返回数据;重试3次,全部失败则返回False"""
# error=None
global proxies
for i in range(3):
try:
num_this=requests.get('https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names='+user,proxies=proxies,timeout=(10,30)).json()[0]['fo... | c72a8b4272e7432cfa81ace7344dba469082bcdd | 25,798 |
def _init_basemap(border_colour):
"""Initializes basemap.
:param border_colour: Colour (in any format accepted by matplotlib) of
political borders.
:return: narr_row_limits: length-2 numpy array of (min, max) NARR rows to
plot.
:return: narr_column_limits: length-2 numpy array of (min, ... | aeec84f7973972abd93bc344fc7f2028d216c4b5 | 25,800 |
def makeFigure():
"""Get a list of the axis objects and create a figure"""
ax, f = getSetup((9, 12), (5, 2))
cellTarget = "Treg"
epitopesDF = pd.DataFrame(columns={"Classifier", "Epitope"})
posCorrs1, negCorrs = CITE_RIDGE(ax[4], cellTarget)
for x in posCorrs1:
epitopesDF = epitopesDF.a... | e0c4cf34630171e489f195d14a3d29f8d0fa10e1 | 25,801 |
def get_data_frame(binary_tables, all_inputs):
"""
Gets a data frame that needs QM reduction and further logic.
Also removes the all_inputs from the DataFrame.
:param binary_tables: contains a tables with True and False outputs.
:param all_inputs: columns
:return: Pandas DataFrame.
"""
... | e40a914f19242ee82cd0c3e0f706f97f6c71e9fa | 25,802 |
def compute_shift_delay_samples(params_delays,vector_seconds_ref,freq_sample,seconds_frame,pair_st_so,data_type=0,\
front_time=None,cache_rates=[],cache_delays=[]):
"""
Compute number of samples to shift signal (always positive since reference station is closest to source).
... | 5cf35bd1b2187d107f8fd5809dd7db9822d5c110 | 25,803 |
from typing import Dict
from typing import Tuple
def classification_metrics_function(
logits: jnp.ndarray,
batch: base_model.Batch,
target_is_onehot: bool = False,
metrics: base_model.MetricNormalizerFnDict = _CLASSIFICATION_METRICS,
) -> Dict[str, Tuple[float, int]]:
"""Calculates metrics for the c... | defcde9e70822721a866a5af62c472386251b0e8 | 25,804 |
def get_host_finding_vulnerabilities_hr(vulnerabilities):
"""
Prepare human readable json for "risksense-get-host-finding-detail" command.
Including vulnerabilities details.
:param vulnerabilities: vulnerabilities details from response.
:return: list of dict
"""
vulnerabilities_list = [{
... | 8f0689441f2fef41bbd5da91c802dfb8baa2b979 | 25,806 |
from typing import Optional
from typing import List
import copy
def train_on_file_dataset(
train_dataset_path: str,
valid_dataset_path: Optional[str],
feature_ids: List[str],
label_id: str,
weight_id: Optional[str],
model_id: str,
learner: str,
task: Optional[TaskType] = Task.CLASSIFIC... | 16e692adc9e72d06678680e13ef50636e6f17450 | 25,807 |
def db_fixture():
"""Get app context for tests
:return:
"""
return db | 4c780071e5a092870a676685aede295365de6ad9 | 25,808 |
def login_required(route_function):
"""
这个函数看起来非常绕
是实现装饰器的一般套路
"""
def f(request):
u = current_user(request)
if u is None:
log('非登录用户')
return redirect('/login')
else:
return route_function(request)
return f | 44cff97ad32257e4dc4cfe5d7e3b79ea643986ef | 25,809 |
def cuTypeConverter(cuType):
""" Converts calendar user types to OD type names """
return "recordType", CalendarDirectoryRecordMixin.fromCUType(cuType) | a4afcfe912fc1d853ee841ed215c099c352ace0c | 25,810 |
def add_viz_sphere(
sim: habitat_sim.Simulator, radius: float, pos: mn.Vector3
) -> habitat_sim.physics.ManagedRigidObject:
"""
Add a visualization-only sphere to the world at a global position.
Returns the new object.
"""
obj_attr_mgr = sim.get_object_template_manager()
sphere_template = ob... | cc8f47c8b32ad2f4bf7c0e159d19dac048546aea | 25,811 |
import torch
def get_normalize_layer(dataset: str) -> torch.nn.Module:
"""Return the dataset's normalization layer"""
if dataset == "imagenet":
return NormalizeLayer(_IMAGENET_MEAN, _IMAGENET_STDDEV)
elif dataset == "cifar10":
return NormalizeLayer(_CIFAR10_MEAN, _CIFAR10_STDDEV) | 52d5d0a744e0e10db1f54d83dfb9b7a8b779c49d | 25,812 |
def summer_69(arr):
"""
Return the sum of the numbers in the array,
except ignore sections of numbers starting
with a 6 and extending to the next 9 (every 6 will be followed by at least one 9).
Return 0 for no numbers.
:param arr: list of integers
:return: int
"""
get_result = 0
... | d155a739afe131025b654002bebb51b25325bd1e | 25,813 |
def get_notebook_title(nb_json, default=None):
"""Determine a suitable title for the notebook.
This will return the text of the first header cell.
If that does not exist, it will return the default.
"""
cells = nb_json['cells']
for cell in cells:
if cell['cell_type'] == 'heading':
... | 4a20fe9890371ab107d0194e791c6faf9901d714 | 25,814 |
import torch
def extract_sequence(sent,
annotations,
sources,
label_indices):
"""
Convert the annotations of a spacy document into an array of observations of shape
(nb_sources, nb_bio_labels)
"""
sequence = torch.zeros([len(sent), len... | 1d988fe82b19d583438b8bf1ceb00671de566fca | 25,816 |
def is_valid_password_1(password):
"""
>>> is_valid_password_1("111111")
True
>>> is_valid_password_1("223450")
False
>>> is_valid_password_1("123789")
False
"""
has_double = any(password[c] == password[c+1] for c in range(len(password)-1))
is_ascending = all(password[c] <= passw... | 8544e15a7d50c025073a3ac51b9f5b8809341d2e | 25,817 |
def mean(x, axis=None, keepdims=False):
"""Mean of a tensor, alongside the specified axis.
Parameters
----------
x: A tensor or variable.
axis: A list of integer. Axes to compute the mean.
keepdims: A boolean, whether to keep the dimensions or not.
If keepdims is False, the rank of the tensor is reduce... | 9f8d1b98a5f1dd37a91493fb822437885e04468e | 25,818 |
def frame_pass_valid_sample_criteria(frame, image_type):
"""Returns whether a frame matches type criteria"""
return frame_image_type_match(frame, image_type) | cf5b51dfe63e7667a14b41c9793a66aa065663e8 | 25,819 |
def embed(tokenizer, text):
"""
Embeds a text sequence using BERT tokenizer
:param text: text to be embedded
:return: embedded sequence (text -> tokens -> ids)
"""
return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text)) | 453d411d9c460dfc28cb54c7a6a807290905bed3 | 25,820 |
def exponent_fmt(x, pos):
""" The two args are the value and tick position. """
return '{0:.0f}'.format(10 ** x) | 46e2104e966ec452fb510a411b1907090d55daf3 | 25,821 |
def _unpack(arr, extent, order='C'):
"""
This is a helper method that handles the initial unpacking of a data array.
ParaView and VTK use Fortran packing so this is convert data saved in
C packing to Fortran packing.
"""
n1,n2,n3 = extent[0],extent[1],extent[2]
if order == 'C':
arr =... | 2d7054da8ffc5773bfd151973bf3b06c84c2e735 | 25,822 |
import torch
def unzip(list):
"""unzip the tensor tuple list
Args:
list: contains tuple of segemented tensors
"""
T, loss = zip(*list)
T = torch.cat(T)
mean_loss = torch.cat(loss).mean()
return T, mean_loss | 5ed656aa8221c7bc5bd8a43b80fe0efd07d4df24 | 25,823 |
def ergs_to_lsun(luminosity):
"""
From luminostiy in erg/s to Lsun
"""
lum = u.Quantity(luminosity, u.erg / u.s)
return lum.to(u.L_sun) | fa7e572f5509b0408520e15433141e6da88daae1 | 25,824 |
def decode(code, P):
"""
Decode an RNS representation array into decimal number
:param P: list of moduli in order from bigger to smaller [pn, .., p2, p1, p0]
>>> decode(code=[5, 3, 1], P=[7,6,5])
201
"""
lcms = np.fromiter(accumulate(P[::-1], np.lcm), int)[::-1]
n = code[-1] % P[-1]
... | 422128ef0d0da62b404b6e8c0b927221505ead17 | 25,825 |
def is_collection(obj):
"""
Check if a object is iterable.
:return: Result of check.
:rtype: bool
"""
return hasattr(obj, '__iter__') and not isinstance(obj, str) | 70fa0262ea7bf91a202aade2a1151d467001071e | 25,826 |
import hashlib
def file_md5(fpath):
"""Return the MD5 digest for the given file"""
with open(fpath,'rb') as f:
m = hashlib.md5()
while True:
s = f.read(4096)
if not s:
break
m.update(s)
return m.hexdigest() | 40b355b9a628d286bf86b5199fd7e2a8bea354de | 25,827 |
def move(column, player):
"""Apply player move to the given column"""
index = _index_of(column, None)
if index < 0:
print('Entire column is occupied')
return False
column[index] = player
return True | 9c728c4c764154390478e27408f5bc25acaacf1d | 25,830 |
def calculate_costs(points, centric_point):
""" Returns the accumulated costs of all point in `points` from the centric_point """
if len(points) == 1:
return points[0].hyp()
_part = (points - centric_point)**2
_fin = []
for point in _part:
_fin.append(point.hyp())
return (np.array(_fin)).sum() | c35e00dabb3e85d5136afc3f5696a73aad607470 | 25,831 |
def formatUs(time):
"""Format human readable time (input in us)."""
if time < 1000:
return f"{time:.2f} us"
time = time / 1000
if time < 1000:
return f"{time:.2f} ms"
time = time / 1000
return f"{time:.2f} s" | 7546db60e3977e07dbbbad0a3ab767865840c2e3 | 25,832 |
from typing import Dict
from typing import List
from typing import Union
def parse_annotations(ann_filepath: str) -> Dict[int, List[Label]]:
"""Parse annotation file into List of Scalabel Label type per frame."""
outputs = defaultdict(list)
for line in load_file_as_list(ann_filepath):
gt = line.st... | 1ef42147fa4cb44b1ebd37f861444e502d0ea9b9 | 25,833 |
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from typing import Any
def apply(lang1: Dict[List[str], float], lang2: Dict[List[str], float], parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> float:
"""
Calculates the EMD distance between ... | c87d171018a6eddef6572a0bd3639952499fca44 | 25,835 |
import collections
def reInpainting(image, ground_truth, teethColor):
"""
if pixel has pink color (marked for teeth) and not in range of teeth => fill by teethColor
"""
isTeeth, isNotTeeth = 0, 0
threshold = calculateThreshhold(image, teethColor)
# print(f"Threshold: {threshold}")
for ... | c5f8a71c9c1bbf6e3b4c03b477901b9669d9f72c | 25,836 |
def data_for_cylinder_along_z(center_x, center_y, radius, height_z):
"""
Method for creating grid for cylinder drawing. Cylinder will be created along Z axis
:param center_x: Euclidean 3 dimensional center of drawing on X axis
:param center_y: Euclidean 3 dimensional center of drawing on Y axis
:par... | 2582860582564e7b8a4e9ba6e89d0740d44fa069 | 25,837 |
def _configure_learning_rate(num_samples_per_epoch, global_step):
"""Configures the learning rate.
Args:
num_samples_per_epoch: The number of samples in each epoch of training.
global_step: The global_step tensor.
Returns:
A `Tensor` representing the learning rate.
Raises:
ValueError: if
""... | c1395b7521b6a55e8a77c50b47dca920f8c27dc0 | 25,838 |
def cpm(adata: ad.AnnData) -> ad.AnnData:
"""Normalize data to counts per million."""
_cpm(adata)
return adata | ec0a2a0ed61965e8c78ebf59fab569f2a4954790 | 25,839 |
def argon2_key(encryption_password, salt):
"""
Generates an encryption key from a password using the Argon2id KDF.
"""
return argon2.low_level.hash_secret_raw(encryption_password.encode('utf-8'), salt,
time_cost=RFC_9106_LOW_MEMORY.time_cost, memory_cost=RFC_9106_LOW_MEMORY.memory_cost,
... | eaf5a0f3ca0ee12e22b0ddb9594dcd1734ef91e8 | 25,840 |
def print_policy_analysis(policies, game, verbose=False):
"""Function printing policy diversity within game's known policies.
Warning : only works with deterministic policies.
Args:
policies: List of list of policies (One list per game player)
game: OpenSpiel game object.
verbose: Whether to print po... | 51379d78dc3dd924da41dc00e8d6236d72b68f3c | 25,841 |
def model_fn(is_training=True, **params):
"""
Create base model with MobileNetV2 + Dense layer (n class).
Wrap up with CustomModel process.
Args:
is_training (bool): if it is going to be trained or not
params: keyword arguments (parameters dictionary)
"""
baseModel = MobileNetV2... | 2a14d803c5d521f453ce30a641d8736364e64ac0 | 25,842 |
def roundToElement(dateTime, unit):
""" Returns a copy of dateTime rounded to given unit
:param datetime.datetime: date time object
:param DtUnit unit: unit
:return: datetime.datetime
"""
year = dateTime.year
month = dateTime.month
day = dateTime.day
hour = dateTime.hour
minute ... | 226f532e9e729d155d14135e4025015e8b00b2e0 | 25,844 |
def tuple_factory(colnames, rows):
"""
Returns each row as a tuple
Example::
>>> from cassandra.query import tuple_factory
>>> session = cluster.connect('mykeyspace')
>>> session.row_factory = tuple_factory
>>> rows = session.execute("SELECT name, age FROM users LIMIT 1")
... | 5526647a414b397ac9d71c35173718c01385a03b | 25,845 |
def is_error(splunk_record_key):
"""Return True if the given string is an error key.
:param splunk_record key: The string to check
:type splunk_record_key: str
:rtype: bool
"""
return splunk_record_key == 'error' | 26371ec9c5941fbf07a84c6904ea739b02eb97ba | 25,846 |
def parse_network_info(net_bond, response_json):
"""
Build the network info
"""
out_dict = {}
ip_list = []
node_count = 0
# Build individual node information
for node_result in response_json['result']['nodes']:
for node in response_json['result']['nodes']:
if node['no... | 2c83aa72d6ee0195a42339546d1fded84f85680f | 25,847 |
async def create_or_update(hub, ctx, name, resource_group, **kwargs):
"""
.. versionadded:: 1.0.0
Create or update a network security group.
:param name: The name of the network security group to create.
:param resource_group: The resource group name assigned to the
network security group... | 251ee69d6077d2fd4ffda8c9da53b8ae84c9a696 | 25,848 |
def download_media_suite(req, domain, app_id):
"""
See Application.create_media_suite
"""
return HttpResponse(
req.app.create_media_suite()
) | fe0f5e0b5598b2368fd756a7f6bee89035813317 | 25,849 |
def non_numeric(string: str) -> str:
""" Removes all numbers from the string """
return ''.join(letter for letter in string if not letter.isdigit()) | fe16297c4cf1b144fb583986a5c01ea02920787e | 25,850 |
import re
def prepare_xs(path, numbergroup=1):
"""Prepare the needed representation of cross-section data
Paramteres:
-----------
path : str
filename of cross-section data
numbergroup : int
number of energies neutron multigroup
Returns:
--------
energies : iter... | 5f6ffd4e7954984d43ebc00c108d268797831256 | 25,851 |
def shiftField(field, dz):
"""Shifts the z-coordinate of the field by dz"""
for f in field:
if f.ID == 'Polar Data':
f.set_RPhiZ(f.r, f.phi, f.z + dz)
elif f.ID == 'Cartesian Data':
f.set_XYZ(f.x, f.y, f.z + dz)
return field | c3c592356dc21688049a94291d075879a12012ee | 25,852 |
def pair_equality(dataframe, column_1, column_2, new_feature_name):
"""
Adds a new binary feature to an existing dataframe which, for every row,
is 1 if and only if that row has equal values in two given columns.
:param dataframe:
Dataframe to add feature to
:param column_1:
Name of... | d82a02c49399351aa62b712664bb9500390ebf81 | 25,853 |
def identity_block(input_tensor, kernel_size, filters, stage, block):
"""The identity block is the block that has no conv layer at shortcut.
# Arguments
input_tensor: input tensor
kernel_size: default 3, the kernel size of middle conv layer at main path
filters: list of integers, the fil... | 3d33a0bec933697eae642199fe7b24e90e45e15b | 25,855 |
def cmp_id(cls1, cls2, idx1, idx2):
"""Compare same particles between two clusters and output numbers
Parameters
----------
cls1,cls2: Cluster object
idx1,idx2: Indices of detected particles in the clusters.
Output
------
The number of same particles.
"""
partId1 = cls1.gas_id[... | b3ebf4a3c98da18a84545caff446e0d1732208a0 | 25,858 |
def get_clinical_cup():
"""
Returns tuple with clinical cup description
"""
return ("8", "2", "M", "01", 25) | fac133ea74fbe30b50e551fdd7cdce349cc02a3a | 25,859 |
def to_utm_bbox(bbox: BBox) -> BBox:
"""Transform bbox into UTM CRS
:param bbox: bounding box
:return: bounding box in UTM CRS
"""
if CRS.is_utm(bbox.crs):
return bbox
lng, lat = bbox.middle
utm_crs = get_utm_crs(lng, lat, source_crs=bbox.crs)
return bbox.transform(utm_crs) | 80e67ce402ba1551a5282f93fc629be78255e96a | 25,860 |
def define_actions(action):
"""
Define the list of actions we are using.
Args
action: String with the passed action. Could be "all"
Returns
actions: List of strings of actions
Raises
ValueError if the action is not included in H3.6M
"""
actions = ["walking", "wiping", "lifting", "co-exis... | 45bfbd20971a04f566feeed0de509b21be83963b | 25,861 |
def gen_order_history_sequence(uid, history_grouped, has_history_flag):
""" 用户订单历史结果构成的序列 """
# 311 天的操作记录
sequence = ['0'] * 311
if has_history_flag == 0:
return sequence
df = history_grouped[uid]
for i in df['days_from_now']:
sequence[i] = str(df[df['days_from_now'] == i].shap... | 9f9e93549ea4c35971f87957b74e44e258d79d49 | 25,862 |
def _get_plugin_type_ids():
"""Get the ID of each of Pulp's plugins.
Each Pulp plugin adds one (or more?) content unit type to Pulp. Each of
these content unit types is identified by a certain unique identifier. For
example, the `Python type`_ has an ID of ``python_package``.
:returns: A set of pl... | 0c31a239980a2427f1fb115d890eea9d92edf396 | 25,863 |
def scale_48vcurrent(value, reverse=False, pcb_version=0):
"""
Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw
value to Amps (if reverse=False), or convert a value in Amps to raw (if reverse=True).
For now, raw values are hundredths of a... | 562a9354f1648203ba9854f2404e00365e12f67f | 25,864 |
import pickle
def get_graph(graph_name):
"""Return graph, input can be string with the file name (reuse previous created graph),
or a variable containing the graph itself"""
# open file if its a string, or just pass the graph variable
if '.p' not in graph_name:
graph_name = add_extension(gra... | 0efe5cb90b6f8bf1fc59853704cf7e07038fb8fb | 25,865 |
def get_transfer_encodings():
"""Return a list of supported content-transfer-encoding values."""
return transfer_decoding_wrappers.keys() | c42dfd886b1080e6a49fe4dabc2616967855a7f0 | 25,867 |
def is_name_valid(name: str, rules: list) -> bool:
""" Determine whether a name corresponds to a named rule. """
for rule in rules:
if rule.name == name:
return True
return False | 41e9f88d86a078ca6386f1d0d6b7123233c819b9 | 25,868 |
def fig2data(fig, imsize):
"""
:param fig: Matplotlib figure
:param imsize:
:return:
"""
canvas = FigureCanvas(fig)
ax = fig.gca()
# ax.text(0.0, 0.0, "Test", fontsize=45)
# ax.axis("off")
canvas.draw()
image = np.fromstring(canvas.tostring_rgb(), dtype="uint8")
width,... | 5a8b7bf34d6aa3849f20b5ca140c572c5cad0e57 | 25,869 |
def draw_agent_trail(img, trail_data, rgb, vision):
""" draw agent trail on the device with given color.
Args:
img : cv2 read image of device.
trail_data : data of trail data of the agent
rgb : (r,g,b) tuple of rgb color
Returns:
img : updated image ... | 9524cb10cbe1ed7dceb8714c7ace443be64e8767 | 25,870 |
def get_total_received_items(scorecard):
""" Gets the total number of received shipments in the period (based on Purchase Receipts)"""
supplier = frappe.get_doc('Supplier', scorecard.supplier)
# Look up all PO Items with delivery dates between our dates
data = frappe.db.sql("""
SELECT
SUM(pr_item.received_q... | 856e5b42a1b572a6fa7150b789eb8754a045677d | 25,871 |
def generate_default_filters(dispatcher, *args, **kwargs):
"""
Prepare filters
:param dispatcher: for states
:param args:
:param kwargs:
:return:
"""
filters_list = []
for name, filter_data in kwargs.items():
if filter_data is None:
# skip not setted filter name... | e307b9933280bfc91ef25ac306586c3cc6cf8c94 | 25,872 |
def linear_map(x, init_mat_params=None, init_b=None, mat_func=get_LU_map,
trainable_A=True, trainable_b=True, irange=1e-10,
name='linear_map'):
"""Return the linearly transformed, y^t = x^t * mat_func(mat_params) + b^t,
log determinant of Jacobian and inverse map.
Args:
... | 1286fc8087288f94b1ef63388fc6c8636d061b2f | 25,873 |
def isolated_70():
"""
Real Name: b'Isolated 70'
Original Eqn: b'INTEG ( isolation rate symptomatic 70+isolation rate asymptomatic 70-isolated recovery rate 70\\\\ -isolated critical case rate 70, init Isolated 70)'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
retur... | b1185a6a03759830f7cfeaefae34389699e62c48 | 25,874 |
def db_retry(using=None, tries=None, delay=None, max_delay=None, backoff=1, jitter=0, logger=logging_logger):
"""Returns a retry decorator.
:param using: database alias from settings.DATABASES.
:param tries: the maximum number of attempts.
-1 means infinite.
None - get fr... | 5727bb89f55a8cc68cea2a35ea256b79b6b852da | 25,875 |
from typing import Collection
def A000142(start: int = 0, limit: int = 20) -> Collection[int]:
"""Factorial numbers: n! = 1*2*3*4*...*n
(order of symmetric group S_n, number of permutations of n letters).
"""
sequence = []
colors = []
x = []
for i in range(start, start + limit):
se... | c0c709529bb7926369912ea195aec5fba17f7887 | 25,876 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.