content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import io
import torch
def load_image_buffer_to_tensor(image_buf, device):
"""Maps image bytes buffer to tensor
Args:
image_buf (bytes buffer): The image bytes buffer
device (object): The pytorch device object
Returns:
py_tensor tensor: Pytorch tensor
"""
image = Image.op... | 43740d2f9b7eec64f54111e85e0a54787afc8100 | 7,200 |
def alpha2tand(freq, a, b, n):
"""Convert Halpern's 'a' and 'b' from an absorption coefficient
of the form `a*freq**b` to a (frequency-dependent) loss tangent.
Parameters
----------
freq : numpy array or float
The frequency (Hz) (or frequencies) at which to calculate the loss
tangen... | 2acf658e7d18a0e115ba557698cc4efd591ed26d | 7,201 |
def convert_path_to_pixels(path):
"""
Purpose:
---
This function should convert the obtained path (list of tuples) to pixels.
Teams are free to choose the number of points and logic for this conversion.
Input Arguments:
---
`path` : [ list ]
Path returned from task_4a.find_path() function.
Returns:
... | a50557f252d43f9c3df1b3781c1203dd518d3797 | 7,202 |
def uniform_prob(*args, prob=None, inside=None, pscale=1.):
""" Uniform probability function for discrete and continuous vtypes. """
# Detect ptype, default to prob if no values, otherwise detect vtype
assert len(args) >= 1, "Minimum of a single positional argument"
pscale = eval_pscale(pscale)
use_logs = ... | 75cd547fc2845cb94f5733310be0d7761ba379fb | 7,203 |
import glob
def obtenerListaArchivos(path: str):
""" genera una lista de los archivos alojados en str """
lista = glob.glob(path, recursive=True)
return lista | 3b9582dbf086a2af673cc75277041f32d001e215 | 7,204 |
def is_equal_to(amount: float) -> Predicate:
"""Says that a field is exactly equal to some constant amount."""
return is_nearly_equal_to(amount, tolerance=0, taper=0) | c2c9b795d7bb089834e8e11e980b9d794e69d97a | 7,205 |
from sys import version_info
def get_version():
"""Return the current version info.
The first call to this function will call version_info.load() and cache the
result for later calls.
"""
global _version
if _version is None:
_version = version_info.load()
return _version | 4ced584e4155bc5926c6d28e28a090d332a7387b | 7,206 |
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If config... | 957a5d171568592da89cfa58a69c746ffcf67d33 | 7,207 |
def unmix_cvxopt(data, endmembers, gammaConst=0, P=None):
"""
******************************************************************
unmix finds an accurate estimation of the proportions of each endmember
Syntax: P2 = unmix(data, endmembers, gammaConst, P)
This product is Copyright (c) 2013 University o... | d529b412afde7a7eb35a02d5d039ec271285829f | 7,208 |
import logging
def _accumulate_reward(
timestep: dm_env.TimeStep,
episode_return: float) -> float:
"""Accumulates rewards collected over the course of an episode."""
if timestep.reward and timestep.reward != 0:
logging.info('Reward: %s', timestep.reward)
episode_return += timestep.reward
if ti... | 8f96e9a5bbeb4babfd43283b6da8a7984e53f02b | 7,209 |
def unsafe_load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
Resolve all tags, even those known to be
unsafe on untrusted input.
"""
return load(stream, UnsafeLoader) | ff74beb13746504508832cc9b658a8faf672d2ca | 7,210 |
import pickle
def load_tl_gan_model():
"""
Load the linear model (matrix) which maps the feature space
to the GAN's latent space.
"""
with open(FEATURE_DIRECTION_FILE, 'rb') as f:
feature_direction_name = pickle.load(f)
# Pick apart the feature_direction_name data structure.
featu... | aeb0bd329e4c9f8c91ded7c80385c30e1fb69773 | 7,211 |
from typing import Optional
from pathlib import Path
import os
def _find_test_file_from_report_file(base_path: str, report: str) -> Optional[Path]:
"""
Find test file from cucumber report file path format
e.g) Test-features-foo-hoge.xml -> features/foo/hoge.feature or features/foo-hoge.feature
"""
... | ebe53bc0fe5fefde6133d32a7ec6801810026626 | 7,212 |
def luminance(qcolor):
""" Gives the pseudo-equivalent greyscale value of this color """
r,g,b = qcolor.red(), qcolor.green(), qcolor.blue()
return int(0.2*r + 0.6*g + 0.2*b) | 9e1821da2c0c6e8d76aefe56d6ed659a728737bb | 7,213 |
def read_info(path, layer=None, encoding=None):
"""Read information about an OGR data source.
`crs` and `geometry` will be `None` and `features` will be 0 for a
nonspatial layer.
Parameters
----------
path : str or pathlib.Path
layer : [type], optional
Name or index of layer in dat... | 7479c63223288c94ed4756350756473866d7b2b3 | 7,214 |
import time
import requests
import json
def _macro_cons_opec_month():
"""
欧佩克报告-月度, 数据区间从 20170118-至今
这里返回的具体索引日期的数据为上一个月的数据, 由于某些国家的数据有缺失,
只选择有数据的国家返回
:return: pandas.Series
阿尔及利亚 安哥拉 厄瓜多尔 加蓬 伊朗 伊拉克 科威特 利比亚 尼日利亚 \
2017-01-18 108.0 172.4 54.5 21.3 37... | 5ae77b64b5d66e14027d757ea840385d0fc96033 | 7,215 |
import argparse
def createparser():
"""Create an :class:`argparse.ArgumentParser` instance
:return: parser instance
:rtype: :class:`argparse.ArgumentParser`
"""
parser = argparse.ArgumentParser(prog=__package__,
description=__doc__)
s = parser.add_subparse... | d5aa807be432d9e1aaa5d155b12fa1366c5fe050 | 7,216 |
def get_activation(preact_dict, param_name, hook_type):
"""
Hooks used for in sensitivity schedulers (LOBSTE, Neuron-LOBSTER, SERENE).
:param preact_dict: Dictionary in which save the parameters information.
:param param_name: Name of the layer, used a dictionary key.
:param hook_type: Hook type.
... | 8d5766178ef972e010b5be3a3826774f051dd3bd | 7,217 |
def createAbsorption(cfgstr):
"""Construct Absorption object based on provided configuration (using available factories)"""
return Absorption(cfgstr) | 587b0e12f845171ffd61d5d04c37b4ff98865216 | 7,218 |
def get_optimizer_config():
"""Gets configuration for optimizer."""
optimizer_config = configdict.ConfigDict()
# Learning rate scheduling. One of: ["fixed", "exponential_decay"]
optimizer_config.learning_rate_scheduling = "exponential_decay"
# Optimization algorithm. One of: ["SGD", "Adam", "RMSprop"].
opt... | 1918cd8aa9ff8446dec8cb90ff529de97f05d5aa | 7,219 |
def flat2seq(x: Tensor, num_features: int) -> Tensor:
"""Reshapes tensor from flat format to sequence format.
Flat format: (batch, sequence x features)
Sequence format: (batch, sequence, features)
Args:
x (Tensor): a tensor in the flat format (batch, sequence x features).
num_features ... | d8bace4548d82352ebae28dc9be665b862b744d0 | 7,220 |
def run_results(results_data, time_column, pathway_column, table_letters, letters,
dataframe_T1, dataframe_T2, dataframe_T3, dataframe_T4,
original_transitions, simulation_transitions,
intervention_codes, target, individuals,
save_location, simulation_... | 5292328a1f74d2ecb89daae465bace1a95eff538 | 7,221 |
from typing import Optional
def get_spatial_anchors_account(name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSpatialAnchorsAccountResult:
"""
Get information about ... | db94c210af0c46cea2e3a95573f339ec65f7e7fe | 7,222 |
import re
def format_query(str_sql):
"""Strips all newlines, excess whitespace, and spaces around commas"""
stage1 = str_sql.replace("\n", " ")
stage2 = re.sub(r"\s+", " ", stage1).strip()
stage3 = re.sub(r"(\s*,\s*)", ",", stage2)
return stage3 | 5adb0f9c3314ba04bbf92c88e3ef17802b2afeb0 | 7,223 |
def make_ytick_labels(current_ticks, n, numstring = ""):
"""
"""
new_ticks = []
for item in current_ticks:
if int(item) == item:
new_ticks.append(f"{int(item)}{numstring}")
else:
new_ticks.append(f"{item:.1f}{numstring}")
return new_ticks | 2685126dc72305ccb7b4bf652fe645e9a39affd3 | 7,224 |
import re
def check_token(token):
"""
Returns `True` if *token* is a valid XML token, as defined by XML
Schema Part 2.
"""
return (token == '' or
re.match(
"[^\r\n\t ]?([^\r\n\t ]| [^\r\n\t ])*[^\r\n\t ]?$", token)
is not None) | b4e1d313fb64aad4c1c244cb18d3629e13b1c3af | 7,225 |
def generate_random_data(n=10):
"""Generate random data."""
return rand(10) | 872591efc14d28282b24138f80e19c92487bde6d | 7,226 |
import re
import os
def get_basenames(root, path, remove='.py'):
"""Get file basenames of a folder.
Args:
root (str): Root path
path (str): Path to folder
remove (str, optional): Defaults to '.py'. Part to remove from filename.
Returns:
list: list of names
"""
reg... | cdce93c20b8938f2c6176e82d6fde2d061da0d2c | 7,227 |
def get_phoible_feature_list(var_to_index):
"""
Function that takes a var_to_index object and return a list of Phoible segment features
:param var_to_index: a dictionary mapping variable name to index(column) number in Phoible data
:return :
"""
return list(var_to_index.keys())[11:] | a53995cd927d1cdc66fadb2a8e6af3f5e2effff0 | 7,228 |
def split_data(dataset):
"""Split pandas dataframe to data and labels."""
data_predictors = [
"Steps_taken",
"Minutes_sitting",
"Minutes_physical_activity",
"HR",
"BP",
]
X = dataset[data_predictors]
y = dataset.Health
x_train, x_test, y_train, y_test = ... | b15db522ff45dee825d64d7daf6604fb400bc677 | 7,229 |
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
return response | 6e755f47bd12095d80a941338c451e677f80bcc6 | 7,230 |
def recursive_isomorphism_counter(smp, matching, *,
unspec_cover, verbose, init_changed_cands, tmplt_equivalence=False,
world_equivalence=False):
"""
Recursive routine for solving subgraph isomorphism.
Parameters
----------
smp : MatchingProblem
A subgraph matching problem
... | 3bc46c76569b17e05484ba3e31ecb3e5207c86cc | 7,231 |
def draw_lane_on_unwarped_frame(frame, left_line, right_line, trsf_mtx_inv):
""" Drawing of the unwarped lane lines and lane area to the current frame.
Args:
left_line: left Line instance
right_line: right Line instance
trsf_mtx_inv: inverse of the perspective transformation matrix
... | b59b3d99a17ba241aff0a9ac7e6d33497f1db803 | 7,232 |
import os
def _init_buffer_file() -> str:
"""Returns file path to the temporary buffer file. Creates the
temp directory and temp buffer file.
"""
if not os.path.exists(".git"):
raise NotAGitRepoException(f"No .git folder found. {os.getcwd()} is not a git repo!")
file_path = os.path.join(".... | 871346ec0f6960befa5365b9f63eca8d6adc6c62 | 7,233 |
def n_states_of_vec(l, nval):
""" Returns the amount of different states a vector of length 'l' can be
in, given that each index can be in 'nval' different configurations.
"""
if type(l) != int or type(nval) != int or l < 1 or nval < 1:
raise ValueError("Both arguments must be positive integ... | 98770fa5a5e62501bf365a4a5a40a932b2ba2450 | 7,234 |
def remove_items_from_dict(a_dict, bad_keys):
"""
Remove every item from a_dict whose key is in bad_keys.
:param a_dict: The dict to have keys removed from.
:param bad_keys: The keys to remove from a_dict.
:return: A copy of a_dict with the bad_keys items removed.
"""
new_dict = {}
for ... | 7c665e372c2099441f8a661f1194a76a21edf01c | 7,235 |
def writeObject(img_array, obj_array, bbox):
"""Writes depression objects to the original image.
Args:
img_array (np.array): The output image array.
obj_array (np.array): The numpy array containing depression objects.
bbox (list): The bounding box of the depression object.
Returns:... | 141cf9c3f47766a4020d737e743215db04761f54 | 7,236 |
def process_model(current_val):
"""
:param current_val: model generated by sat solver, atom is satisfied if in modal.
:return tuple of sets comprising true and false atoms.
"""
true_atoms, false_atoms = set(), set()
for atom in current_val:
if current_val[atom]:
true_atoms.... | 9cf90aec097091841c0f0ac820317f373a92e4c1 | 7,237 |
import re
def filter_strace_output(lines):
"""
a function to filter QEMU logs returning only the strace entries
Parameters
----------
lines : list
a list of strings representing the lines from a QEMU log/trace.
Returns
-------
list
a list of strings representing only ... | 01b6c048ebdf890e9124c387fc744e56cc6b7f4d | 7,238 |
def export_gmf_xml(key, dest, sitecol, imts, ruptures, rlz,
investigation_time):
"""
:param key: output_type and export_type
:param dest: name of the exported file
:param sitecol: the full site collection
:param imts: the list of intensity measure types
:param ruptures: an ord... | 139e24feb476ab10c0f1192fd47f80b7bbe29ccb | 7,239 |
import functools
def track_state_change(entity_ids, from_state=None, to_state=None):
"""Decorator factory to track state changes for entity id."""
def track_state_change_decorator(action):
"""Decorator to track state changes."""
event.track_state_change(HASS, entity_ids,
... | 08f6e7f8354f51dfa54d233156585c84d9b811b3 | 7,240 |
def phrase():
"""Generate and return random phrase."""
return models.PhraseDescription(text=random_phrase.make_random_text()) | 458529df5d6dbd92b7a6545d92b836763a8411a6 | 7,241 |
def classify_tweets(text):
"""
classify tweets for tweets about car accidents and others
:param text: tweet text
:return: boolean, true if tweet is about car accident, false for others
"""
return text.startswith(u'בשעה') and (
(u'הולך רגל' in text or
u'הולכת רגל' in text... | b34991a36febf2648cd83f2782ba4a8631e65a1a | 7,242 |
def _build_results(drift_type, raw_metrics):
"""Generate all results for queried time window or run id of some a datadriftdetector.
:param raw_metrics: origin data diff calculation results.
:return: a list of result dict.
"""
results = []
for metric in raw_metrics:
ep = _properties(met... | 2938257d54d0be0ac012c4ddc39952c6767b8a38 | 7,243 |
def no_test_server_credentials():
"""
Helper function that returns true when TEST_INTEGRATION_*
credentials are undefined or empty.
"""
client_id = getattr(settings, 'TEST_INTEGRATION_CLIENT_ID', None)
username = getattr(settings, 'TEST_INTEGRATION_USERNAME', None)
password = getattr(setting... | a98f249e15f9d1c42aacd62a22024af577332275 | 7,244 |
from typing import Tuple
from typing import Any
def skip_spaces(st: ST) -> Tuple[ST, Any]:
"""
Pula espaços.
"""
pos, src = st
while pos < len(src) and src[pos].isspace():
pos += 1
return (pos, src), None | df0c549c8af18a66a6e2d1704991592516e62ffb | 7,245 |
def mixed_phone_list():
"""Return mixed phone number list."""
return _MIXED_PHONE_LIST_ | e607eb5778d8f4999fcbeb85ea5a3bb0ca04ee40 | 7,246 |
def bootstrap(config):
"""
Configure the existing account for subsequent deployer runs.
Create S3 buckets & folders, upload artifacts required by
infrastructure to them.
Args:
config: dictionary containing all variable settings required
to run terraform with
Returns:
... | c06101d64113a9e2cf647d29cad32fa923ffbcb2 | 7,247 |
def get_report_summary(report):
"""
Retrieve the docstring summary content for the given report module.
:param report: The report module object
:returns: the first line of the docstring for the given report module
"""
summary = None
details = get_report_details(report)
if not details:
... | ea350c527cfab62496110ae08eedd9841db10492 | 7,248 |
def load_dataset(dataset_identifier, train_portion='75%', test_portion='25%', partial=None):
"""
:param dataset_identifier:
:param train_portion:
:return: dataset with (image, label)
"""
# splits are not always supported
# split = ['train[:{0}]'.format(train_portion), 'test[{0}:]'.format(tes... | f836236f56ba8359194c21c20ea6767d296a0ee4 | 7,249 |
from typing import List
import functools
def stop(ids: List[str]):
"""Stop one or more instances"""
return functools.partial(ec2.stop_instances, InstanceIds=ids) | fdf6db088323e5874c01662cf931aa85143ac2aa | 7,250 |
import os
import re
def search_names(word, archive=TAXDB_NAME, name="names.dmp", limit=None):
"""
Processes the names.dmp component of the taxdump.
"""
# Needs a taxdump to work.
if not os.path.isfile(archive):
utils.error("taxdump file not found (download and build it first)")
# Ope... | 127f65d713df58a15bf01f498123dde8550727a3 | 7,251 |
def simple_parse(config_file):
"""
Do simple parsing and home-brewed type interference.
"""
config = ConfigObj(config_file, raise_errors=True)
config.walk(string_to_python_type)
# Now, parse input and output in the Step definition by hand.
_step_io_fix(config)
return(config) | 85a406125a644fb75a5d8986778de6ea9b8af52a | 7,252 |
import pickle
def deserialize_columns(headers, frames):
"""
Construct a list of Columns from a list of headers
and frames.
"""
columns = []
for meta in headers:
col_frame_count = meta["frame_count"]
col_typ = pickle.loads(meta["type-serialized"])
colobj = col_typ.deser... | 176d936a6019669f15049f11df00e14ad62238d7 | 7,253 |
import os
import sys
def get_site_config(sites_path=None, site_path=None):
"""Returns `site_config.json` combined with `sites/common_site_config.json`.
`site_config` is a set of site wide settings like database name, password, email etc."""
config = {}
sites_path = sites_path or getattr(local, "sites_path", None... | 84346f0307f3e4b278c5dfe7fb9662b9d59f8a87 | 7,254 |
def words_with_joiner(joiner):
"""Pass through words unchanged, but add a separator between them."""
def formatter_function(i, word, _):
return word if i == 0 else joiner + word
return (NOSEP, formatter_function) | 9f24b2e7d202663902da0bfccd8e9b96faebc152 | 7,255 |
def magerr2Ivar(flux, magErr):
"""
Estimate the inverse variance given flux and magnitude error.
The reason for this is that we need to correct the magnitude or
flux for Galactic extinction.
Parameters
----------
flux : scalar or array of float
Flux of the obejct.
magErr : scal... | 37c48c26f1b876ca4d77dc141b1728daaea24944 | 7,256 |
def create_policy_work_item_linking(repository_id, branch,
blocking, enabled,
branch_match_type='exact',
organization=None, project=None, detect=None):
"""Create work item linking policy.
"""
organiza... | 230604606ba47c29386027503f45d30577cb5edf | 7,257 |
import numbers
def center_data(X, y, fit_intercept, normalize=False, copy=True,
sample_weight=None):
"""
Centers data to have mean zero along axis 0. This is here because
nearly all linear models will want their data to be centered.
If sample_weight is not None, then the weighted mean ... | d31b27868a6f1ee21ef4019df9954fc1136d73eb | 7,258 |
import socket
async def get_ipv4_internet_reachability(host, port, timeout):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host,... | ff1d335dec568810431c58b0bc1a72eb10e65372 | 7,259 |
def cov_pen(h_j, h_no_j):
"""
Personal implementation of covariance matrix with penalization.
:param h_j:
:param h_no_j:
:return:
"""
final_dim = h_j.shape[1]
cov_matrix = np.empty((final_dim, final_dim))
for row in range(final_dim):
for column in range(final_dim):
... | 4a3ef366a072fd84d198597213ea544d88032ac5 | 7,260 |
def get_last_timestamp():
"""
获取当天23:59:59的时间戳
:return:
"""
# 获取明天0点的时间戳
future_timestamp = get_timestamp(-1)
# 明天0点的时间戳-1
last_timestamp = future_timestamp - 1
return last_timestamp | 7f4c07309f9be1437c1743f691402bae58a7ec34 | 7,261 |
from typing import List
from typing import Dict
import os
import timeit
def crawl(folder: str, search: str, maxnum: int, num_threads: int, crawlers: [List[str]] = ['GOOGLE', 'BING', 'BAIDU']) -> Dict[str, str]:
"""Crawl web sites for images"""
print('(1) Crawling ...')
# prepare folders
os.makedirs(fo... | 409a338ad0cd49641c0a690434d5706664bc7c6e | 7,262 |
def _get_all_subclasses(typ, # type: Type[T]
recursive=True, # type: bool
_memo=None # type: Set[Type[Any]]
):
# type: (...) -> Iterable[Type[T]]
"""
Returns all subclasses of `typ`
Warning this does not support g... | a9a9c1186e195347f937961b928159c605b64ffe | 7,263 |
import logging
def conditions_summary(conditions):
"""
Return a dict of consumer-level observations, say, for display on a
smart mirror or tablet.
"""
keys = ['timestamp', 'dewpoint', 'barometricPressure', 'windDirection',
'windSpeed', 'windGust', 'precipitationLastHour', 'temperature',
... | aa4c95fd892c63bd05abd24188b8931375973bc0 | 7,264 |
def InsertOrganisation(cur, con, entity_name: str = "Organisation") -> int:
""" Inserts a new Organisation into the database """
# Get information about the video game
print(f"Enter new {entity_name}'s details:")
row = {}
row["Name"] = input(f"Enter the name of the {entity_name}: ") or None
row[... | de22b6eeb446efab58a2124f1b26da1e9edb12ed | 7,265 |
def _rgb_to_hsv(rgbs):
"""Convert Nx3 or Nx4 rgb to hsv"""
rgbs, n_dim = _check_color_dim(rgbs)
hsvs = list()
for rgb in rgbs:
rgb = rgb[:3] # don't use alpha here
idx = np.argmax(rgb)
val = rgb[idx]
c = val - np.min(rgb)
if c == 0:
hue = 0
... | ee4a2d9867351e61bf9b14de4ef2d05425285879 | 7,266 |
def find_correlation(convergence_data, lens_data, plot_correlation=False, plot_radii=False, impact=False, key=None):
"""Finds the value of the slope for plotting residuals against convergence. Magnitude of slope and error
quantify correlation between the two.
Inputs:
conv -- convergence.
mu_diff ... | d507cd256a555b442fff1cd2a00862a5afdf0661 | 7,267 |
def ELCE2_null_estimator(p_err, K, rng):
"""
Compute the ELCE^2_u for one bootstrap realization.
Parameters
----------
p_err: numpy-array
one-dimensional probability error vector.
K: numpy-array
evaluated kernel function.
rng: type(np.random.RandomState... | 5b42e36ade4aba416bb8cbf6790d22fd8e4913b1 | 7,268 |
import curses
def select_from(stdscr, x, y, value, slist, redraw):
"""
Allows user to select from a list of valid options
:param stdscr: The current screen
:param x: The start x position to begin printing
:param y: The start y position to begin pritning
:param value: The current value chosen
... | 208283731317418bbe5ae1d16386584eaebcd626 | 7,269 |
def describe(r):
"""Return a dictionary with various statistics computed on r:
mean, variance, skew, kurtosis, entropy, median.
"""
stats = {}
stats['mean'] = r.mean()
stats['variance'] = r.var()
stats['skew'] = skew(r)
stats['kurtosis'] = kurtosis(r)
stats['median'] = np.median(... | 7ed070110ac327ef69cf1c05eefdda16c21f7f0d | 7,270 |
def value_iteration(env,maxiter):
"""
Just like policy_iteration, this employs a similar approach.
Steps (to iterate over):
1) Find your optimum state_value_function, V(s).
2) Keep iterating until convergence
3) Calculate your optimized policy
Outputs:
- Your f... | c116d0408d6edfa82763febb030633b815d69812 | 7,271 |
def is_excluded(branch_name):
"""
We may want to explicitly exclude some BRANCHES from the list
of BRANCHES to be merged, check if the branch name supplied
is excluded if yes then do not perform merging into it.
Args:
branch_name: The branch to check if to be inc... | d38923a84e7a3f9a40ebd101de5c542156fff7aa | 7,272 |
def schedule_contrib_conv2d_winograd_without_weight_transform(attrs, outs, target):
"""Schedule definition of conv2d_winograd_without_weight_transform"""
with target:
return topi.generic.schedule_conv2d_winograd_without_weight_transform(outs) | e186a727ccf69c3292d8807abd003485308754db | 7,273 |
import os
import sys
import mne
from mne.preprocessing import read_ica
from nipype.utils.filemanip import split_filename as split_f
from ephypype.preproc import create_ts
def preprocess_set_ica_comp_fif_to_ts(fif_file, subject_id, n_comp_exclude,
is_sensor_space):
"""Preproce... | f70cd29a4a1e189dfe46e2713dfce95c8a21e8f9 | 7,274 |
def _phi(r: FloatTensorLike, order: int) -> FloatTensorLike:
"""Coordinate-wise nonlinearity used to define the order of the
interpolation.
See https://en.wikipedia.org/wiki/Polyharmonic_spline for the definition.
Args:
r: input op.
order: interpolation order.
Returns:
`phi_k` e... | 80a41c99a4ef8b396d16b02a6217eaa9191105f6 | 7,275 |
def linbin(n, nbin=None, nmin=None):
"""Given a number of points to bin and the number of approximately
equal-sized bins to generate, returns [nbin_out,{from,to}].
nbin_out may be smaller than nbin. The nmin argument specifies
the minimum number of points per bin, but it is not implemented yet.
nbin defaults to th... | 2d537131ad8d13e32375b74b9fa3e77088d046dd | 7,276 |
from bs4 import BeautifulSoup
def get_soup(url):
"""Gets the soup of the given URL.
:param url: (str) URL the get the soup from.
:return: Soup of given URL.
"""
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36'}... | 69982a75a5c329b0d9e0ca7638c0ffffdc3ac21e | 7,277 |
def msd_id_to_dirs(msd_id):
"""Given an MSD ID, generate the path prefix.
e.g. TRABCD12345678 -> A/B/C/TRABCD12345678"""
return op.join(msd_id[2], msd_id[3], msd_id[4], msd_id) | e210ae919de4fc8b037a7e8d7aabb6858b6e07f9 | 7,278 |
def get_data_path(sub_path):
"""Returns path to file in data folder."""
return join(_data_folder_path, sub_path) | 847b59cfea7f4d42b65f166230c032e71bb92ecd | 7,279 |
import io
def read_avro_bytes(URL, open_with, start_byte, length, header, nrows=None):
"""Pass a specific file/bytechunk and convert to dataframe with cyavro
Both a python dict version of the header, and the original bytes that
define it, are required. The bytes are prepended to the data, so that the
... | 9542eb13c1247de35f00a1fa370aba721f8657cd | 7,280 |
def get_launches(method="", **query):
"""Gets launches based on query strings
Gets launches based on query strings from
the API
Parameters
----------
method : str (optional)
the method used for the request
query : keyword args
keyword args based on t... | ca162affdd7aef187985e0d2c75e153ad75db162 | 7,281 |
def state(obj):
"""Gets the UnitOfWork state of a mapped object"""
return obj.__ming__.state | 1072265fe175ffcd581d14af5d4ee85f2941a5e4 | 7,282 |
def save_file_in_path(file_path, content):
"""Write the content in a file
"""
try:
with open(file_path, 'w', encoding="utf-8") as f:
f.write(content)
except Exception as err:
print(err)
return None
return file_path | 7b1e453a9b2a8c1211e111a6e8db432811d84a7a | 7,283 |
import json
from datetime import datetime
def export_entity_for_model_and_options(request):
"""
Export entity list in a list of 'format' type.
@note EntityModelClass.export_list() must return a list of results.
User of the request is used to check for permissions.
"""
limit = int_arg(request.G... | 5539d3fe66dd3163044acf7073e40e55cc1c3b5c | 7,284 |
def gen_instance_hv_map(ann, crop_shape):
"""Input annotation must be of original shape.
The map is calculated only for instances within the crop portion
but based on the original shape in original image.
Perform following operation:
Obtain the horizontal and vertical distance maps for each
nuclear instance.
""... | e6a5d6f50d91e0e6b7cf27cb05568b6526608ff9 | 7,285 |
import torch
def jaccard_loss(true, logits, eps=1e-7):
"""Computes the Jaccard loss, a.k.a the IoU loss.
Note that PyTorch optimizers minimize a loss. In this
case, we would like to maximize the jaccard loss so we
return the negated jaccard loss.
Args:
true: a tensor of shape [B, H, W] or ... | ae6c8f94662f48be81abf60c8a8fcd88f7ff7d81 | 7,286 |
def _get_distribution_schema():
""" get the schema for distribution type """
return schemas.load(_DISTRIBUTION_KEY) | 32af1d9547d978a8a57a799ba74723f21e05c756 | 7,287 |
def compute_transforms(rmf_coordinates, mir_coordinates, node=None):
"""Get transforms between RMF and MIR coordinates."""
transforms = {
'rmf_to_mir': nudged.estimate(rmf_coordinates, mir_coordinates),
'mir_to_rmf': nudged.estimate(mir_coordinates, rmf_coordinates)
}
if node:
m... | 3190a94cc406bb1199df3480202df4a3258912f9 | 7,288 |
def merge_dicts(*list_of_dicts):
"""Merge a list of dictionaries and combine common keys into a list of values.
args:
list_of_dicts: a list of dictionaries. values within the dicts must be lists
dict = {key: [values]}
"""
output = {}
for dikt in list_of_dicts:
for k, v ... | 3d629bb9bc6af2a637a622fea158447b24c00bd0 | 7,289 |
def highpass_filter(src, size):
"""
highpass_filter(src, size)
ハイパスフィルター
引数
----------
src : AfmImg形式の画像
size : 整数
フィルターのサイズ
戻り値
-------
dst : AfmImg形式の画像
フィルターがかかった画像
"""
def highpass(dft_img_src, *args):
dft_img = dft_img_src.copy()
#マ... | 7945e3556cdd2eb4fd1e2303cbba00052a4a5900 | 7,290 |
import re
import socket
def parse_target(target):
"""
解析目标为ip格式
:param str target: 待解析的目标
:return tuple scan_ip: 解析后的ip和域名
"""
scan_ip = ''
domain_result = ''
main_domain = ''
try:
url_result = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', target)
if ... | 292d90eebefb8da5289b20914dfbcd9c294ee5b7 | 7,291 |
from typing import Type
def isWrappedScalarType(typ: Type) -> bool:
"""
Given a type, determine if it is a c10::scalar which we will wrap in a lazy Value.
Since we literally change the type from scalarT to valueT, information is lost.
This function helps build a list of wrapped scalars to save that in... | 0d854c734ddf3441dd2524c56d1d84d85fc7ac22 | 7,292 |
def assign_topic(data, doc_topic_distr):
""" Assigns dominant topic to documents of corpus.
:param data: DF of preprocessed and filtered text data
:type data: pd.DataFrame
:param doc_topic_distr: Array of topic distribution per doc of corpus
:type doc_topic_distr: np.array
:return: DF incl assi... | d53661831d9ee1431f989b290396be3ebde0582a | 7,293 |
def _enable_scan_single_bytecode(code, name):
"""
Part of the ``_enable_scan`` that applies the scan behavior on a single
given list/set comprehension or generator expression code.
"""
bc = bytecode.Bytecode.from_code(code)
Instr = bytecode.Instr
# Updates LOAD_GLOBAL to LOAD_FAST when arg ... | d1bd12f50961869e09d4cbdc121e01abbe34232a | 7,294 |
def composite_rotation(r, p1=qt.QH([1, 0, 0, 0]), p2=qt.QH([1, 0, 0, 0])):
"""A composite function of next_rotation."""
return next_rotation(next_rotation(r, p1), p2) | 335363a18efb36d28c87b0266bd4dcdd27b6b85a | 7,295 |
def extract_vectors_ped_feature(residues, conformations, key=None, peds=None, features=None, indexes=False, index_slices=False):
"""
This function allows you to extract information of the ped features from the data structure. In particular allows:
- all rows or a specific subset of them, containing a certai... | 3d0efb833ffd80303e2494d017c12e1d06d10bcc | 7,296 |
def Load_File(filename):
"""
Loads a data file
"""
with open(filename) as file:
data = file.readlines()
return data | f49aa4474d9af0b8a778b9575e282eb579c103ab | 7,297 |
from scipy.ndimage import morphology
import numpy
def massage_isig_and_dim(isig, im, flag, band, nm, nu, fac=None):
"""Construct a WISE inverse sigma image and add saturation to flag.
unWISE provides nice inverse variance maps. These however have no
contribution from Poisson noise from sources, and so u... | b0bf70ddfff3a6b0a48005b9e1069c5c5f670dac | 7,298 |
import subprocess
def sh(arg):
"""
Execute command in a background shell.
Args:
arg (str or list): shell command, or a list of shell commands.
"""
if isinstance(arg, list):
return [sh(a) for a in arg]
else:
return subprocess.check_output(arg, shell=True).decode("utf-8"... | bfde2eaca0b25a0c8012f5541b72a6f142d1180f | 7,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.