content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dict_option(s):
"""An option of type 'dict'.
The value (on the command-line, in an env var or in the config file) must be eval'able to a dict.
"""
return _convert(s, (dict,)) | 93b574b33f44a144c52b0cde3403cba3646fb7a1 | 3,601,733 |
def get_present_volume(present):
"""Calculate volume of the box needed for present."""
volume = 1
for side in present:
volume *= side
return volume | e3df95638a741513307163abd90a68013aa7da3b | 3,601,735 |
def crop_rasters_for_sr(max_sr_factor, *hmaps):
"""Crop a list of rasters to a size such that they can be evently divided by
``max_sr_factor``. It assumes that each raster is centered identically. I.e. if one
raster has size 256x256 and another 254x254, it assumes that it is a border of size
1 that is r... | 77b45841cb82bc5475c6343df05c91b04d4e74c8 | 3,601,736 |
def fit(model):
"""Represents a general fit process.
Parameters
----------
model : uncertainty-aware model
Represents the fitted uncertainty-aware model.
Returns
-------
ensemble : list
Returns a list of fitted base estimators.
"""
global fit_state
# Set global ... | 9e1ad91f4919acd4d66ca1b53099aa314eb357f2 | 3,601,737 |
from datetime import datetime
def beta(pos: TimeSeriesInterface, benchmark: TimeSeriesInterface, lookback: str = None, date: datetime = None,
**kwargs) -> float:
"""
Compute the beta of the returns distribution from a TimeSeries object on a benchmark on the specified time period.
:param pos: Tim... | c362fcaa881162dfbeeed36a617710cac90b7f69 | 3,601,738 |
def merge_with(x, other):
"""Returns a shape combining the information in `x` and `other`.
The dimensions in `x` and `other` are merged elementwise, according to the
rules defined for `tf.Dimension.merge_with()`.
For more details, see `help(tf.TensorShape.merge_with)`.
Args:
x: object representing a sh... | dd38fbfa98d892bbeab58cd76b6304fbeab90c3c | 3,601,739 |
from typing import Tuple
def scale_coordinates(
reference_coords: CoordinatePair,
reference_size: Tuple[int, int],
target_size: Tuple[int, int],
) -> CoordinatePair:
"""Compute the coordinates corresponding to a scaled version of the image.
Parameters
----------
reference_coords: Coordina... | eea199864ed73b48859b08b3412b591df2a82f22 | 3,601,740 |
def sklearn_flatten(input_xr):
"""
Reshape a DataArray or Dataset with spatial (and optionally
temporal) structure into an np.array with the spatial and temporal
dimensions flattened into one dimension.
This flattening procedure enables DataArrays and Datasets to be used
to train and predict... | 6f753b3dc0827b0852f2020e3e374b83ab0678c5 | 3,601,741 |
def semeval2conll(dataset):
"""
transform the format of semeval datasets to conll form
:param dataset: input dataset
:return:
"""
conll_lines = []
for record in dataset:
ote_raw_tags = record['ote_raw_tags']
ts_raw_tags = record['ts_raw_tags']
words = record['words']
... | 1c6ad2c5e27a1e8c2a5603768c96cc5dc82b8508 | 3,601,742 |
def login():
""" Show login form """
session.clear()
if request.method == "POST":
if not request.form.get("username"):
flash("Must provide a Username", "alert-warning")
return render_template("login.html")
elif not request.form.get("password"):
flash("... | 47cefc6c1bfaa4c2bee7f66475603cc8bc9ae4f0 | 3,601,743 |
def form_folder(groups):
"""
take in a date tuple and form the folder name
"""
month = groups[0]
day = groups[1]
year = groups[2]
if month in month_map:
month = month_map[month]
else:
logger.error("month ({}) not in month_map. this should never happen".format(month))
return None
if len(day... | 1f069e5ea27f5c9bdd1f02d3ff1a0aa31ec69007 | 3,601,744 |
def get_user_from_dict(user, data_coleta=None):
"""Return user metadata."""
# pylint: disable=too-many-locals
# remove space and _ from name and screen_name
name = _pre_processing(user.get('name'))
screen_name = _pre_processing(user.get("screen_name"))
background_image = 1 if user.get('profile_... | a3baaf14659dfcaadf46885100e5f12f1d3f4579 | 3,601,745 |
def wtap_damage_assessment(probabilities, assignment, target_values):
"""
:param probabilities: graph.
:param assignment: graph
:param target_values: dictionary
:return: total survival value of the targets.
"""
assert isinstance(probabilities, Graph)
assert isinstance(assignment, Graph)
... | 5e7ac8bfc7eda568a4ae2c106e7319a11ea502bf | 3,601,746 |
def track_score(track_path):
"""
Scoring the proposal tracklet can b associate 2 st_track possibility.
Score = weight_motion * score_motion + weight_appearance * score_appearance
:return:
"""
path_score = 0.
for each_node in track_path:
path_score += each_node.score
return path_s... | 8633bdbff8520e94e775d34b64bc448fa3b9366b | 3,601,747 |
def interpolate(df, verbose=True, prev_df=None, next_df=None, sr=None, start_time=None, stop_time=None, fill_big_gap_with_na=True, gap_threshold = 1, method="spline"):
"""Make timestamps with consistent intervals with interpolation.
Delete duplicate timestamps, interpolate to make sampling rate consistent wit... | ec96ec758025cffb8b3cd00a09ad5ef5e3554bad | 3,601,748 |
from typing import Mapping
from typing import Type
from typing import DefaultDict
from typing import Dict
import difflib
def apply_args_filters(
args,
) -> Mapping[str, Mapping[str, Mapping[str, Type[InstanceConfig]]]]:
"""
Take an args object and returns the dict of cluster:service:instances
Currentl... | 4b8b638899cfce025b508d67c7d9dcb08c969452 | 3,601,749 |
import requests
def get_sensor_map_request(sensor_class, dates_selected, group,
cum_hours, geo_win,
interpolator,
img_dim, radius, stream=False):
"""
get a map for the selected sensor on the selected geowindow
:param sensor_class: sensor class strin... | 912b6b2fb6763fa4b7653a051b0f8d35c85cdda1 | 3,601,750 |
from typing import Union
from typing import Sequence
def repsep(
parser: Union[Parser, Sequence[Input]], separator: Union[Parser, Sequence[Input]]
) -> RepeatedSeparatedParser:
"""Match a parser zero or more times separated by another parser.
This matches repeated sequences of ``parser`` separated by ``s... | fc1ac9e5eae16ae1d589a52caea1310d309c9a56 | 3,601,751 |
import itertools
def get_available_languages(include_default=True):
"""
Returns a tuple of available languages for django-modeltrans.
"""
MODELTRANS_AVAILABLE_LANGUAGES = get_available_languages_setting()
if include_default:
return tuple(
set(itertools.chain(MODELTRANS_AVAILAB... | 4f61b99e203c07be0329114b44b42b41f7f7b555 | 3,601,752 |
def argmin_except_0(x,p):
"""
argmin_except_0(x,p)
Ensure that p is the argmin, i.e. the position of the minimum value
in x, but ignores any value of 0.
Note:
- If there are many minimum values then argmin_except_0(x,p) will find
all these values.
- We assume that there are at least one value > 0.... | 26fe8ed14044147bc8963fecdb1f73af17ddee5b | 3,601,753 |
def font_size_norm(x):
"""the web font size is different from the game client's - try to
approximate how it would look without having to know the actual value."""
try:
x = int(x)
except ValueError:
return "100%"
ratio = x / 24
return f"{int(ratio * 100)}%" | d70679ec385abe0cb283aa4615853e8b5e1a853e | 3,601,754 |
def load_vec_data_year(filename):
"""
give a save filename with a saved vector data year
creates a vector data year from what was saved
"""
try:
npzfile = np.load(filename)
x = npzfile["DY_x"]
y = npzfile["DY_y"]
except KeyError:
pass
else:
temp_tim... | eb2cffd72575166a317af9e67c82858cdb995693 | 3,601,756 |
def max_col_by_col(arrays,NaN=False):
"""Perform column by column max"""
colmax=[]
for arr in arrays:
if not colmax:
colmax=arr[:]
else:
if NaN:
colmax=[max_w_nan([colmax[i],arr[i]]) for i in xrange(0,len(arr))]
else:
c... | 6f5fb44bdf3d8eef06b2c8b6f937d0c36d76ddb5 | 3,601,757 |
def preprocessIncome(df, numOutliers):
"""
Function for preprocessing income and adding net income
"""
#print('Min kereset: ', df['htnetto'].min())
#print('Max kereset: ', df['htnetto'].max())
# Droping out outiers
for i in range(0, numOutliers):
df.drop(df[df['htnetto'] == df['... | 0d0666ce37c1538216766de51d9cc0ea4c2932a1 | 3,601,759 |
import dlib
def det_landmarks(image_path, dlib_model="E:/ModelZoo/shape_predictor_68_face_landmarks.dat"):
"""
detect faces in one image, return face bbox and landmarks
:param image_path:
:return:
"""
predictor = dlib.shape_predictor(dlib_model)
detector = dlib.get_frontal_face_detector()
... | 213258555a320274a86d6fd6da603d4518fe9fa0 | 3,601,760 |
def all_resolve_success(subdomains):
"""
判断是否所有子域都解析成功
:param subdomains: 子域列表
"""
resolver = utils.dns_resolver()
resolver.cache = None # 不使用DNS缓存
status = set()
for subdomain in subdomains:
status.add(query_a_record(subdomain, resolver))
return all(status) | ae618a4d41595bc404abe26b761772c56567ca9c | 3,601,761 |
import array
def get_Is(self):
"""Return the stator current DataTime object
Parameters
----------
self : OutElec
an OutElec object
"""
# Calculate stator currents if Is is not in OutElec
if self.Is is None:
# Generate current according to Id/Iq
Isdq = array([self.... | 3a64b6621c3cbaed7c0ef9e5ca6d1f6fbcaa9fbc | 3,601,762 |
def shared_rid_input(app):
"""Access DB directly. Get a random msmt
that has a match both in the measurement and fastpath tables
Returns (rid, input)
"""
sql = """
SELECT
fastpath.report_id,
fastpath.input
FROM fastpath
WHERE input IS NOT NULL
AND fastpath.report_id I... | 70ef5985de2d29473db8d499e83f5e71be6096a6 | 3,601,764 |
def apim_api_operation_get(client, resource_group_name, service_name, api_id, operation_id):
"""Gets the details of the API Operation specified by its identifier."""
return client.api_operation.get(resource_group_name, service_name, api_id, operation_id) | 4101a7aa2b3815856bf852a299698d407af390c0 | 3,601,765 |
def excel_to_json(file_path: str, sheet_name: str = None, want_sheet_names: bool = False) -> dict:
"""
This function reads the excel file and converts it to JSON
:param file_path:
:param sheet_name:
:param want_sheet_names:
:return:
"""
sheet_data = {'columnDefs': [{'headerName': "", 'fi... | ac8245c06b252dfa1a40d34987f530b1dd631673 | 3,601,766 |
def getEnumStr(obj, enum):
"""
Helper function that returns the names of enums for a property"
"""
enumStr = None
for enumName,val in vars(obj).iteritems():
if not enumName.startswith('__') and enumName not in IGNORED_TYPES:
if val == enum:
enumStr = enumName
... | 8474db290e2249c39f4f9cd46a1f5297c2b4ce6f | 3,601,767 |
def _uses_vulnerable_solc_version(version):
"""Detect if used compiler version is 0.4.[0|1|2|3|4]
Args:
version (solc version used)
Returns:
Bool
"""
if version in ["0.4.0", "0.4.1", "0.4.2", "0.4.3", "0.4.4"]:
return True
return False | 475dff3c6d3ed71317aab79e147f8797bde85f3a | 3,601,768 |
def entries_lto(test_dir):
"""
Recycle the test cases from pymatgen
"""
entries = loadfn(test_dir / "LiTiO2_batt.json")
for itr, ient in enumerate(entries):
ient.entry_id = f"mp-{itr}"
return entries | e08c0942c7152582b60a77b752071e19eb801749 | 3,601,769 |
import hashlib
def get_subscriber_hash(member_email):
"""
The MD5 hash of the lowercase version
of the list member's email.
Uses as memeber_id
"""
member_email = member_email.lower()
m = hashlib.md5(member_email)
return m.hexdigest() | c2d7c7f4d0da58ec3990cccad865cb53cf2ebe15 | 3,601,770 |
import threading
def _wait_for_emulator_ready(proc,
emulator,
indicator,
timeout=_EMULATOR_TIMEOUT):
"""Waits for emulator to be ready."""
def _read_thread(proc, ready_event):
"""Thread to continuously read from the proces... | 3e3274ab214ff1a9c6b02bf500f82812ec3f8b22 | 3,601,772 |
def Reverse(action):
"""Reverses the behavior of the action
Example::
# rotates the sprite 180 degrees in 2 seconds counter clockwise
action = Reverse( RotateBy( 180, 2 ) )
sprite.do( action )
"""
return action.__reversed__() | 9bde87421204300e55fff80eed0564f4b4d8e978 | 3,601,773 |
def outside_root_to_404(fn):
"""
Decorator for converting PathOutsideRoot errors to 404s.
"""
@wraps(fn)
def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except PathOutsideRoot as e:
raise HTTPError(404, "Path outside root: [%s]" % e.args[0])
... | d207eaf44d6be860d6203b802c0768718554e15d | 3,601,774 |
def affine_grid_backward(*grad_hess, grid=None):
"""Converts ∇ wrt dense displacement into ∇ wrt affine matrix
g = affine_grid_backward(g, [grid=None])
g, h = affine_grid_backward(g, h, [grid=None])
Parameters
----------
grad : (..., *spatial, dim) tensor
Gradient with respect to a den... | 2d09d2ab4bb2e82fa41483f8fa81b72ece8d150c | 3,601,775 |
def SurfaceStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | 5d96a51e634aa47479b5a12f4aa8ad4983c89022 | 3,601,776 |
def CI_sum_prop(estimates, mul_CIs):
"""
This function calculates the 95% confidence interval of a sum of two estimates.
We assume these estimates are distributed lognormally with 95% confidence interval provided as input
Input:
estimates: numpy array of the estimates to sum over
mul_CI... | 7fd582042796aa2441b1ce89920093bb6c8a0cfb | 3,601,777 |
from datetime import datetime
def prune(iterable, start, end):
"""Discard events that fall outside the start-end interval."""
events = sorted(iterable, key=lambda event: event.created_at)
events.reverse()
# Check if we have at least one event older than the start date.
# If so, then we have a com... | d69be8ef507347049b4fc59938378eb108cc8ee4 | 3,601,778 |
def get_licenses(obj):
"""
Returns a list of license under which the given language resource is
available.
"""
result = []
for dist in obj.distributioninfotype_model_set.all():
for licence_info in dist.licenceInfo.all():
result.append(licence_info.licence)
return result | 09cbadcc55b15d189c0f19095351fdb2d9d526e3 | 3,601,779 |
def patches(internal_api_patcher):
"""
Fixture that resets session-wide patches before each test case function
"""
for mock in internal_api_patcher.patcher_mocks:
mock.reset_mock()
return internal_api_patcher | 05bacb7491e7178a324c07da4c67fad0b1fed01c | 3,601,780 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
List the current nodes in the cluster
"""
return isamAppliance.invoke_get("List the current nodes in the cluster",
"/isam/cluster/nodes/v1", requires_model=requires_model) | 9a4c50d494facdfa914ae59f6671cc402b788e12 | 3,601,781 |
def bin(x, y, bins=10, range=None):
"""
Bin x and returns lists of the y-values inside each bin.
Parameters
----------
x: array-like
Variable that is binned.
y: array-like
Variable that is sorted according to the binning of x.
bins: integer or array-like
Number of bins or ... | 997cee04e25f30979a02ee39dd4019e4af4a5252 | 3,601,782 |
from typing import List
def verify_security(headers_dict: dict) -> List:
"""
Check the headers contained in the HTTP response against
the list of security headers recommended by the OWASP
Secure Headers Project
Args:
headers_dict (dict): dict of header names and descriptions
Returns:
... | 181a60e7f717f3c89e997820dbc46971179f5e5a | 3,601,784 |
import torch
def add_ligand_atom_to_data(data, pos, atom_type, y_ind, type_map=[1,6,7,8,9,15,16,17]):
"""
"""
data = data.clone()
data.ligand_context_pos = torch.cat([
data.ligand_context_pos, pos.view(1, 3).to(data.ligand_context_pos)
], dim=0)
data.ligand_context_feature_full = tor... | f3d1ca6d961542e6ec029f1d8fa6e2d22a4cc164 | 3,601,785 |
def readKiKitProps(footprint):
"""
Given a footprint, returns a string containing KiKit annotations.
Annotations are in FP_TEXT starting with prefix `KIKIT:`.
Returns a dictionary of key-value pairs.
"""
for x in footprint.GraphicalItemsList():
if not isinstance(x, pcbnew.FP_TEXT):
... | 98effcdecd5e77eac1fb15ea691a46bd126f6682 | 3,601,786 |
def add_dashboard_to_flask(server):
"""Create a Plotly Dash dashboard with the specified server.
This is actually used to create a dashboard that piggybacks on a
Flask app, using that app its server.
"""
dash_app = Dash(
__name__,
server=server,
routes_pathname_prefix='/dash-upload/',
... | 06dc62bcc79f29f5414dbc2e024970de96356802 | 3,601,788 |
from typing import Dict
from typing import Any
from typing import Iterable
def _get_properties(rsp: Dict[Text, Any]) -> Iterable[CdProperty]:
""" Retrieve key properties to be passed onto dynatrace server. """
machine_type = rsp.get("machineType", "/").split("/")[-1]
labels = [CdProperty(label, value) for... | 3921bc1613bad9166bf2486f5596b88f3af24086 | 3,601,789 |
def load_match(fn, create_part=False, pedal_threshold=64, first_note_at_zero=False):
"""Load a matchfile.
Parameters
----------
fn : str
The matchfile
create_part : bool, optional
When True create a Part object from the snote information in
the match file. Defaults to False.... | e87fb039ccfa6f555b6352cefbf093f18363f5ff | 3,601,791 |
def get_frame_number(frame):
"""Get frame number by calculating distance to newest frame."""
num = 0
newer = frame.newer()
while newer != None:
newer = newer.newer()
num += 1
return num | 1b653a629d9e34af2cfa1ce37bea54644a18236a | 3,601,792 |
from typing import Optional
import re
def convert_message(message: str) -> Optional[str]:
"""Extract release note from the commit message,
return None if there is no release note"""
if RELEASE_NOTES_TAG in message:
# new
if match := re.findall(RELEASE_NOTES_RE, message):
return... | a47281276ca2036917d855b8b92ee543f729a878 | 3,601,793 |
def separable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes,
**kwargs):
"""A block of separable convolutions."""
return conv_block_internal(separable_conv, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | 2de04fd4ec0c13b8cce3fa6ab2e27ab39c9f452e | 3,601,794 |
def make_terminal(edu, edu_i, relation, nuclearity):
"""
Parameters
----------
edu: str
edu_i: int
relation: str
nuclearity: str
Returns
-------
Terminal
"""
# node = Terminal(token=edu, index=edu_i, label="<%s,%s>" % (relation, nuclearity))
node = Terminal(token=edu... | ff9da81f01d69bc865a2f2dd6dde34fc61c9056e | 3,601,795 |
from typing import Tuple
from typing import List
def get_ema_tick_imbalance_bars(file_path_or_df: Tuple[str, pd.DataFrame], num_prev_bars: int = 3,
expected_imbalance_window: int = 10000, exp_num_ticks_init: int = 20000,
exp_num_ticks_constraints: List[f... | 1ff32901b1c406c54ce43ec95b90c89a2e7d038f | 3,601,796 |
from scipy.stats import norm
def match_end(ref, hyp, args):
"""Match end boundary given distribution."""
score = 0.0
collar = args.collar
if args.distribution == "uniform":
if (ref - collar < hyp and ref + collar > hyp):
score = 1.0
elif args.distribution == "triangular":
... | a3545181eb759af74338fb215b7918f397ebfb2c | 3,601,797 |
import torch
def batch_l2(kernels):
"""
Args:
kernels: (num_kernels, bsize, bsize)
"""
n = kernels.shape[0]
kernels = kernels.view(n, -1) # (n, bsize*bsize)
distances = torch.cdist(kernels, kernels)
distances = distances - torch.diag(torch.diag(distances))
return - distances.m... | 0d1d9d1544cf98a0ae92e34e6ed739dadc6ef5f5 | 3,601,798 |
def calculate_bbox_iou(bbox_a: BBox, bbox_b: BBox) -> float:
"""Calculates the IoU between 2 bboxes.
Args:
bbox_a (BBox): BBox.
bbox_b (BBox): BBox.
Returns:
float: IoU between the two bboxes.
"""
intersect_area = bbox_a.intersection_area_with(bbox_b)
union_area = bbox... | c4519ba8219e6b8a98fc35c7fa4130ff07637e9d | 3,601,800 |
def get_settings():
"""Return module settings global settings.
This method is cached through python's lru_cache decorator, so
only the first request creates an object, and all other requests
to this method returns the same object created the first time.
"""
return Settings() | 869686ffa1b1dd17e63b276324869c734e398c41 | 3,601,801 |
def resnet18(num_classes):
"""A slightly modified ResNet-18 model"""
def resnet_block(num_channels, num_residuals, first_block=False):
blk = nn.Sequential()
for i in range(num_residuals):
if i == 0 and not first_block:
blk.add(d2l.Residual(
num_cha... | 52ab1ff4feddb329aea4b3b6f74db705f2bb8e71 | 3,601,803 |
def person_lookup(request, details):
"""
Lists the demographic for a specific student
"""
data = {'status': 'error', 'message': 'No information for '+str(details)}
profiles = {}
for db in uqx_api.courses.EDX_DATABASES:
if db == 'default' or db == 'personcourse' or db == 'Course_Event':
... | c1a9611db5e2ae408757c591698643167c22f1c3 | 3,601,804 |
def md5shuffle(arr: ndarray, salt: str = None) -> ndarray:
"""
md5shuffle
Will shuffle the input array pseudo-randomly in a deterministic manner using MD5 hashing.
Parameters
----------
arr: list, ndarray
The array of values that you want shuffled
salt: str
A sting to appen... | 76bbce003290e1040ca4f5dadda4efa6b0732de2 | 3,601,805 |
def design_matrix(bvals, bvecs):
"""Return the diffusion kurtosis imaging design matrix.
Parameters
----------
bvals : numpy.ndarray
Floating-point array with shape (number of acquisitions,).
bvecs : numpy.ndarray
Floating-point array with shape (number of acquisitions, 3).
Ret... | 62a6e916d8df3d7e07ab30b5e39c20a9e5b21ca1 | 3,601,806 |
def residual_predicted_chart(predicted, residuals, title="Residual vs Predicted Values"):
"""Residual vs predicted values curve."""
source = pd.DataFrame({"x": predicted, "y": residuals})
return scatter_chart(source, "Prediction", "Residual", title=title) | a8c6b83eaa5896f8caf2a2af74cbc44f8a0004be | 3,601,807 |
def ecs_efs_encryption_status(status):
"""
Property: EFSVolumeConfiguration.TransitEncryption
"""
valid_status = ["ENABLED", "DISABLED"]
if status not in valid_status:
raise ValueError(
'ECS EFS Encryption in transit can only be one of: "%s"'
% (", ".join(valid_statu... | 85e0d0f8b3c33331c8d877f0554126ca72c023bc | 3,601,808 |
import yaml
def GetSchedulingNodeAffinityListFromArgs(args,
messages,
support_node_project=False):
"""Returns a list of ScheduleNodeAffinity messages populated from args."""
operator_enum = messages.SchedulingNodeAffinity.Operator... | c3f5c4a2b17ea1302baa58ea34fe671d89ac1998 | 3,601,809 |
def load_model(model_file, check_size=True):
"""
Loads a svm model from a file and computes its size
:param model_file: The file name of the model to load
:return: A dictionary with keys model, file, and size
"""
model = svm_load_model(model_file)
model_dict = {'model': model}
if check_s... | 73741e43603c270d73463ab2db28d5d9290a49a6 | 3,601,810 |
def robust_zscore(x: pd.Series, zscore=False):
"""Robust ZScore Normalization
Use robust statistics for Z-Score normalization:
mean(x) = median(x)
std(x) = MAD(x) * 1.4826
Reference:
https://en.wikipedia.org/wiki/Median_absolute_deviation.
"""
x = x - x.median()
mad = x... | 060d80ce5159b73dc2d68d265d2ae6eb965fa166 | 3,601,811 |
import warnings
def GlobalHandleGetBytes(handle, offset, count):
""" Backward compatible alias for :func:`global_handle_get_bytes` """
warnings.warn("GlobalHandleGetBytes is deprecated, use global_handle_get_bytes instead", DeprecationWarning)
return global_handle_get_bytes(handle, offset, count) | 75001aaa968b4789961d1fc8370f54d468907faa | 3,601,812 |
def folder_contents_html(folder_path, files, folders):
"""Given files and folders generate html."""
html = "<!DOCTYPE html><html><body>{}</body></html>"
atag = '<a href="{}">{}</a>'
files_and_folders = ''
for folder in folders:
files_and_folders += '<h4>' + atag.format(folder_path + '/' + fo... | 6b6b37ca9452319d309a61c877ebf6d1fba201aa | 3,601,813 |
def onehot_features(train, test, features, full=False, sparse=False, dummy_na=True):
"""Encode categorical features using a one-hot scheme.
Parameters
----------
train : pd.DataFrame
test : pd.DataFrame
features : list
Column names in the DataFrame to be encoded.
full : bool, defaul... | d42e6bd843cfc3ae990b0c8309c95b7b34f52f4d | 3,601,814 |
def is_valid_chars(value: str, chars: str = _input_character_set) -> bool:
"""
**is_valid_chars**
checks if all characters are valid
:param value: value to check
:param chars: valid characters
:return: bool indicating if characters are valid or not
"""
return not bool([inval... | 3b4fba6c79cd23430e78a9eb1a9f924cc353a572 | 3,601,816 |
def concentration_monthly_trend(hemisphere=None, year=None, month=None,
search_paths=nt.DEFAULT_SEA_ICE_PATHS,
min_days_for_valid_month=nt.MINIMUM_DAYS_FOR_VALID_MONTH,
trend_start_year=None, *, clipping_threshold):
"""R... | ab4b28b2dd22f568c87e71214ddd71e52200485f | 3,601,817 |
def prediction(outDir, model_weight):
"""
predict single sample breast cancer risk
:param outDir: output directory
:param model_weight: the MiScan model weight file path
:return: (risk_to_be_patient, probability_to_be_normal)
"""
logger.info('start model evaluation')
model = build_mode... | 2b65884a5ac88ecd45276a5488269807494d1d29 | 3,601,818 |
def find_package(sought_package):
"""Is this name mentioned anywhere? Then return it as a suggestion?
"""
# First check top-level keys
if sought_package in PACKAGE_MAP.keys():
return PACKAGE_MAP[sought_package]
for package in PACKAGE_MAP.keys():
for install_type in PACKAGE_MAP[package].keys():
if sought_pac... | e07962da8a48559abfbd3211c795a4d83a3ba3cb | 3,601,819 |
def launch():
""" Initialize the module. """
return UEMeasurementsWorker(UEMeasurements,
EP_ACT_UE_MEASURE,
UE_MEAS_RESPONSE) | a017fd4468c034efcce1880c82a76845df414af8 | 3,601,820 |
def search_date():
"""Function to search entries by date"""
date_printer()
user_parsed = date_checker()
date_query = Task.select().where(Task.date == user_parsed)
final_values = query_to_dict(date_query)
return final_values | 18d2a5b46da2267fdc199917526d3312e0028fac | 3,601,821 |
import functools
import inspect
import warnings
def deprecatedmethod(func):
"""
This is a decorator which can be used to mark class member
functions as deprecated.
"""
@functools.wraps(func)
def new_func(self, *args, **kwargs):
call_loc = inspect.stack()[-1]
warnings.warn_expli... | cdab9d45301c3ca9cee6b059b3ae44cbcc5a9a1f | 3,601,822 |
def set_defaults(module_path):
"""
Creates a module metadata using default values
"""
metadata = module_metadata.create_default_metadata(module_path)
return metadata | f8d215a8c0ef9d15d1d28f157f8770fb00224912 | 3,601,823 |
from typing import Union
def parallel_range(arg: Union[int, slice]) -> ParallelFor:
"""
Builds a parallel iterator.
"""
return _pygauss.parallel_range(arg) | bc569c08f2fe024d0e853673083685dc13ac921d | 3,601,824 |
import torch
import copy
def ResNet101_conv5_body(pretrained=True, model_path = None):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model_path = cfg.RESNETS.IMAGENET_PRETRAINED_WEIGHTS if model_path is None else model_path
mo... | a0d20abdb4692f02998db4fe4cf267d75b5647d0 | 3,601,827 |
def getConfig( config_file_path = "/etc/monitor.conf" ):
"""
Reads the process configuration from the config file.
Config file contains the processes to be monitored.
"""
process_dict = {}
parser = SafeConfigParser()
parser.read( config_file_path )
for section in parser.sections():
... | a258d61ddf8a859d7cda99a8e7d59715ced307af | 3,601,828 |
def calculateGainFactor(numerator:list, denominator:list, passband_freq:float) -> float:
"""Calculate and return the coefficent needed to normalise the passband gain of an IIR filter to unity"""
# Initalise variables
num_coeff = len(numerator) # Calculate number of tap coefficents
numerator_sum = 0 # T... | 035748dfd3bcd0aefe1aa56472f1559133eeb656 | 3,601,829 |
def setUnitValue(plug, value):
"""
Updates the unit value for the supplied unit plug.
:type plug: om.MPlug
:type value: Union[om.MDistance, om.MAngle]
:rtype: None
"""
return __setunitvalue__[getUnitType(plug.attribute())](plug, value) | e391037bd4041eb7d294ae380786aa09277e2ac8 | 3,601,830 |
from typing import List
from typing import Union
def select(evaluated_population: List[Eval], random_seed: Union[int, float] = 0.12345, num_elites: int = 5,
method: SelectionMethod = SelectionMethod.TOURNAMENT, tournament_size: int = 5,
temperature: float = 1.0) -> List[Parents]:
"""Uses the... | d29f8834cb268765bc8cef7dd9c48e896525c45b | 3,601,831 |
import re
import dateutil
import pytz
def convert_date_range_option(date_range):
"""Convert a DateRange option to datetime objects
Parameters
----------
date_range: str
The value of a DateRange option.
Returns
-------
start: datetime.datetime
The date range's start value
... | dc9be7add77ab94af0a1e361ce5dd21ae387cc6d | 3,601,832 |
def dummy(xy_in, params, invert=False):
"""
"""
return xy_in | 74e6986c37bd1367dbc152e77b5cef2097bf8e14 | 3,601,833 |
import random
def pick_sites(grid):
"""
Randomly pick two adjacent sites on a grid.
@type grid: Grid object
@param grid: grid
"""
# Pick the first site
site1 = (random.randrange(grid.height), random.randrange(grid.width))
# Pick an adjacent site
site2 = random.choice(grid.cells[si... | 18ed6a17aae292a23cec4a66dab98b290c0c5992 | 3,601,834 |
def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False, concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = ... | 37ff58f9c85904f937fdc9cd122d6a51d84eb009 | 3,601,835 |
from typing import Dict
from typing import Set
from typing import Any
def unique(domains: Dict[str, Set[Any]]) -> bool:
""" Each variable has exactly one value """
return all((len(domain) == 1
for domain in domains.values())) | 64551d938135b1a288ca97d480abe4282eddeefd | 3,601,836 |
def expand_flattened_path(flattened_path, value=None, separator='.'):
"""
Expands a dotted path into a nested dict; if value is set, the
final key in the path will be set to value.
:param str flattened_path: flattened path to expand
:param str separator: character(s) separating path components
... | 41c8cf40495e9922df3d31b641235fad2a823b4d | 3,601,837 |
def update_interview_questions_endpoint():
"""
Updates an interview question
Request body:
- `id`: Question ID
- `new_question`: New question for that interview
"""
content = request.json
headers = request.headers
if not validate_authentication(headers):
return jsonify({"status": auth_error})
... | 3d0fbd5de6c9c38445b04ab3f73e055f280b3504 | 3,601,838 |
def get_iou_scores(boxes, gt, mask):
"""
Compute and return IoU scores between two tensor of bounding boxes, and mask them with `mask`.
:param boxes: A [..., d, 4] tensor
:param gt: A [..., d, 4] tensor
:param mask: A [..., d, 1] tensor
:return: A [..., d, 1] tensor with IoU scores where mask i... | 4b50cd51dbeadc89d39326a10d19031b5ab22e5b | 3,601,839 |
def toMaiden(lat: float, lon: float = None, *, precision: int = 3) -> str:
"""
Returns a maidenhead string for latitude, longitude at specified level.
Parameters
----------
lat : float or tuple of float
latitude or tuple of latitude, longitude
lon : float, optional
longitude (i... | 6dba5f6cc0826a5def861105a672eca0d6108192 | 3,601,840 |
import html
def create_download_button(key):
"""
Creates a button that submits a POST request to the /download/ route.
Args:
key (str): S3 key
Returns:
html.Form
"""
return html.Form(
[
dbc.Input(type='hidden', name='key', value=serialize(key)),
... | 8f8cb8865c6bca468c1587e7c24dcd7d75055ba9 | 3,601,841 |
def _map_listparameter(value, separator=',', dtype=None):
"""
Map a string list into a python list
:param value: str or list, if list returns if string tries to evaluate
:param separator: str, where to split the str at to make a list
:param dtype: type, if set forces elements of list to this data t... | f3fbb7ae8415976842d980ab456f8de071068294 | 3,601,842 |
def handle_hashes(f):
"""
Normalize torrent hash arguments.
Initial implementations of this client used 'hash' and 'hashes'
as function arguments for torrent hashes. Since 'hash' collides
with an internal python name, all arguments were updated to
'torrent_hash' or 'torrent_hashes'. Since both ... | 7f59cc73f47bef073f5f24d2f209f061bf1fc031 | 3,601,843 |
def create_app(injector: Injector) -> Flask:
"""
Creates a Flask app
:param injector: The injector
:return: Returns the Flask app
"""
app_flask = Flask(__name__)
injector.binder.bind(Application, to=app_flask)
app_flask.config.from_object(Config)
registers = injector.get(Application... | f40759cad801963cb3f08d94208576a56d385bed | 3,601,844 |
from typing import Optional
def parse_dot_notation(input: str) -> tuple[str, Optional[tuple[str, ...]]]:
""" Parse dot-notation
Example:
parse_dot_notation('a') #-> 'a', None
parse_dot_notation('a.b.c') #-> 'a', ['b', 'c']
"""
name, _, sub_path_str = input.partition('.')
sub_path ... | 06650868fb773b41b97a839b0d423cc8f3cd4a85 | 3,601,845 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.