content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_inputs():
""" Parses the input arguments
Input: Command line inputs specified by the user.
Output: Parsed command line inputs
"""
parser = argparse.ArgumentParser(description = 'This will make a prediction on an image')
parser.add_argument('image', type = str, help = 'pa... | 49,200 |
def find_hpas(config: Config,) -> Iterable[client.models.v1_horizontal_pod_autoscaler.V1HorizontalPodAutoscaler]:
"""Find any HorizontalPodAutoscaler having klutch annotation."""
resp = client.AutoscalingV1Api().list_horizontal_pod_autoscaler_for_all_namespaces()
return filter(lambda h: config.hpa_annotatio... | 49,201 |
def bioacoustics_index (Sxx, fn, flim=(2000, 15000), R_compatible ='soundecology'):
"""
Compute the Bioacoustics Index from a spectrogram [1]_.
Parameters
----------
Sxx : ndarray of floats
matrix : Spectrogram
fn : vector
frequency vector
flim : tupple (fmin, fmax), ... | 49,202 |
def get_create_path_for(tlobject):
"""Gets the file path (and creates the parent directories)
for the given 'tlobject', relative to nothing; only its local path"""
# Determine the output directory
out_dir = 'methods' if tlobject.is_function else 'constructors'
if tlobject.namespace:
out... | 49,203 |
def test_fetch_incidents(requests_mock):
"""
Tests the fetch incident command
Configures requests_mock instance to generate the appropriate fetch_incidents
API response when the correct fetch_incidents API request is performed. Checks
the output of the command function with the expected output.
... | 49,204 |
def ctm_to_dict(ctm_fn):
"""
Return a dictionary with a list of (start, dur, word) for each utterance.
"""
ctm_dict = {}
with open(ctm_fn, "r") as f:
for line in f:
utt, _, start, dur, word = line.strip().split(" ")
if not utt in ctm_dict:
ctm_dict[utt... | 49,205 |
def upload_processed_image(img_info):
""" Uploads image to database
This function takes a processed image and its metadata and uploads
it to the MongoDB database. The image is linked to the user
that uploaded it.
Args:
img_info (dict): dictionary with image metadata including
the u... | 49,206 |
def double_a_float():
"""
What comes in: Nothing.
What goes out: Nothing (i.e. None)
Side effects:
a. Prompts the user for and inputs a floating point number.
b. Prints the input number, doubled (i.e., multiplied by 2).
No input validation is required. Nothing else should be printed.
... | 49,207 |
def qft_core(qubits, coef=1):
"""
Generates a quil programm that performs
quantum fourier transform on given qubits
without swaping qubits at the end.
:param qubits: A list of qubit indexes.
:param coeff: A modifier for the angle used in rotations (-1 for inverse
QFT, 1 f... | 49,208 |
def get_formatted_timestamp(app_type):
"""Different services required different date formats - return the proper format here"""
if app_type in {'duo', 'duo_admin', 'duo_auth'}:
return 1505316432
elif app_type in {'onelogin', 'onelogin_events'}:
return '2017-10-10T22:03:57Z'
elif app_type... | 49,209 |
def find_cp0_and_cpinf(species, heat_capacity):
"""
Calculate the Cp0 and CpInf values, and add them to the HeatCapacityModel object.
"""
if heat_capacity.Cp0 is None:
cp_0 = species.calculate_cp0()
heat_capacity.Cp0 = (cp_0, "J/(mol*K)")
if heat_capacity.CpInf is None:
cp_in... | 49,210 |
def UseWin64():
"""Check if we are on 64 bit windows."""
if sys.platform != 'win32':
return False
arch32 = os.environ.get('PROCESSOR_ARCHITECTURE', 'unk')
arch64 = os.environ.get('PROCESSOR_ARCHITEW6432', 'unk')
if arch32 == 'AMD64' or arch64 == 'AMD64':
return True
return False | 49,211 |
def preprocess(x, copy=False, float=False, axis=None):
"""
Ensure that `x` is a properly formatted numpy array.
Proper formatting means at least one dimension, and may include
optional copying, reshaping and coersion into a floating point
datatype.
Parameters
----------
x : array-like
... | 49,212 |
def generate_robot_2_rst(robot_file, rst_file, prefix, relationship_to_tag_mapping, gen_matrix):
"""
Calls mako template function and passes all needed parameters.
Args:
robot_file (Path): Path to the input file (.robot).
rst_file (Path): Path to the output file (.rst).
prefix (str)... | 49,213 |
def detect_defaults_settings(output):
""" try to deduce current machine values without any
constraints at all
"""
output.writeln("\nIt seems to be the first time you run conan", Color.BRIGHT_YELLOW)
output.writeln("Auto detecting your dev setup to initialize conan.conf", Color.BRIGHT_YELLOW)
re... | 49,214 |
def align_instance_center(dfi, original_patterns, aligned_patterns, trim_frac=0.08):
"""Align the center of the seqlets using aligned patterns
Args:
dfi: pd.DataFrame returned by `load_instances`
original_patterns: un-trimmed patterns that were trimmed using
trim_frac before scanning
... | 49,215 |
def compute_continent_histogram(docs: DocumentSet, **kwargs) -> pd.DataFrame:
""" Compute a histogram of number of documents by affiliation
continent.
"""
from .continent import COUNTRY_TO_CONTINENT
def extract(doc):
result = set()
for author in doc.authors or []:
fo... | 49,216 |
def calc_prod(corpus_context, envs, strict = True, all_info = False, ordered_pair = None,
stop_check = None, call_back = None):
"""
Main function for calculating predictability of distribution for
two segments over specified environments in a corpus.
Parameters
----------
corpus_c... | 49,217 |
def logPlot(name,itemname,value):
"""Logs a custom visualization item to a plot"""
global _vis
if _vis is None:
return
_vis.logPlot(name,itemname,value) | 49,218 |
def read_run_dict(file_name):
"""Read a run file in the form of a dictionary where keys are query IDs.
:param file_name: run file name
:return:
"""
result = {}
with FileWrapper(file_name) as f:
for ln, line in enumerate(tqdm(f, desc='loading run (by line)', leave=False)):
li... | 49,219 |
def get(expected_in = None):
"""
Validate that response on the last request to Aigents is one as expected.
Don't validate if no expected responce is provided.
Print the response if verbose is set to True.
Args:
expected_in - expected response text
Returns:
nothing
"""
global last_in
global failed
global v... | 49,220 |
def parse_address(address):
"""Convert host:port or port to address to pass to connect."""
if ':' not in address:
return ('', int(address))
host, port = address.rsplit(':', 1)
return (host, int(port)) | 49,221 |
def visualize_grasps(full_pc, pred_grasps_cam, scores, plot_opencv_cam=False, pc_colors=None, gripper_openings=None, gripper_width=0.08):
"""Visualizes colored point cloud and predicted grasps. If given, colors grasps by segmap regions.
Thick grasp is most confident per segment. For scene point cloud predictio... | 49,222 |
async def sync_bars_worker(sync_params: dict = None, secs: List[str] = None):
"""
worker's sync job
"""
logger.info("sync_bars_worker with params: %s, %s", sync_params, secs)
try:
frame_type, start, stop = _parse_sync_params(sync_params)
except Exception as e:
logger.warning("in... | 49,223 |
def buildDQMasks(imageObjectList,configObj):
""" Build DQ masks for all input images.
"""
# Insure that input imageObject is a list
if not isinstance(imageObjectList, list):
imageObjectList = [imageObjectList]
for img in imageObjectList:
img.buildMask(configObj['single'], configObj[... | 49,224 |
def secure_host_url(request, secure_url=None):
"""Overrides ``host_url`` to make sure the protocol is secure."""
# Test jig.
if secure_url is None:
secure_url = secure_request_url
return secure_url(request, 'host_url') | 49,225 |
def search():
"""
Used by `nuget list`.
"""
logger.debug("Route: /search")
logger.debug(request.args)
# TODO: Cleanup this and db.search_pacakges call sig.
include_prerelease = request.args.get('includePrerelease', default=False)
order_by = request.args.get('$orderBy', default='Id')
... | 49,226 |
def get_resource_mutator(cpu=None, memory=None, gpu=None, gpu_vendor='nvidia'):
"""The mutator for getting the resource setting for pod spec.
The useful example:
https://github.com/kubeflow/fairing/blob/master/examples/train_job_api/main.ipynb
:param cpu: Limits and requests for CPU resources (Default... | 49,227 |
def gram_matrix(features):
"""
Calculates the gram matrix of the feature representation matrix
:param features: The feature matrix that is used to calculate the gram matrix
:return: The gram matrix
"""
return K.dot(features, K.transpose(features)) | 49,228 |
def lp_dominate(w, U):
"""
Computes the belief in which w improves U the most.
With LP in White & Clark
:param w: np.ndarray
:param U: list of np.ndarray
:return: b if d >= 0 else None
"""
# print("LP dominate")
if len(U) == 0:
return w
S = len(w)
d = cvx.Variable()
... | 49,229 |
def get_random_subset_dataloader(dataset: Dataset, subset_size: Union[float, int], **dataloader_kwargs) -> DataLoader:
""" Returns a random subset dataloader sampling data from given dataset, without replacement.
Args:
- dataset: PyTorch dataset from which random subset dataloader is sampling data.
... | 49,230 |
def _combine_pfs(pfa, pfb, coeff, operator):
""" Obtain the pf information of the multiplication of pfa and pfb
"""
tempsa, logqa, dq_dta, d2q_dt2a = pfa
_, logqb, dq_dtb, d2q_dt2b = pfb
if operator == 'multiply':
logq = [a+b+numpy.log(coeff) for a, b in zip(logqa, logqb)]
dq_dt = ... | 49,231 |
def epa_nei_nonpoint_parse(*, df_list, source, year, config, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param source: source
:param year: year
:param config: dictionary, items in FBA method yaml
:return: df, parsed an... | 49,232 |
def create_auto_config(
dataset: Union[str, pd.DataFrame, dd.core.DataFrame, DatasetInfo],
target: Union[str, List[str]],
time_limit_s: Union[int, float],
tune_for_memory: bool,
user_config: Dict = None,
) -> dict:
"""Returns an auto-generated Ludwig config with the intent of training the best m... | 49,233 |
def main():
""" My main function"""
#
# finding a decoder match:
# - go through the list of bitmasks in the order of specificity
# - test first the ones that have most bits set
# - first one to match is the one
#
maskstrings = sorted(INSTRUCTIONS.iterkeys(),
... | 49,234 |
def change_file_name(file_path, prefix=None, name=None, suffix=None):
"""
Change the file name from the given file path
:param file_path: Input file path
:param prefix: Prefix to the file name
:param name: Whether a new name is set instead of the current name.
If None, the current file name ... | 49,235 |
def create_orbit_from_particles(particles, angular_velocity=0.|units.yr**-1):
"""
Use mass, position and velocity to determine orbital parameters.
Then setup Roche_Orbit
"""
roche = Roche_Orbit()
roche.mass_1, roche.mass_2 = particles.mass
position_vector = particles.position[1] - p... | 49,236 |
def bitter_rivals(voting_dict):
"""
Input: a dictionary mapping senator names to lists representing
their voting records
Output: a tuple containing the two senators who most strongly
disagree with one another.
Example:
>>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': ... | 49,237 |
def last_contacts(ts_start):
"""Get the last time each timeseries datapoint was updated.
Args:
config: Configuration object
ts_start: Timestamp to start from
Returns:
data: List of dicts of last contact information
"""
# Initialize key variables
data = []
last_cont... | 49,238 |
def directory_contents(path_to_dir):
"""
Returns list of paths to files and folders relatively from path_to_dir.
"""
cur_dir_backup = os.getcwd()
os.chdir(path_to_dir)
files = glob.glob('**', recursive=True)
os.chdir(cur_dir_backup)
return files | 49,239 |
def train_one_epoch_loss_acc(net, train_iter, loss, updater):
"""训练模型一个迭代周期(定义见第3章)
Defined in :numref:`sec_softmax_scratch`
返回 train loss 和 train acc
"""
# 将模型设置为训练模式
if isinstance(net, torch.nn.Module):
net.train()
# 训练损失总和、训练准确度总和、样本数
metric = Accumulator(3)
for X, y in tr... | 49,240 |
async def test_template_out_of_bounds(hass, calls):
"""Test template out-of-bounds condition."""
with assert_setup_component(1, "cover"):
assert await setup.async_setup_component(
hass,
"cover",
{
"cover": {
"platform": "template",
... | 49,241 |
def get_numeric_cache(hostname):
"""Get all the numeric cache entries we have for an hostname
"""
return [{
'collection': str(n.template.collection),
'template': str(n.template),
'value': n.value,
'last_modified': n.last_modified,
} for n in NumericCache.objects.filter(h... | 49,242 |
def partition_dataset(
data: Sequence,
ratios: Optional[Sequence[float]] = None,
num_partitions: Optional[int] = None,
shuffle: bool = False,
seed: int = 0,
drop_last: bool = False,
even_divisible: bool = False,
):
"""
Split the dataset into N partitions. It can support shuffle based... | 49,243 |
def test_proxy_with_clear(url_test):
"""检测某链接代理的可用性并清楚无用代理"""
_proxy_list = get_proxy_all().json()
for proxy in _proxy_list:
test_proxy_with_clear_and_url(proxy.get('proxy'), url_test) | 49,244 |
def canopy_PAR_absorbed(states: States, setpoints: Setpoints, weather: Weather):
"""The PAR absorbed by the canopy
Equation 8.26
:return: The PAR absorbed by the canopy [W m^-2]
"""
return canopy_PAR_absorbed_from_greenhouse_cover(states, setpoints, weather) + canopy_PAR_absorbed_from_greenhouse_flo... | 49,245 |
def from_nat(key, val, section, pjsip, nmapped):
"""Sets values from nat into the appropriate pjsip.conf options."""
# nat from sip.conf can be comma separated list of values:
# yes/no, [auto_]force_rport, [auto_]comedia
if 'yes' in val:
set_value('rtp_symmetric', 'yes', section, pjsip, nmapped)... | 49,246 |
def tiff_to_array(tiff):
"""
Open a TIFF file as an array, normalizing the dimensions.
:param tiff: Filename
:return:
"""
array = (
tiff.asarray(out='memmap') if tiff.pages[0].is_memmappable else tiff.asarray()
)
if array.ndim < 3:
array = array[np.newaxis, ...]
retu... | 49,247 |
def factor_costs_for_var(factor: Constraint, variable: Variable, recv_costs, mode: str):
"""
Computes the marginals to be send by a factor to a variable
The content of this message is a table d -> mincost where
* d is a value of the domain of the variable v
* mincost is the minimum value of f when... | 49,248 |
def version():
"""donghuangzhong version"""
return "0.0.1" | 49,249 |
def list_dot(a, b):
"""
Returns the Euclidean inner product of two itterable data-structures.
"""
try:
if len(a) == len(b):
temp = 0
for i in range(len(a)):
temp += a[i]*b[i]
return(temp)
else:
raise ValueError("The length o... | 49,250 |
def pack_bytes(payload):
"""Optimally pack a byte string according to msgpack format"""
pl = len(payload)
if pl < (2**8):
prefix = struct.pack('BB', 0xC4, pl)
elif pl < (2**16):
prefix = struct.pack('>BH', 0xC5, pl)
else:
prefix = struct.pack('>BI', 0xC6, pl)
return prefi... | 49,251 |
def disparity_consistency_src_to_tgt(meshgrid_homo, K_src_inv, disparity_src,
G_tgt_src, K_tgt, disparity_tgt):
"""
:param xyz_src_B3N: Bx3xN
:param G_tgt_src: Bx4x4
:param K_tgt: Bx3x3
:param disparity_tgt: Bx1xHxW
:return:
"""
B, _, H, W = disparit... | 49,252 |
def split (properties):
""" Given a property-set of the form
v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM
Returns
v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM
Note that vN...vM may contain slashes. This is resilient to the
substitution of backslashes for slashes, since Jam, unbidde... | 49,253 |
def _import_one(package_name: str, plugin_name: str) -> None:
"""Import a plugin from a package
This is essentially just a regular python import. As the module is
imported, the _PLUGINS-dict will be populated by @register decorated
function in the file.
Args:
package_name: Name of package... | 49,254 |
def _deduce_state_variables():
"""Deduce the needed invocation context"""
var_names = ('currentAddress', 'currentHighlight', 'currentLocation', 'currentProgram', 'currentSelection', 'state')
"""Sentinel variables that we can use to detect the invocation context"""
for s in inspect.stack():
if i... | 49,255 |
def set_thermo(outfile: str,
thermo_period: int=10000,
rigid=True,
) -> None:
"""Set the thermodynamic quantities for a simulation."""
default = ['N', 'volume', 'momentum', 'temperature', 'pressure',
'potential_energy', 'kinetic_energy',
... | 49,256 |
def abort_behavior(token):
""" Abort behavior identified with the token """
return True, stop_nodenetrunner(behavior_token_map[token]) | 49,257 |
def limit_to_value_max(value_max, value):
"""
:param
1.(int) value_max -- value that should not be exceed
2.(int) value -- actual value
:return
1. return a value in the given range bound with value_max
"""
if value > value_ma... | 49,258 |
def test_gaussian_v1_regression_losses(loss_type):
"""Tests gaussian regression losses v1.
Args:
loss_class (str): type of gaussian loss v1.
"""
pred = torch.rand((10, 5))
target = torch.rand((10, 5))
weight = torch.rand((10, 5))
# Test loss forward with weight
loss = GDLoss_v1... | 49,259 |
def reference_col(
tablename, nullable=False, pk_name="id", foreign_key_kwargs=None, column_kwargs=None
):
"""Column that adds primary key foreign key reference.
Usage: ::
category_id = reference_col('category')
category = relationship('Category', backref='categories')
"""
foreign_... | 49,260 |
def test__traj():
""" test geom.from_xyz_trajectory_string
"""
ref_traj_str = """ 3
comment 1
C 0.000000 0.000000 0.000000
C 0.000000 0.000000 1.000000
C 0.000000 0.000000 2.000000
3
comment 2
C 0.000000 0.000000 3.000000
C 0.000000 0.000000 4.000000
C 0.000000 0.00... | 49,261 |
def set_doctest_env(doctest_namespace):
"""Inject objects into the testing namespace"""
doctest_namespace['numpy'] = numpy | 49,262 |
def extract_municipality_hashtags(df):
""" This function takes a twitter dataframe as an input then the output is the dataframe with 2 new columns namely a hashtag
column and a municipality column.
Example
------
if the tweet contains the @mention '@CityPowerJhb' then the coresponding output in... | 49,263 |
def vertices_homography(vertices, H):
"""Apply projective transformation (homography) on a sequence of points.
Parameters:
vertices: List of (x, y) tuples.
A list for projective transformation.
H: A homography matrix.
Return:
vertices_homo: List of (x, y) tuples.
... | 49,264 |
def SRCNNv2(input_shape, depth_multiplier=1, multi_output=False):
"""
conv 9-64 puis 7-64 puis 5-32 puis 7-1 -> 1.006 120 epoch
conv 9-128 puis 7-64 puis 5-32 puis 7-16 puis 9-1 -> 1.007 130 epoch
@ multi_output : set to True
"""
inputs = Input(input_shape, name="inputs")
conv1 ... | 49,265 |
def parse_labels(string, bb_label_mapping, static_label):
"""Returns array of rectangles geometry and their labels
Arguments:
string {str} -- JSON string
bb_label_mapping {dict} -- Mapping from color to label
static_label {list} -- List of labels valid for the whole image
R... | 49,266 |
def spike_profile(*args, **kwargs):
""" Computes the spike-distance profile :math:`S(t)` of the given
spike trains. Returns the profile as a PieceWiseConstLin object. The
SPIKE-values are defined positive :math:`S(t)>=0`.
Valid call structures::
spike_profile(st1, st2) # returns the bi-variate ... | 49,267 |
def wig_to_dataframe(infile, step, format):
"""Read a wig file into a Pandas dataframe
infile(str): Path to file
Returns:
Dataframe
"""
fs = open(infile, 'r')
coverage_data = []
pos = 0
chr = ""
for line in fs.readlines():
try:
f = float(line)
... | 49,268 |
def get_all_commcare_users_by_domain(domain):
"""Returns all CommCareUsers by domain regardless of their active status"""
from corehq.apps.users.models import CommCareUser
def get_ids():
for flag in ['active', 'inactive']:
key = [flag, domain, CommCareUser.__name__]
for user... | 49,269 |
def writer(path, text):
"""Writes to a file from a string
Handy way of piping a processed namelist into
a file.
:param path: Path to output file
:param text: Input text to process
"""
with open(path, "w") as handle:
handle.write(text) | 49,270 |
def DihedralAngleOfCA(ires,jres,kres,lres):
""" not used """
# dihedral angle of four CA atoms
print 'Use DihedralAngle Method' | 49,271 |
def plot_waveforms(time,voltage,APTimes,titlestr):
"""
plot_waveforms takes four arguments - the recording time array, the voltage
array, the time of the detected action potentials, and the title of your
plot. The function creates a labeled plot showing the waveforms for each
detected action potent... | 49,272 |
def __lldb_init_module(debugger, _):
"""Installs a new debugger handle for formatting hermes values"""
debugger.HandleCommand(
'type summary add "hermes::vm::HermesValue" "hermes::vm::PinnedHermesValue" "hermes::vm::GCHermesValue" -w hermes -F HermesValueFormatter.hv_format'
) | 49,273 |
def print_cycles_info(data):
"""
Print various information about cycles.
"""
n_cycles = len(data.cycles)
output('number of cycles:', n_cycles)
if not n_cycles:
return data
slengths = sorted(set(data.cycles_lengths))
lhist, lbins = np.histogram(data.cycles_lengths,
... | 49,274 |
def plot_figures(output_dict, name, params):
"""Plots the figure from the output."""
figure_dir = os.path.join(FLAGS.output_dir, 'figures')
if not gfile.Exists(figure_dir):
gfile.MakeDirs(figure_dir)
fig = plt.figure()
plt.plot(output_dict['gbt_train_losses'], label='gbt')
plt.plot(output_dict['agbt_b_t... | 49,275 |
def get_block_size(sigma = 1.5):
"""
Devuelve el tamaño de los vecinos (block_size) que se va a utilizar para
obtener los puntos Harris. El valor se fija al valor correspondiente al uso
de máscaras gaussianas de sigma 1.5. El tamaño de la máscara Gaussiana es
6*1.5+1.
"""
return int(6*sigma... | 49,276 |
def load_fixture(filename: str) -> str:
"""Load a fixture."""
path = os.path.join(os.path.dirname(__file__), "fixtures", filename)
with open(path, encoding="utf-8") as fptr:
return fptr.read() | 49,277 |
def approxZeroNewton(f: Callable[[float], float], df: Callable[[float], float], ddf: Callable[[float], float], a: Union[int, float], b: Union[int, float], epsilon: float, iteration: int) -> Tuple[float, int]:
"""
Approximates the solution to f(x) = 0 in range [a, b] using Newton's method
:param f: callable... | 49,278 |
def chain_data(symbol, info=None):
"""Gets chain data for stock. INSTANT. Includes possible expiration dates for options."""
assert type(symbol) == str
return robin_stocks.options.get_chains(symbol, info) | 49,279 |
def convert_Cf2manningn(Cf, h):
"""
Convert the friction coefficient Cf to the Manning's n
"""
n = h**(1 / 6) * np.sqrt(Cf / g)
return n | 49,280 |
def lstmemory_unit(input,
name=None,
size=None,
param_attr=None,
act=None,
gate_act=None,
state_act=None,
mixed_bias_attr=None,
lstm_bias_attr=None,
... | 49,281 |
def _GetPrivateIpv6GoogleAccess(dataproc, private_ipv6_google_access_type):
"""Get PrivateIpv6GoogleAccess enum value.
Converts private_ipv6_google_access_type argument value to
PrivateIpv6GoogleAccess API enum value.
Args:
dataproc: Dataproc API definition
private_ipv6_google_access_type: argument va... | 49,282 |
def retry_(f, ex, times=3, interval=1, on_error=lambda e, x: None, *args, **kwargs):
"""
Call a function and try again if it throws a specified exception.
:param funciton f: The function to retry
:param ex: The class of the exception to catch, or an iterable of classes
:type ex: class or iterable
... | 49,283 |
def pca_analysis(model, data):
"""Run PCA analysis on model to visualize hidden layer activity.
To get the values of the intermediate layer, a new model needs to be
created. This model takes the normal input from the RNN, and returns the
output of the rnn layer. The values of the hidden layer can the... | 49,284 |
def prepare_imports():
""" Prepare any imports for testing run
At the moment, we prepare matplotlib by trying to make it use a backend that
does not need a display
"""
try:
import matplotlib as mpl
except ImportError:
pass
else:
mpl.use('agg') | 49,285 |
def get_plugin_history(name):
"""
Get history of results for single plugin
:param name: name of the plugin
:type name: string
"""
plugin = smokerd.pluginmgr.get_plugin(name)
results = []
for res in plugin.result:
res = standardized_api_list(res)
results.append({'result'... | 49,286 |
def _parse_instance_info(node):
"""Gets the instance and driver specific Node deployment info.
This method validates whether the 'instance_info' and 'driver_info'
property of the supplied node contains the required information for
this driver to deploy images to the node.
:param node: a single Nod... | 49,287 |
def pipe(db_new, db_old, table):
"""新表中默认数据的insert语句"""
res = db_new.query('select * from %s' % table)
if len(res) <= 0:
return []
values = ''
keys = None
_sqls = []
for i, _item in enumerate(res):
# TODO 导入默认数据
if keys is None:
_keys = '`, `'.join(_item.k... | 49,288 |
def test_init_GlobalNet():
"""
Testing init of GlobalNet is built as expected.
"""
# Initialising GlobalNet instance
global_test = g.GlobalNet(
image_size=[1, 2, 3],
out_channels=3,
num_channel_initial=3,
extract_levels=[1, 2, 3],
out_kernel_initializer="softm... | 49,289 |
def str2polynomial(string):
""" Get a string, return a polynomial """
try:
parts = advanced_split(string, '+', '-', contain=True)
terms = [str2term(each) for each in parts]
return Polynomial(*terms)
except:
raise Exception('Example input: -5x_1^2*y_1^3+6x_2^2*y_2^4-x_3^1*y_3^... | 49,290 |
def transpose_2d(array):
"""Transpose an array represented as an iterable of iterables."""
return list(map(list, zip_equal(*array))) | 49,291 |
def get_test_examples(args):
"""See base class."""
src = file2list(args.src_data)
trg = file2list(args.trg_data)
return _create_examples(src, trg, "test") | 49,292 |
def parse_site_config(config_site):
"""
Parse Site level configuration
:param config_site: Site config dict
:return: Tuple of WAN Interface config, LAN Network config, Element Config, DHCP Server config, and
Site Extension config
"""
local_debug("SITE CONFIG: " + str(json.dumps(conf... | 49,293 |
def precrec_unvoted(preds, gts, radius, pred_rphi=False, gt_rphi=False):
"""
The "unvoted" precision/recall, meaning that multiple predictions for the same ground-truth are NOT penalized.
- `preds` an iterable (scans) of iterables (per scan) containing predicted x/y or r/phi pairs.
- `gts` an iterable ... | 49,294 |
def get_weapon_objects(json_load):
"""creates weapon objects by iterating over the json load
and making an object of each dictionary, then returns
a list of all the objects
"""
weapon_object_list = []
for weapon_dict in json_load:
# weapon_dict is a dictionary which has data for one weap... | 49,295 |
def _t_P(P):
"""Define the boundary between Region 2 and 3, T=f(P)
>>> "%.2f" % _t_P(16.52916425)
'623.15'
"""
n=[0, 0.34805185628969e3, -0.11671859879975e1, 0.10192970039326e-2,0.57254459862746e3, 0.1391883977870e2]
return n[4]+((P-n[5])/n[3])**0.5 | 49,296 |
def add_as_function(cls):
""" Decorator for classes. Automatically adds functional interface for `call` method of class.
For example, `ConvBlock` class is transformed into `conv_block` function, while
`Conv1DTranspose` class is transformed into `conv1d_transpose` function.
"""
name = cls.__name__
... | 49,297 |
def rollout(ps, replay_buffer, config):
"""Collect experience using an exploration policy"""
env = gym.make(config["env"])
obs, reward, done, ep_ret, ep_len = env.reset(), 0, False, 0, 0
total_steps = config["steps_per_epoch"] * config["epochs"]
agent = SAC(env.observation_space.shape, env.action_s... | 49,298 |
def remove_from_cart(request):
"""
Remove product from cart
"""
product_id = int(request.POST['product_id'])
# Checking if user session has cart or session may already flushed
# Cart an empty cart for user
if 'cart_id' in request.session:
cart_id = int(request.session['cart_id'])
... | 49,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.