file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
lookup_service.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package internal
import (
"errors"
"fmt"
"net/url"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/gogo/protobuf/proto"
"github.com/TencentCloud/tdmq-go-client/pulsar/log"
pb "github.com/TencentCloud/tdmq-go-client/pulsar/internal/pulsar_proto"
)
var (
lookupRequestsCount = promauto.NewCounter(prometheus.CounterOpts{
Name: "pulsar_client_lookup_count",
Help: "Counter of lookup requests made by the client",
})
)
// LookupResult encapsulates a struct for lookup a request, containing two parts: LogicalAddr, PhysicalAddr.
type LookupResult struct {
LogicalAddr *url.URL
PhysicalAddr *url.URL
}
// LookupService is a interface of lookup service.
type LookupService interface {
// Lookup perform a lookup for the given topic, confirm the location of the broker
// where the topic is located, and return the LookupResult.
Lookup(topic string) (*LookupResult, error)
}
type lookupService struct {
rpcClient RPCClient
serviceURL *url.URL
tlsEnabled bool
listenerName string
log log.Logger
}
// NewLookupService init a lookup service struct and return an object of LookupService.
func NewLookupService(rpcClient RPCClient, serviceURL *url.URL, tlsEnabled bool, listenerName string, logger log.Logger) LookupService {
return &lookupService{
rpcClient: rpcClient,
serviceURL: serviceURL,
tlsEnabled: tlsEnabled,
listenerName: listenerName,
log: logger.SubLogger(log.Fields{"serviceURL": serviceURL}),
}
}
func (ls *lookupService) getBrokerAddress(lr *pb.CommandLookupTopicResponse) (logicalAddress *url.URL,
physicalAddress *url.URL, err error) {
if ls.tlsEnabled {
logicalAddress, err = url.ParseRequestURI(lr.GetBrokerServiceUrlTls())
} else {
logicalAddress, err = url.ParseRequestURI(lr.GetBrokerServiceUrl())
}
if err != nil {
return nil, nil, err
}
var physicalAddr *url.URL
if lr.GetProxyThroughServiceUrl() | else {
physicalAddr = logicalAddress
}
return logicalAddress, physicalAddr, nil
}
// Follow brokers redirect up to certain number of times
const lookupResultMaxRedirect = 20
func (ls *lookupService) Lookup(topic string) (*LookupResult, error) {
lookupRequestsCount.Inc()
id := ls.rpcClient.NewRequestID()
res, err := ls.rpcClient.RequestToAnyBroker(id, pb.BaseCommand_LOOKUP, &pb.CommandLookupTopic{
RequestId: &id,
Topic: &topic,
Authoritative: proto.Bool(false),
AdvertisedListenerName: proto.String(ls.listenerName),
})
if err != nil {
return nil, err
}
ls.log.Debugf("Got topic{%s} lookup response: %+v", topic, res)
for i := 0; i < lookupResultMaxRedirect; i++ {
lr := res.Response.LookupTopicResponse
switch *lr.Response {
case pb.CommandLookupTopicResponse_Redirect:
logicalAddress, physicalAddr, err := ls.getBrokerAddress(lr)
if err != nil {
return nil, err
}
ls.log.Debugf("Follow topic{%s} redirect to broker. %v / %v - Use proxy: %v",
topic, lr.BrokerServiceUrl, lr.BrokerServiceUrlTls, lr.ProxyThroughServiceUrl)
id := ls.rpcClient.NewRequestID()
res, err = ls.rpcClient.Request(logicalAddress, physicalAddr, id, pb.BaseCommand_LOOKUP, &pb.CommandLookupTopic{
RequestId: &id,
Topic: &topic,
Authoritative: lr.Authoritative,
AdvertisedListenerName: proto.String(ls.listenerName),
})
if err != nil {
return nil, err
}
// Process the response at the top of the loop
continue
case pb.CommandLookupTopicResponse_Connect:
ls.log.Debugf("Successfully looked up topic{%s} on broker. %s / %s - Use proxy: %t",
topic, lr.GetBrokerServiceUrl(), lr.GetBrokerServiceUrlTls(), lr.GetProxyThroughServiceUrl())
logicalAddress, physicalAddress, err := ls.getBrokerAddress(lr)
if err != nil {
return nil, err
}
return &LookupResult{
LogicalAddr: logicalAddress,
PhysicalAddr: physicalAddress,
}, nil
case pb.CommandLookupTopicResponse_Failed:
errorMsg := ""
if lr.Error != nil {
errorMsg = lr.Error.String()
}
ls.log.Warnf("Failed to lookup topic: %s, error msg: %s", topic, errorMsg)
return nil, fmt.Errorf("failed to lookup topic: %s", errorMsg)
}
}
return nil, errors.New("exceeded max number of redirection during topic lookup")
}
| {
physicalAddr = ls.serviceURL
} |
mod.rs | // Copyright (c) 2017 fd developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use regex_syntax::hir::Hir;
use regex_syntax::ParserBuilder;
pub use self::file_types::FileTypes;
macro_rules! print_error {
($($arg:tt)*) => (eprintln!("[fd error]: {}", format!($($arg)*)))
}
macro_rules! print_error_and_exit {
($($arg:tt)*) => {
print_error!($($arg)*);
::std::process::exit(1);
};
}
mod file_types;
pub mod opts;
pub mod filter;
#[cfg(unix)]
pub fn osstr_to_bytes(input: &OsStr) -> Cow<[u8]> {
use std::os::unix::ffi::OsStrExt;
Cow::Borrowed(input.as_bytes())
}
#[cfg(windows)]
pub fn osstr_to_bytes(input: &OsStr) -> Cow<[u8]> {
let string = input.to_string_lossy();
match string {
Cow::Owned(string) => Cow::Owned(string.into_bytes()),
Cow::Borrowed(string) => Cow::Borrowed(string.as_bytes()),
}
}
/// Determine if a regex pattern contains a literal uppercase character.
pub fn pattern_has_uppercase_char(pattern: &str) -> bool {
let mut parser = ParserBuilder::new().allow_invalid_utf8(true).build();
parser
.parse(pattern)
.map(|hir| hir_has_uppercase_char(&hir))
.unwrap_or(false)
}
/// Determine if a regex expression contains a literal uppercase character.
fn hir_has_uppercase_char(hir: &Hir) -> bool {
use regex_syntax::hir::*;
match *hir.kind() {
HirKind::Literal(Literal::Unicode(c)) => c.is_uppercase(),
HirKind::Literal(Literal::Byte(b)) => char::from(b).is_uppercase(),
HirKind::Class(Class::Unicode(ref ranges)) => ranges
.iter()
.any(|r| r.start().is_uppercase() || r.end().is_uppercase()),
HirKind::Class(Class::Bytes(ref ranges)) => ranges
.iter()
.any(|r| char::from(r.start()).is_uppercase() || char::from(r.end()).is_uppercase()),
HirKind::Group(Group { ref hir, .. }) | HirKind::Repetition(Repetition { ref hir, .. }) => {
hir_has_uppercase_char(hir)
}
HirKind::Concat(ref hirs) | HirKind::Alternation(ref hirs) => {
hirs.iter().any(hir_has_uppercase_char)
}
_ => false,
}
}
/// Maximum size of the output buffer before flushing results to the console
pub const MAX_BUFFER_LENGTH: usize = 1000;
/// Traverse args_os, looking for -exec and replacing it with --exec.
///
/// # Returns
///
/// * The args, with substitution if required
pub fn transform_args_with_exec<I>(original: I) -> Vec<OsString>
where
I: Iterator<Item = OsString>,
{
let mut in_exec_opt = false;
let target = OsString::from("-exec");
let long_start = OsString::from("--exec");
let short_start = OsString::from("-x");
let exec_end = OsString::from(";");
original.fold(vec![], |mut args, curr| {
if in_exec_opt {
if curr == exec_end {
in_exec_opt = false;
}
args.push(curr);
return args;
}
if curr == target || curr == long_start || curr == short_start {
args.push(if curr == target {
OsString::from("--exec")
} else {
curr
});
in_exec_opt = true;
} else {
args.push(curr);
}
args
})
}
#[cfg(test)]
mod tests {
use super::*;
fn oss_vec(strs: &[&str]) -> Vec<OsString> {
strs.into_iter().map(OsString::from).collect()
}
/// Ensure that -exec gets transformed into --exec
#[test]
fn normal_exec_substitution() {
let original = oss_vec(&["fd", "foo", "-exec", "cmd"]);
let expected = oss_vec(&["fd", "foo", "--exec", "cmd"]);
let actual = transform_args_with_exec(original.into_iter());
assert_eq!(expected, actual);
}
/// Ensure that --exec is not touched
#[test]
fn passthru_of_original_exec() {
let original = oss_vec(&["fd", "foo", "--exec", "cmd"]);
let expected = oss_vec(&["fd", "foo", "--exec", "cmd"]);
let actual = transform_args_with_exec(original.into_iter());
assert_eq!(expected, actual);
}
#[test]
fn temp_check_that_exec_context_observed() {
let original = oss_vec(&[
"fd",
"foo",
"-exec",
"cmd",
"-exec",
"ls",
";",
"-exec",
"rm",
";",
"--exec",
"find",
"-exec",
"rm",
";",
"-x",
"foo",
"-exec",
"something",
";",
"-exec",
]);
let expected = oss_vec(&[
"fd",
"foo",
"--exec",
"cmd",
"-exec",
"ls",
";",
"--exec",
"rm",
";",
"--exec",
"find",
"-exec",
"rm",
";",
"-x", | "something",
";",
"--exec",
]);
let actual = transform_args_with_exec(original.into_iter());
assert_eq!(expected, actual);
}
} | "foo",
"-exec", |
images.py | import datetime
import hashlib
import json
import numpy as np
import pandas as pd
import tifffile
def timestamp():
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
class MicroManagerTIFF:
def __init__(self, src_filepath, verbose=True):
'''
'''
self.verbose = verbose
self.src_filepath = src_filepath
self.events = []
self.global_metadata = {'processing_timestamp': timestamp()}
self.open_tiff()
def event_logger(self, message):
'''
'''
if self.verbose:
print('EVENT: %s' % message)
self.events.append({'message': message, 'timestamp': timestamp()})
def save_events(self, dst_filepath):
if not self.events:
return
pd.DataFrame(data=self.events).to_csv(dst_filepath, index=False)
def save_global_metadata(self, dst_filepath):
with open(dst_filepath, 'w') as file:
json.dump(self.global_metadata, file)
def save_mm_metadata(self, dst_filepath):
self.mm_metadata.to_csv(dst_filepath, index=False)
def calc_hash(self):
'''
Calculate the sha1 hash from the file contents
'''
sha1 = hashlib.sha1()
with open(self.src_filepath, 'rb') as file:
sha1.update(file.read())
hash_value = sha1.hexdigest()
self.global_metadata['sha1_hash'] = hash_value
return hash_value
def open_tiff(self):
'''
Open the stack using tifffile.TiffFile
'''
self.tiff = tifffile.TiffFile(self.src_filepath)
@staticmethod
def _parse_mm_tag_schema_v1(mm_tag):
'''
Parse a MicroManagerMetadata tag in the 'old' schema
(KC: I believe this schema corresponds to MicroManager 1.x)
'''
metadata = {
'slice_ind': mm_tag['SliceIndex'],
'frame_ind': mm_tag['FrameIndex'],
'channel_ind': mm_tag['ChannelIndex'],
'position_ind': mm_tag['PositionIndex'],
'exposure_time': mm_tag['AndorEMCCD-Exposure'],
'laser_status_405': mm_tag['AndorILE-A-Laser 405-Power Enable'],
'laser_power_405': mm_tag['AndorILE-A-Laser 405-Power Setpoint'],
'laser_status_488': mm_tag['AndorILE-A-Laser 488-Power Enable'],
'laser_power_488': mm_tag['AndorILE-A-Laser 488-Power Setpoint'],
}
return metadata
@staticmethod
def _parse_mm_tag_schema_v2(mm_tag):
'''
Parse a MicroManagerMetadata tag in the 'new' schema
(KC: I believe this schema corresponds to MicroManager 2.x)
'''
metadata = {
'slice_ind': mm_tag['SliceIndex'],
'frame_ind': mm_tag['FrameIndex'],
'channel_ind': mm_tag['ChannelIndex'],
'position_ind': mm_tag['PositionIndex'],
'exposure_time': mm_tag.get('Andor EMCCD-Exposure')['PropVal'],
'laser_status_405': mm_tag.get('Andor ILE-A-Laser 405-Power Enable')['PropVal'],
'laser_power_405': mm_tag.get('Andor ILE-A-Laser 405-Power Setpoint')['PropVal'],
'laser_status_488': mm_tag.get('Andor ILE-A-Laser 488-Power Enable')['PropVal'],
'laser_power_488': mm_tag.get('Andor ILE-A-Laser 488-Power Setpoint')['PropVal'],
}
return metadata
def parse_micromanager_metadata(self):
'''
Parse the MicroManager metadata for each page in the TIFF file
'''
# the IJMetadata appears only in the first page
ij_metadata = None
try:
ij_metadata = self.tiff.pages[0].tags['IJMetadata'].value['Info']
except Exception:
self.event_logger('There was no IJMetadata tag found on the first page')
if ij_metadata is not None:
try:
ij_metadata = json.loads(ij_metadata)
except Exception:
self.event_logger('IJMetadata could not be parsed by json.loads')
mm_metadata_rows = []
for ind, page in enumerate(self.tiff.pages):
mm_metadata_row = {
'page_ind': ind,
'error': False
}
mm_tag = page.tags.get('MicroManagerMetadata')
if not isinstance(mm_tag, tifffile.tifffile.TiffTag):
self.event_logger('There was no MicroManagerMetadata tag found on page %s' % ind)
mm_metadata_row['error'] = True
mm_metadata_rows.append(mm_metadata_row)
continue
try:
page_metadata_v1 = self._parse_mm_tag_schema_v1(mm_tag.value)
except Exception:
page_metadata_v1 = None
try:
page_metadata_v2 = self._parse_mm_tag_schema_v2(mm_tag.value)
except Exception:
page_metadata_v2 = None
| page_metadata = page_metadata_v1
elif page_metadata_v2 is not None:
mm_metadata_version = 'v2'
page_metadata = page_metadata_v2
else:
mm_metadata_row['error'] = True
self.event_logger('Unable to parse MicroManagerMetadata tag from page %s' % ind)
mm_metadata_rows.append({**mm_metadata_row, **page_metadata})
self.mm_metadata = pd.DataFrame(data=mm_metadata_rows)
self.global_metadata['mm_metadata_version'] = mm_metadata_version
class RawPipelineTIFF(MicroManagerTIFF):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# the channels we expect to find in a Pipeline-like TIFF
self.laser_405 = '405'
self.laser_488 = '488'
def validate_micromanager_metadata(self):
'''
Validate the parsed MicroManager metadata tags for a raw Pipeline-like TIFF file
(these are TIFFs found in the 'PlateMicroscopy' directory)
Generates validated_mm_metadata and sets various flags
that determine whether and how to split the pages into the 405 and 488 channels
Steps
------
- drop rows with any NAs
- check that the dropped rows had a parsing error
- check for two channel_inds and an equal number of pages from each
- if there are no channel_inds, check for an even number of pages
- if there are two channel_inds, check that slice_inds
and exposure settings are consistent within each channel
'''
# whether the MM metadata has two channel inds with an equal number of slices
self.has_valid_channel_inds = False
# whether the MM metadata for each channel has slice_inds that increment by one
self.has_valid_slice_inds = False
# whether it is safe to split the TIFF stack into channels by splitting the pages in half,
# when there are not valid channel inds
self.safe_to_split_in_half = False
md = self.mm_metadata.copy()
# remove the error flag column
errors = md['error']
md = md.drop(labels='error', axis=1)
# drop rows with NAs in any of the columns parsed from the MicroManagerMetadata tag
parsed_columns = set(md.columns).difference(['page_ind'])
md = md.dropna(how='any', subset=parsed_columns, axis=0)
# check that the dropped rows had an error
# (note that 'error' means either there was no MM tag or it could not be parsed)
num_error_rows = errors.sum()
num_dropped_rows = self.mm_metadata.shape[0] - md.shape[0]
if num_dropped_rows != num_error_rows:
self.event_logger(
'%s rows with NAs were dropped but %s rows had errors'
% (num_dropped_rows, num_error_rows)
)
# check that we can coerce the parsed columns as expected
int_columns = ['slice_ind', 'channel_ind']
for column in int_columns:
md[column] = md[column].apply(int)
float_columns = ['laser_power_405', 'laser_power_488', 'exposure_time']
for column in float_columns:
md[column] = md[column].apply(float)
# if there are two distinct channels, we assign the first to 405 and the second to 488
self.channel_inds = None
unique_channel_inds = sorted(md.channel_ind.unique())
if len(unique_channel_inds) == 2:
self.channel_inds = {
self.laser_405: min(unique_channel_inds),
self.laser_488: max(unique_channel_inds),
}
# if there are three channel_inds, we assume the third channel is brightfield
elif set(unique_channel_inds) == set([0, 1, 2]):
self.event_logger('There were three channel inds')
self.channel_inds = {
self.laser_405: 0,
self.laser_488: 1,
}
# if there's one channel index, check for an even number of pages
elif len(unique_channel_inds) == 1:
if np.mod(md.shape[0], 2) == 0:
self.safe_to_split_in_half = True
else:
self.event_logger('There is one channel_ind and an odd number of pages')
else:
self.event_logger('Unexpected number of channel_inds (%s)' % unique_channel_inds)
# if there were valid channel_inds, check for an equal number of pages from each channel
if self.channel_inds is not None:
num_405 = (md.channel_ind == self.channel_inds[self.laser_405]).sum()
num_488 = (md.channel_ind == self.channel_inds[self.laser_488]).sum()
if num_405 == num_488:
self.has_valid_channel_inds = True
else:
self.event_logger(
'Channels have unequal number of slices: %s and %s' % (num_405, num_488)
)
# in each channel, check that slice_ind increments by 1.0
# and that exposure time and laser power are consistent
for channel_ind in unique_channel_inds:
md_channel = md.loc[md.channel_ind == channel_ind]
steps = np.unique(np.diff(md_channel.slice_ind))
# check that slice inds are contiguous
if len(steps) == 1 and steps[0] == 1:
self.has_valid_slice_inds = True
elif len(steps) == 1:
self.event_logger(
'Unexpected slice_ind increment %s for channel_ind %s'
% (steps[0], channel_ind)
)
elif len(steps) > 1:
self.event_logger(
'The slice_inds are not contiguous for channel_ind %s' % channel_ind
)
for column in float_columns:
steps = np.unique(np.diff(md_channel[column]))
if len(steps) > 1 or steps[0] != 0:
self.event_logger(
'Inconsistent values found in column %s for channel_ind %s'
% (column, channel_ind)
)
self.validated_mm_metadata = md
@staticmethod
def tag_and_coerce_metadata(row, tag):
'''
Transform `row` to a dict, prepend the keys with `tag`,
and do some hackish type coercion
'''
d = {}
for key, val in dict(row).items():
key = '%s_%s' % (key, tag)
try:
val = float(val)
except Exception:
pass
d[key] = val
return d
def split_channels(self):
'''
Split the pages of the pipeline-like TIFF into 405 and 488 channels
to construct the z-stack for each channel and, if possible,
extract the channel-specific MM metadata (i.e., exposure time and laser power)
Overview
--------
In a perfect world, this would be easy: we would simple use the two unique channel_inds
to split the pages by channel (and verify the page order using the slice_inds).
Unfortunately, due to a bug, the MM metadata tag in some TIFFs is the same on every page
(this is notably true for 'disentangled' TIFFs from Plates 16,17,18).
In these cases, we split the tiff into channels simply by splitting the pages in half.
Note that we use the flags set in self.validate_mm_metadata to determine
which of these methods to use.
Assignment of channels
----------------------
When there are two valid channel_inds, the 405 laser is assigned
to the lower channel_ind (which is either 0 or -1).
When there are no channel_inds, the 405 laser is assigned
to the first half of the pages.
'''
self.did_split_channels = True
self.stacks = {}
md = self.validated_mm_metadata.copy()
if self.has_valid_channel_inds:
for channel_name in (self.laser_405, self.laser_488):
channel_md = md.loc[md.channel_ind == self.channel_inds[channel_name]]
self.global_metadata.update(
self.tag_and_coerce_metadata(channel_md.iloc[0], tag=channel_name)
)
self.stacks[channel_name] = self.concat_pages(channel_md.page_ind.values)
elif self.safe_to_split_in_half:
n = int(md.shape[0]/2)
self.stacks[self.laser_405] = self.concat_pages(md.iloc[:n].page_ind.values)
self.stacks[self.laser_488] = self.concat_pages(md.iloc[n:].page_ind.values)
else:
self.event_logger('Unable to safely split pages by channel')
self.did_split_channels = False
def concat_pages(self, page_inds):
'''
'''
stack = np.array([self.tiff.pages[ind].asarray() for ind in page_inds])
return stack
def project_stack(self, channel_name, axis, dst_filepath=None):
'''
Generate x-, y-, or z-projections and log the max and min intensities
'''
axis_inds = {'x': 1, 'y': 2, 'z': 0}
if axis not in axis_inds.keys():
raise ValueError("Axis must be one of 'x', 'y', or 'z'")
axis_ind = axis_inds[axis]
try:
proj = self.stacks[channel_name].max(axis=axis_ind)
minmax = {
'min_intensity': int(proj.min()),
'max_intensity': int(proj.max()),
}
self.global_metadata.update(self.tag_and_coerce_metadata(minmax, tag=channel_name))
if dst_filepath is not None:
tifffile.imsave(dst_filepath, proj)
except Exception:
self.event_logger(
'An error occured while %s-projecting the %s channel' % (axis, channel_name)
)
def calculate_z_profiles(self, channel):
'''
Calculate various statistics of the intensities for each z-slice
'''
stack = self.stacks[channel]
return {
'min': np.array([zslice.min() for zslice in stack]).astype(int),
'max': np.array([zslice.max() for zslice in stack]).astype(int),
'mean': np.array([zslice.mean() for zslice in stack]).astype(int),
'p9999': np.array([np.percentile(zslice, 99.99) for zslice in stack]).astype(int),
}
@staticmethod
def find_cell_layer(stack):
'''
Estimate the center of the cell layer using the center of mass
of the z-profile of the mean intensity of the Hoechst staining
'''
# z-profile of the mean intensity in the Hoechst channel
raw_profile = np.array([zslice.mean() for zslice in stack]).astype(float)
profile = raw_profile - raw_profile.mean()
profile[profile < 0] = 0
x = np.arange(len(profile))
center_of_mass = (profile * x).sum()/profile.sum()
return center_of_mass, raw_profile
def align_cell_layer(
self, cell_layer_bottom, cell_layer_top, step_size, bottom_wiggle_room=0
):
'''
Approximately align the 405 and 488 stacks to correct for chromatic aberration,
and crop around the cell layer so that it is in the center of the stack
cell_layer_bottom : the position of the bottom of the cell layer, in microns,
relative to the center of the cell layer (should be negative)
cell_layer_top : the position of the top of cell layer, in microns,
relative to the center (should be positive)
step_size : the z-step size of the stack (in microns)
(note that the step size is not included in the MicroManager metadata,
so it must be provided by the user)
bottom_wiggle_room : optional 'wiggle room', in microns, for the cell_layer_bottom;
if the actual bottom of the stack is within this distance of cell_layer_bottom,
the stack is still cropped, and the bottom of the cropped stack padded with zeros.
For example, if cell_layer_bottom is -5um but the actual bottom is at -4.5um,
setting bottom_wiggle_room to 1um would allow the stack to be cropped
(because -4.5 + 5 < 1)
'''
stacks = {}
result = {}
stack_405 = self.stacks[self.laser_405].copy()
stack_488 = self.stacks[self.laser_488].copy()
# hard-coded chromatic aberration offset in microns
# this is an empirically estimated median offset,
# obtained by inspecting z-stacks from nucleus-localized targets
chromatic_aberration_offset = 1.0
offset_ind = int(chromatic_aberration_offset/step_size)
stack_405 = stack_405[:-offset_ind, :, :]
stack_488 = stack_488[offset_ind:, :, :]
# estimate the cell layer center and round it the nearest z-slice
cell_layer_center, _ = self.find_cell_layer(stack_405)
cell_layer_center = np.round(cell_layer_center)
# absolute position, in number of z-slices, of the top and bottom of the cell layer
bottom_ind = int(np.floor(cell_layer_center + cell_layer_bottom/step_size))
top_ind = int(np.ceil(cell_layer_center + cell_layer_top/step_size))
# log some parameters (for debugging, mostly)
result['padded'] = False
result['stack_shape'] = stack_405.shape
result['crop_window'] = [bottom_ind, top_ind]
result['cell_layer_center'] = cell_layer_center
result['chromatic_aberration_offset'] = offset_ind
pad_depth = None
if bottom_ind < 0:
if abs(bottom_ind) <= np.round(bottom_wiggle_room/step_size):
pad_depth = abs(bottom_ind)
bottom_ind = 0
else:
result['error'] = 'The cell layer center was too close to the bottom of the stack'
return stacks, result
if top_ind >= stack_405.shape[0]:
result['error'] = 'The cell layer center was too close to the top of the stack'
return stacks, result
stack_405 = stack_405[bottom_ind:top_ind, :, :]
stack_488 = stack_488[bottom_ind:top_ind, :, :]
# pad the bottom of the stack if necessary
if pad_depth:
result['padded'] = True
result['pad_depth'] = pad_depth
padding = np.zeros((pad_depth, *stack_405.shape[1:]), dtype=stack_405.dtype)
stack_405 = np.concatenate((padding, stack_405), axis=0)
stack_488 = np.concatenate((padding, stack_488), axis=0)
stacks = {'405': stack_405, '488': stack_488}
return stacks, result | page_metadata = {}
mm_metadata_version = None
if page_metadata_v1 is not None:
mm_metadata_version = 'v1' |
mem.rs | use std::io::{Read, Write};
use std::result;
use persistent_log::{Error, Log};
use {LogIndex, ServerId, Term};
/// This is a `Log` implementation that stores entries in a simple in-memory vector. Other data
/// is stored in a struct. It is chiefly intended for testing.
///
/// # Panic
///
/// No bounds checking is performed and attempted access to non-existing log
/// indexes will panic.
#[derive(Clone, Debug)]
pub struct MemLog {
current_term: Term,
voted_for: Option<ServerId>,
entries: Vec<(Term, Vec<u8>)>,
}
impl MemLog {
pub fn new() -> MemLog {
MemLog {
current_term: Term(0),
voted_for: None,
entries: Vec::new(),
}
}
}
impl Log for MemLog {
type Error = Error;
fn current_term(&self) -> result::Result<Term, Error> {
Ok(self.current_term)
}
fn set_current_term(&mut self, term: Term) -> result::Result<(), Error> {
self.voted_for = None;
self.current_term = term;
Ok(())
}
fn inc_current_term(&mut self) -> result::Result<Term, Error> {
self.voted_for = None;
self.current_term = self.current_term + 1;
self.current_term()
}
fn voted_for(&self) -> result::Result<Option<ServerId>, Error> {
Ok(self.voted_for)
}
fn set_voted_for(&mut self, address: ServerId) -> result::Result<(), Error> {
self.voted_for = Some(address);
Ok(())
}
fn latest_log_index(&self) -> result::Result<LogIndex, Error> {
Ok(LogIndex(self.entries.len() as u64))
}
fn latest_log_term(&self) -> result::Result<Term, Error> {
let len = self.entries.len();
if len == 0 {
Ok(Term::from(0))
} else {
Ok(self.entries[len - 1].0)
}
}
fn entry<W: Write>(&self, index: LogIndex, buf: Option<W>) -> Result<Term, Error> {
match self.entries.get((index - 1).as_u64() as usize) {
Some(&(term, ref bytes)) => {
if let Some(mut buf) = buf {
buf.write_all(&bytes)?;
};
Ok(term)
}
None => Err(Error::BadIndex),
}
}
fn append_entries<R: Read, I: Iterator<Item = (Term, R)>>(
&mut self,
from: LogIndex,
entries: I,
) -> result::Result<(), Self::Error> {
if self.latest_log_index()? + 1 < from {
return Err(Error::BadLogIndex);
}
// TODO remove vector hack
let mut entries_vec = Vec::new();
for (term, mut reader) in entries {
let mut v = Vec::new();
reader.read_to_end(&mut v)?;
entries_vec.push((term, v));
}
self.entries.truncate((from - 1).as_u64() as usize);
self.entries.extend(entries_vec.into_iter());
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
use persistent_log::{append_entries, get_entry, Log};
use {LogIndex, ServerId, Term};
#[test]
fn test_current_term() {
let mut store = MemLog::new();
assert_eq!(Term(0), store.current_term().unwrap());
store.set_voted_for(ServerId::from(0)).unwrap();
store.set_current_term(Term(42)).unwrap();
assert_eq!(None, store.voted_for().unwrap());
assert_eq!(Term(42), store.current_term().unwrap());
store.inc_current_term().unwrap();
assert_eq!(Term(43), store.current_term().unwrap());
}
#[test]
fn test_voted_for() {
let mut store = MemLog::new();
assert_eq!(None, store.voted_for().unwrap());
let id = ServerId::from(0);
store.set_voted_for(id).unwrap();
assert_eq!(Some(id), store.voted_for().unwrap());
}
#[test]
fn test_append_entries() {
let mut store = MemLog::new();
assert_eq!(LogIndex::from(0), store.latest_log_index().unwrap());
assert_eq!(Term::from(0), store.latest_log_term().unwrap());
// [0.1, 0.2, 0.3, 1.4]
append_entries(
&mut store,
LogIndex(1),
&[
(Term::from(0), &[1]),
(Term::from(0), &[2]),
(Term::from(0), &[3]),
(Term::from(1), &[4]),
],
).unwrap();
assert_eq!(LogIndex::from(4), store.latest_log_index().unwrap());
assert_eq!(Term::from(1), store.latest_log_term().unwrap());
assert_eq!(
(Term::from(0), vec![1u8]),
get_entry(&store, LogIndex::from(1))
);
assert_eq!(
(Term::from(0), vec![2u8]),
get_entry(&store, LogIndex::from(2))
);
assert_eq!(
(Term::from(0), vec![3u8]),
get_entry(&store, LogIndex::from(3))
);
assert_eq!(
(Term::from(1), vec![4u8]),
get_entry(&store, LogIndex::from(4))
);
// [0.1, 0.2, 0.3]
append_entries(&mut store, LogIndex::from(4), &[]).unwrap();
assert_eq!(LogIndex(3), store.latest_log_index().unwrap());
assert_eq!(Term::from(0), store.latest_log_term().unwrap());
assert_eq!(
(Term::from(0), vec![1u8]),
get_entry(&store, LogIndex::from(1))
);
assert_eq!(
(Term::from(0), vec![2u8]),
get_entry(&store, LogIndex::from(2))
);
assert_eq!(
(Term::from(0), vec![3u8]),
get_entry(&store, LogIndex::from(3))
);
// [0.1, 0.2, 2.3, 3.4]
append_entries(
&mut store,
LogIndex::from(3),
&[(Term(2), &[3]), (Term(3), &[4])],
).unwrap();
assert_eq!(LogIndex(4), store.latest_log_index().unwrap());
assert_eq!(Term::from(3), store.latest_log_term().unwrap());
assert_eq!(
(Term::from(0), vec![1u8]),
get_entry(&store, LogIndex::from(1))
);
assert_eq!(
(Term::from(0), vec![2u8]),
get_entry(&store, LogIndex::from(2))
);
assert_eq!(
(Term::from(2), vec![3u8]),
get_entry(&store, LogIndex::from(3))
);
assert_eq!(
(Term::from(3), vec![4u8]),
get_entry(&store, LogIndex::from(4))
);
}
}
impl Default for MemLog {
fn | () -> Self {
MemLog::new()
}
}
| default |
hitoshi.py | from zipline.pipeline import Pipeline
from zipline.api import attach_pipeline, pipeline_output
from zipline.pipeline.data.equity_pricing import USEquityPricing
from zipline.pipeline.data import morningstar
from zipline.pipeline.factors import SimpleMovingAverage, AverageDollarVolume
from zipline.pipeline.filters.morningstar import IsPrimaryShare
import numpy as np # needed for NaN handling
import math # ceil and floor are useful for rounding
from itertools import cycle
def initialize(context):
# set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.50))
set_slippage(
slippage.VolumeShareSlippage(
volume_limit=.20,
price_impact=0.0))
# set_slippage(slippage.FixedSlippage(spread=0.00))
set_commission(commission.PerTrade(cost=0.00))
# set_slippage(slippage.FixedSlippage(spread=0.00))
set_long_only()
context.MaxCandidates = 100
context.MaxBuyOrdersAtOnce = 30
context.MyLeastPrice = 3.00
context.MyMostPrice = 25.00
context.MyFireSalePrice = context.MyLeastPrice
context.MyFireSaleAge = 6
# over simplistic tracking of position age
context.age = {}
print(len(context.portfolio.positions))
# Rebalance
EveryThisManyMinutes = 10
TradingDayHours = 6.5
TradingDayMinutes = int(TradingDayHours * 60)
for minutez in xrange(
1,
TradingDayMinutes,
EveryThisManyMinutes
):
schedule_function(
my_rebalance,
date_rules.every_day(),
time_rules.market_open(
minutes=minutez))
# Prevent excessive logging of canceled orders at market close.
schedule_function(
cancel_open_orders,
date_rules.every_day(),
time_rules.market_close(
hours=0,
minutes=1))
# Record variables at the end of each day.
schedule_function(
my_record_vars,
date_rules.every_day(),
time_rules.market_close())
# Create our pipeline and attach it to our algorithm.
my_pipe = make_pipeline(context)
attach_pipeline(my_pipe, 'my_pipeline')
def make_pipeline(context):
"""
Create our pipeline.
"""
# Filter for primary share equities. IsPrimaryShare is a built-in filter.
primary_share = IsPrimaryShare()
# Equities listed as common stock (as opposed to, say, preferred stock).
# 'ST00000001' indicates common stock.
common_stock = morningstar.share_class_reference.security_type.latest.eq(
'ST00000001')
# Non-depositary receipts. Recall that the ~ operator inverts filters,
# turning Trues into Falses and vice versa
not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest
# Equities not trading over-the-counter.
not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith(
'OTC') | not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')
# Equities without LP in their name, .matches does a match using a regular
# expression
not_lp_name = ~morningstar.company_reference.standard_name.latest.matches(
'.* L[. ]?P.?$')
# Equities with a null value in the limited_partnership Morningstar
# fundamental field.
not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()
# Equities whose most recent Morningstar market cap is not null have
# fundamental data and therefore are not ETFs.
have_market_cap = morningstar.valuation.market_cap.latest.notnull()
# At least a certain price
price = USEquityPricing.close.latest
AtLeastPrice = (price >= context.MyLeastPrice)
AtMostPrice = (price <= context.MyMostPrice)
# Filter for stocks that pass all of our previous filters.
tradeable_stocks = (
primary_share
& common_stock
& not_depositary
& not_otc
& not_wi
& not_lp_name
& not_lp_balance_sheet
& have_market_cap
& AtLeastPrice
& AtMostPrice
)
LowVar = 6
HighVar = 40
log.info(
'''
Algorithm initialized variables:
context.MaxCandidates %s
LowVar %s
HighVar %s''' %
(context.MaxCandidates, LowVar, HighVar))
# High dollar volume filter.
base_universe = AverageDollarVolume(
window_length=20,
mask=tradeable_stocks
).percentile_between(LowVar, HighVar)
# Short close price average.
ShortAvg = SimpleMovingAverage(
inputs=[USEquityPricing.close],
window_length=3,
mask=base_universe
)
# Long close price average.
LongAvg = SimpleMovingAverage(
inputs=[USEquityPricing.close],
window_length=45,
mask=base_universe
)
percent_difference = (ShortAvg - LongAvg) / LongAvg
# Filter to select securities to long.
stocks_worst = percent_difference.bottom(context.MaxCandidates)
securities_to_trade = (stocks_worst)
return Pipeline(
columns={
'stocks_worst': stocks_worst
},
screen=(securities_to_trade),
)
def my_compute_weights(context):
"""
Compute ordering weights.
"""
# Compute even target weights for our long positions and short positions.
stocks_worst_weight = 1.00 / len(context.stocks_worst)
return stocks_worst_weight
def before_trading_start(context, data):
# Gets our pipeline output every day.
context.output = pipeline_output('my_pipeline')
context.stocks_worst = context.output[
context.output['stocks_worst']].index.tolist()
context.stocks_worst_weight = my_compute_weights(context)
context.MyCandidate = cycle(context.stocks_worst)
context.LowestPrice = context.MyLeastPrice # reset beginning of day
print(len(context.portfolio.positions))
for stock in context.portfolio.positions:
CurrPrice = float(data.current([stock], 'price'))
if CurrPrice < context.LowestPrice:
context.LowestPrice = CurrPrice
if stock in context.age:
context.age[stock] += 1
else:
context.age[stock] = 1
for stock in context.age:
if stock not in context.portfolio.positions:
context.age[stock] = 0
message = 'stock.symbol: {symbol} : age: {age}'
log.info(message.format(symbol=stock.symbol, age=context.age[stock]))
pass
def my_rebalance(context, data):
BuyFactor = .99
SellFactor = 1.01
cash = context.portfolio.cash
cancel_open_buy_orders(context, data)
# Order sell at profit target in hope that somebody actually buys it
for stock in context.portfolio.positions:
if not get_open_orders(stock):
StockShares = context.portfolio.positions[stock].amount
CurrPrice = float(data.current([stock], 'price'))
CostBasis = float(context.portfolio.positions[stock].cost_basis)
SellPrice = float(
make_div_by_05(
CostBasis *
SellFactor,
buy=False))
if np.isnan(SellPrice):
pass # probably best to wait until nan goes away
elif (stock in context.age and context.age[stock] == 1):
pass
elif (
stock in context.age
and context.MyFireSaleAge <= context.age[stock]
and (
context.MyFireSalePrice > CurrPrice
or CostBasis > CurrPrice
)
):
if (stock in context.age and context.age[stock] < 2):
pass
elif stock not in context.age:
context.age[stock] = 1
else:
SellPrice = float(
make_div_by_05(.95 * CurrPrice, buy=False))
order(stock, -StockShares,
style=LimitOrder(SellPrice)
)
else:
if (stock in context.age and context.age[stock] < 2):
pass
elif stock not in context.age:
context.age[stock] = 1
else:
order(stock, -StockShares,
style=LimitOrder(SellPrice)
)
WeightThisBuyOrder = float(1.00 / context.MaxBuyOrdersAtOnce)
for ThisBuyOrder in range(context.MaxBuyOrdersAtOnce):
stock = context.MyCandidate.next()
PH = data.history([stock], 'price', 20, '1d')
PH_Avg = float(PH.mean())
CurrPrice = float(data.current([stock], 'price'))
if np.isnan(CurrPrice):
pass # probably best to wait until nan goes away
else:
if CurrPrice > float(1.25 * PH_Avg):
BuyPrice = float(CurrPrice)
else:
BuyPrice = float(CurrPrice * BuyFactor)
BuyPrice = float(make_div_by_05(BuyPrice, buy=True))
StockShares = int(WeightThisBuyOrder * cash / BuyPrice)
order(stock, StockShares,
style=LimitOrder(BuyPrice)
)
# if cents not divisible by .05, round down if buy, round up if sell
def make_div_by_05(s, buy=False):
s *= 20.00
s = math.floor(s) if buy else math.ceil(s)
s /= 20.00
return s
def my_record_vars(context, data):
"""
Record variables at the end of each day.
"""
# Record our variables.
record(leverage=context.account.leverage)
record(positions=len(context.portfolio.positions))
if 0 < len(context.age):
MaxAge = context.age[max(
context.age.keys(), key=(lambda k: context.age[k]))]
print(MaxAge)
record(MaxAge=MaxAge)
record(LowestPrice=context.LowestPrice)
def log_open_order(StockToLog):
oo = get_open_orders()
if len(oo) == 0:
return
for stock, orders in oo.iteritems():
if stock == StockToLog:
for o in orders:
message = 'Found open order for {amount} shares in {stock}'
log.info(message.format(amount=o.amount, stock=stock))
def log_open_orders():
oo = get_open_orders()
if len(oo) == 0:
return
for stock, orders in oo.iteritems():
for o in orders:
message = 'Found open order for {amount} shares in {stock}'
log.info(message.format(amount=o.amount, stock=stock))
def cancel_open_buy_orders(context, data):
oo = get_open_orders()
if len(oo) == 0:
return
for stock, orders in oo.iteritems():
for o in orders:
# message = 'Canceling order of {amount} shares in {stock}'
# log.info(message.format(amount=o.amount, stock=stock))
if 0 < o.amount: # it is a buy order
cancel_order(o)
def cancel_open_orders(context, data):
oo = get_open_orders()
if len(oo) == 0:
return
for stock, orders in oo.iteritems():
for o in orders:
# message = 'Canceling order of {amount} shares in {stock}'
# log.info(message.format(amount=o.amount, stock=stock))
cancel_order(o)
# This is the every minute stuff
def handle_data(context, data):
pass |
# Not when-issued equities. |
_document.js | import Document, { Html, Head, Main, NextScript } from 'next/document'
class | extends Document {
render() {
return (
<Html>
<Head>
<link
href='https://fonts.googleapis.com/css2?family=Noto%20Sans%20HK&display=optional'
rel='stylesheet'
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
| MyDocument |
RedisFailoverCheck.go | // Code generated by mockery v1.0.0. DO NOT EDIT.
package mocks
import (
mock "github.com/stretchr/testify/mock"
time "time"
v1 "github.com/spotahome/redis-operator/api/redisfailover/v1"
)
// RedisFailoverCheck is an autogenerated mock type for the RedisFailoverCheck type
type RedisFailoverCheck struct {
mock.Mock
}
// CheckAllSlavesFromMaster provides a mock function with given fields: master, rFailover
func (_m *RedisFailoverCheck) CheckAllSlavesFromMaster(master string, rFailover *v1.RedisFailover) error {
ret := _m.Called(master, rFailover)
var r0 error
if rf, ok := ret.Get(0).(func(string, *v1.RedisFailover) error); ok {
r0 = rf(master, rFailover)
} else {
r0 = ret.Error(0)
}
return r0
}
// CheckRedisNumber provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) CheckRedisNumber(rFailover *v1.RedisFailover) error {
ret := _m.Called(rFailover)
var r0 error
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) error); ok {
r0 = rf(rFailover)
} else {
r0 = ret.Error(0)
}
return r0
}
// CheckRedisSlavesReady provides a mock function with given fields: slaveIP, rFailover
func (_m *RedisFailoverCheck) CheckRedisSlavesReady(slaveIP string, rFailover *v1.RedisFailover) (bool, error) {
ret := _m.Called(slaveIP, rFailover)
var r0 bool
if rf, ok := ret.Get(0).(func(string, *v1.RedisFailover) bool); ok {
r0 = rf(slaveIP, rFailover)
} else {
r0 = ret.Get(0).(bool)
}
var r1 error
if rf, ok := ret.Get(1).(func(string, *v1.RedisFailover) error); ok {
r1 = rf(slaveIP, rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// CheckSentinelMonitor provides a mock function with given fields: sentinel, monitor
func (_m *RedisFailoverCheck) CheckSentinelMonitor(sentinel string, monitor ...string) error {
_va := make([]interface{}, len(monitor))
for _i := range monitor {
_va[_i] = monitor[_i]
}
var _ca []interface{}
_ca = append(_ca, sentinel)
_ca = append(_ca, _va...)
ret := _m.Called(_ca...)
var r0 error
if rf, ok := ret.Get(0).(func(string, ...string) error); ok {
r0 = rf(sentinel, monitor...)
} else {
r0 = ret.Error(0)
}
return r0
}
// CheckSentinelNumber provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) CheckSentinelNumber(rFailover *v1.RedisFailover) error {
ret := _m.Called(rFailover)
var r0 error
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) error); ok {
r0 = rf(rFailover)
} else {
r0 = ret.Error(0)
}
return r0
}
// CheckSentinelNumberInMemory provides a mock function with given fields: sentinel, rFailover
func (_m *RedisFailoverCheck) CheckSentinelNumberInMemory(sentinel string, rFailover *v1.RedisFailover) error {
ret := _m.Called(sentinel, rFailover)
var r0 error
if rf, ok := ret.Get(0).(func(string, *v1.RedisFailover) error); ok {
r0 = rf(sentinel, rFailover)
} else {
r0 = ret.Error(0)
}
return r0
}
// CheckSentinelSlavesNumberInMemory provides a mock function with given fields: sentinel, rFailover
func (_m *RedisFailoverCheck) CheckSentinelSlavesNumberInMemory(sentinel string, rFailover *v1.RedisFailover) error {
ret := _m.Called(sentinel, rFailover)
var r0 error
if rf, ok := ret.Get(0).(func(string, *v1.RedisFailover) error); ok { | } else {
r0 = ret.Error(0)
}
return r0
}
// GetMasterIP provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) GetMasterIP(rFailover *v1.RedisFailover) (string, error) {
ret := _m.Called(rFailover)
var r0 string
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) string); ok {
r0 = rf(rFailover)
} else {
r0 = ret.Get(0).(string)
}
var r1 error
if rf, ok := ret.Get(1).(func(*v1.RedisFailover) error); ok {
r1 = rf(rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// GetMinimumRedisPodTime provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) GetMinimumRedisPodTime(rFailover *v1.RedisFailover) (time.Duration, error) {
ret := _m.Called(rFailover)
var r0 time.Duration
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) time.Duration); ok {
r0 = rf(rFailover)
} else {
r0 = ret.Get(0).(time.Duration)
}
var r1 error
if rf, ok := ret.Get(1).(func(*v1.RedisFailover) error); ok {
r1 = rf(rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// GetNumberMasters provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) GetNumberMasters(rFailover *v1.RedisFailover) (int, error) {
ret := _m.Called(rFailover)
var r0 int
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) int); ok {
r0 = rf(rFailover)
} else {
r0 = ret.Get(0).(int)
}
var r1 error
if rf, ok := ret.Get(1).(func(*v1.RedisFailover) error); ok {
r1 = rf(rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// GetRedisRevisionHash provides a mock function with given fields: podName, rFailover
func (_m *RedisFailoverCheck) GetRedisRevisionHash(podName string, rFailover *v1.RedisFailover) (string, error) {
ret := _m.Called(podName, rFailover)
var r0 string
if rf, ok := ret.Get(0).(func(string, *v1.RedisFailover) string); ok {
r0 = rf(podName, rFailover)
} else {
r0 = ret.Get(0).(string)
}
var r1 error
if rf, ok := ret.Get(1).(func(string, *v1.RedisFailover) error); ok {
r1 = rf(podName, rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// GetRedisesIPs provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) GetRedisesIPs(rFailover *v1.RedisFailover) ([]string, error) {
ret := _m.Called(rFailover)
var r0 []string
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) []string); ok {
r0 = rf(rFailover)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]string)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*v1.RedisFailover) error); ok {
r1 = rf(rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// GetRedisesMasterPod provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) GetRedisesMasterPod(rFailover *v1.RedisFailover) (string, error) {
ret := _m.Called(rFailover)
var r0 string
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) string); ok {
r0 = rf(rFailover)
} else {
r0 = ret.Get(0).(string)
}
var r1 error
if rf, ok := ret.Get(1).(func(*v1.RedisFailover) error); ok {
r1 = rf(rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// GetRedisesSlavesPods provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) GetRedisesSlavesPods(rFailover *v1.RedisFailover) ([]string, error) {
ret := _m.Called(rFailover)
var r0 []string
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) []string); ok {
r0 = rf(rFailover)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]string)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*v1.RedisFailover) error); ok {
r1 = rf(rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// GetSentinelsIPs provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) GetSentinelsIPs(rFailover *v1.RedisFailover) ([]string, error) {
ret := _m.Called(rFailover)
var r0 []string
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) []string); ok {
r0 = rf(rFailover)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]string)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*v1.RedisFailover) error); ok {
r1 = rf(rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// GetStatefulSetUpdateRevision provides a mock function with given fields: rFailover
func (_m *RedisFailoverCheck) GetStatefulSetUpdateRevision(rFailover *v1.RedisFailover) (string, error) {
ret := _m.Called(rFailover)
var r0 string
if rf, ok := ret.Get(0).(func(*v1.RedisFailover) string); ok {
r0 = rf(rFailover)
} else {
r0 = ret.Get(0).(string)
}
var r1 error
if rf, ok := ret.Get(1).(func(*v1.RedisFailover) error); ok {
r1 = rf(rFailover)
} else {
r1 = ret.Error(1)
}
return r0, r1
} | r0 = rf(sentinel, rFailover) |
register.go | // Copyright 2020 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
jetstreamv1beta2 "github.com/nats-io/nack/pkg/jetstream/apis/jetstream/v1beta2"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
var scheme = runtime.NewScheme()
var codecs = serializer.NewCodecFactory(scheme)
var localSchemeBuilder = runtime.SchemeBuilder{
jetstreamv1beta2.AddToScheme,
}
// AddToScheme adds all types of this clientset into the given scheme. This allows composition
// of clientsets, like in:
//
// import (
// "k8s.io/client-go/kubernetes"
// clientsetscheme "k8s.io/client-go/kubernetes/scheme"
// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
// )
//
// kclientset, _ := kubernetes.NewForConfig(c)
// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)
//
// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types
// correctly.
var AddToScheme = localSchemeBuilder.AddToScheme
func init() | {
v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"})
utilruntime.Must(AddToScheme(scheme))
} |
|
DnsPrimary.go | package go_thunder
import (
"bytes"
"fmt"
"github.com/clarketm/json" // "encoding/json"
"io/ioutil"
"util"
)
type Primary struct {
IPV4Addr PrimaryInstance `json:"primary,omitempty"`
}
type PrimaryInstance struct {
IPV4Addr string `json:"ip-v4-addr,omitempty"`
IPV6Addr string `json:"ip-v6-addr,omitempty"`
UUID string `json:"uuid,omitempty"`
}
func GetDnsPrimary(id string, host string) (*Primary, error) {
logger := util.GetLoggerInstance()
var headers = make(map[string]string)
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
headers["Authorization"] = id
resp, err := DoHttp("GET", "https://"+host+"/axapi/v3/ip/dns/primary", nil, headers)
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
logger.Println("The HTTP request failed with error \n", err)
return nil, err
} else {
data, _ := ioutil.ReadAll(resp.Body)
var m Primary
erro := json.Unmarshal(data, &m)
if erro != nil {
fmt.Printf("Unmarshal error %s\n", err)
return nil, err
} else {
fmt.Print(m)
logger.Println("[INFO] GET REQ RES..........................", m)
err := check_api_status("GetDnsPrimary", data)
if err != nil {
return nil, err
}
return &m, nil
}
}
}
func PostDnsPrimary(id string, vc Primary, host string) error {
logger := util.GetLoggerInstance()
var headers = make(map[string]string)
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
headers["Authorization"] = id
payloadBytes, err := json.Marshal(vc)
logger.Println("[INFO] input payload bytes - " + string((payloadBytes)))
if err != nil {
logger.Println("[INFO] Marshalling failed with error \n", err)
}
resp, err := DoHttp("POST", "https://"+host+"/axapi/v3/ip/dns/primary", bytes.NewReader(payloadBytes), headers)
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
logger.Println("The HTTP request failed with error \n", err)
} else {
data, _ := ioutil.ReadAll(resp.Body)
var v Primary
erro := json.Unmarshal(data, &v)
if erro != nil {
fmt.Printf("Unmarshal error %s\n", err)
} else {
fmt.Println("response Body:", string(data))
logger.Println("response Body:", string(data))
err := check_api_status("PostDnsPrimary", data)
if err != nil |
}
}
return err
}
| {
return err
} |
error.rs | use thiserror::Error;
#[derive(Error, Debug)]
pub enum | {
#[error(transparent)]
ReadError(#[from] std::io::Error),
#[error("Could not find BluOS controller")]
NoBluOSError,
#[error(transparent)]
RequestError(#[from] reqwest::Error),
#[error(transparent)]
XMLError(#[from] serde_xml_rs::Error),
#[error(transparent)]
CancelError(#[from] std::sync::mpsc::SendError<bool>),
#[error("Already discovering using zeroconf")]
AlreadyDiscovering,
#[error("IDK BRO")]
Unknown,
}
| Error |
test_cells.py | #!/usr/bin/env python3
import pytest
from tools import Cell
class Sample:
|
samples = [
Sample(8, 3, 5, 4),
Sample(57, 122,79, -5),
Sample(39, 217, 196, 0),
Sample(71, 101, 153, 4),
]
@pytest.fixture(params=samples, ids=str)
def sample(request):
return request.param
def test_cell(sample):
cell = Cell(sample.serial)
assert cell(sample.x, sample.y) == sample.target
| def __init__(self, serial, x, y, target):
self.serial = serial
self.x = x
self.y = y
self.target = target
def __str__(self):
return f'Cell at {self.x}x{self.y}, ' \
f'grid serial number {self.serial}:' \
f'power level is {self.target}' |
original_dst_forwarder_configurer_test.go | package v3_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
core_xds "github.com/kumahq/kuma/pkg/core/xds"
. "github.com/kumahq/kuma/pkg/xds/envoy/listeners"
util_proto "github.com/kumahq/kuma/pkg/util/proto"
envoy_common "github.com/kumahq/kuma/pkg/xds/envoy"
)
var _ = Describe("OriginalDstForwarderConfigurer", func() {
type testCase struct {
listenerName string
listenerAddress string
listenerPort uint32
listenerProtocol core_xds.SocketAddressProtocol
statsName string
clusters []envoy_common.ClusterSubset
expected string
}
DescribeTable("should generate proper Envoy config",
func(given testCase) {
// when
listener, err := NewListenerBuilder(envoy_common.APIV3).
Configure(OutboundListener(given.listenerName, given.listenerAddress, given.listenerPort, given.listenerProtocol)).
Configure(FilterChain(NewFilterChainBuilder(envoy_common.APIV3).
Configure(TcpProxy(given.statsName, given.clusters...)))).
Configure(OriginalDstForwarder()).
Build()
// then
Expect(err).ToNot(HaveOccurred())
// when
actual, err := util_proto.ToYAML(listener)
Expect(err).ToNot(HaveOccurred())
// and
Expect(actual).To(MatchYAML(given.expected))
},
Entry("basic tcp_proxy with original destination forwarder", testCase{
listenerName: "catch_all",
listenerAddress: "0.0.0.0",
listenerPort: 12345,
statsName: "pass_through",
clusters: []envoy_common.ClusterSubset{{ClusterName: "pass_through", Weight: 200}},
expected: `
name: catch_all
trafficDirection: OUTBOUND
address:
socketAddress:
address: 0.0.0.0
portValue: 12345
filterChains:
- filters:
- name: envoy.filters.network.tcp_proxy
typedConfig:
'@type': type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy
cluster: pass_through
statPrefix: pass_through
useOriginalDst: true
`,
}), | )
}) |
|
forget.py | from datetime import datetime
import os
import pickle
import argparse
import numpy as np
import torch
import torch.nn.functional as F
from mcmc_unlearner import sgmcmcUnlearner
import utils
import models
class myUnlearner(sgmcmcUnlearner):
|
def get_args():
parser = argparse.ArgumentParser()
utils.add_shared_args(parser)
parser.add_argument('--rm-idx-path', type=str, default=None)
parser.add_argument('--save-freq', type=int, default=-1)
return parser.parse_args()
def get_forget_idx(dataset, kill_num):
kill_val = 0
if 'targets' in vars(dataset).keys():
labels = np.array(dataset.targets)
elif 'labels' in vars(dataset).keys():
labels = np.array(dataset.labels)
else:
raise NotImplementedError
randidx = np.random.permutation( np.where(labels==kill_val)[0] )
return randidx[:kill_num]
def evaluate(model, loader, cpu):
''' average log predictive probability '''
loss = utils.AverageMeter()
acc = utils.AverageMeter()
n = len(loader.sampler.indices)
model.eval()
for x, y in loader:
if not cpu: x, y = x.cuda(), y.cuda()
with torch.no_grad():
_y = model(x)
lo = - model.log_prior() + F.cross_entropy(_y,y) * n
lo = lo.item()
ac = (_y.argmax(dim=1) == y).sum().item() / len(y)
loss.update(lo, len(y))
acc.update(ac, len(y))
return loss.average(), acc.average()
def forget_eval_one_time(model, train_loader, forgetted_train_loader, test_loader, log):
remain_train_loss, remain_train_acc = evaluate(model, train_loader, args.cpu)
forgetted_train_loss, forgetted_train_acc = evaluate(model, forgetted_train_loader, args.cpu)
test_loss, test_acc = evaluate(model, test_loader, args.cpu)
utils.add_log(log, 'remain_train_loss', remain_train_loss)
utils.add_log(log, 'remain_train_acc', remain_train_acc)
utils.add_log(log,'forgetted_train_loss', forgetted_train_loss)
utils.add_log(log,'forgetted_train_acc', forgetted_train_acc)
utils.add_log(log, 'test_loss', test_loss)
utils.add_log(log, 'test_acc', test_acc)
logger.info('remaining train loss {:.2e} \t train acc {:.2%}'
.format(remain_train_loss, remain_train_acc))
logger.info('forgetted train loss {:.2e} \t train acc {:.2%}'
.format(forgetted_train_loss, forgetted_train_acc))
logger.info('test loss {:.2e} \t test acc {:.2%}'
.format(test_loss, test_acc))
logger.info('')
def save_checkpoint(save_dir, save_name, log, model, optimizer):
with open('{}/{}-log.pkl'.format(save_dir, save_name), 'wb') as f:
pickle.dump(log, f)
torch.save({
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, '{}/{}-model.pkl'.format(save_dir, save_name))
def main(args, logger):
''' retrieve lots of data '''
trainset, testset = utils.get_dataset(args.dataset)
if args.rm_idx_path is not None:
with open(args.rm_idx_path, 'rb') as f:
forgetted_idx = pickle.load(f)
else:
forgetted_idx = get_forget_idx(trainset, args.ifs_kill_num)
forgetted_idx_loader = utils.IndexBatchSampler(
batch_size=args.ifs_rm_bs, indices=forgetted_idx)
train_sampler = utils.DataSampler(trainset, args.batch_size)
train_loader = utils.DataLoader(trainset, args.batch_size)
train_loader.remove(forgetted_idx)
forgetted_train_loader = utils.DataLoader(trainset, args.batch_size)
forgetted_train_loader.set_sampler_indices(forgetted_idx)
test_loader = utils.DataLoader(testset, args.batch_size)
''' end of retrieving data '''
model = utils.get_mcmc_bnn_arch(args.arch, args.dataset, args.prior_sig)
if not args.cpu:
model.cuda()
args.lr /= len(trainset)
optimizer = utils.get_optim(model.parameters(), args.optim,
lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay, sghmc_alpha=args.sghmc_alpha)
model.n = len(train_sampler)
''' restore model / sampler '''
state_dict = torch.load(args.resume_path)
model.load_state_dict(state_dict['model_state_dict'])
optimizer.load_state_dict(state_dict['optimizer_state_dict'])
''' for backward compatibility '''
for group in optimizer.param_groups:
if 'lr_decay' in group:
group['lr'] *= group['lr_decay']
group.pop('lr_decay')
del state_dict
unlearner = myUnlearner(
model = model,
optimizer = optimizer,
params = model.parameters(),
cpu = args.cpu,
iter_T = args.ifs_iter_T,
scaling = args.ifs_scaling,
samp_T = args.ifs_samp_T,)
log = dict()
log['user_time'] = 0
utils.add_log(log, 'forgetted_idx', forgetted_idx)
forget_eval_one_time(model, train_loader, forgetted_train_loader, test_loader, log)
removed_nums = 0
freq_counter = 0
for ii in forgetted_idx_loader:
''' create forget-batch '''
xx, yy = [], []
for i in ii:
x, y = trainset[i]
if len(x.shape) == 3: x = x.reshape(1, *x.shape)
xx.append(x)
yy.append(y)
xx, yy = torch.cat(xx), torch.tensor(yy)
''' end '''
scaling = args.ifs_scaling / len(train_sampler)
unlearner.param_dict['scaling'] = scaling
''' start calculation of time '''
start_time = datetime.now()
unlearner.remove([xx,yy], train_sampler)
torch.cuda.synchronize()
end_time = datetime.now()
user_time = (end_time - start_time).total_seconds()
''' end calculation of time '''
log['user_time'] += user_time
train_sampler.remove(ii)
''' after removal, update the number of remaining datums '''
unlearner.model.n = len(train_sampler)
removed_nums += len(ii)
freq_counter += len(ii)
''' update mcmc sampler '''
for group in unlearner.optimizer.param_groups:
group['lr'] *= (len(train_sampler) + len(ii)) / len(train_sampler)
logger.info('remaining trainset size {}'.format(len(train_sampler)))
logger.info('user time {:.3f} sec \t'
'cumulated user time {:.3f} mins'
.format(user_time, log['user_time']/60) )
if (args.save_freq > 0) and (freq_counter >= args.save_freq):
freq_counter = 0
save_checkpoint(args.save_dir, '{}-ckpt-{}'.format(args.save_name, removed_nums), log, model, optimizer)
forget_eval_one_time(model, train_loader, forgetted_train_loader, test_loader, log)
save_checkpoint(args.save_dir, args.save_name, log, model, optimizer)
return
if __name__ == '__main__':
args = get_args()
logger = utils.generic_init(args)
try:
main(args, logger)
except Exception as e:
logger.exception('Unexpected exception! %s', e)
| def _apply_sample(self, z):
x, y = z
if not self.cpu: x, y = x.cuda(), y.cuda()
self.model.train()
lo = -self.model.log_prior() + F.cross_entropy(self.model(x), y) * self.model.n
self.optimizer.zero_grad()
lo.backward()
self.optimizer.step()
def _fun(self, z):
x, y = z
if not self.cpu: x, y = x.cuda(), y.cuda()
self.model.train()
return -self.model.log_prior() + F.cross_entropy(self.model(x), y) * self.model.n
def _z_fun(self, z):
x, y = z
if not self.cpu: x, y = x.cuda(), y.cuda()
self.model.train()
return F.cross_entropy(self.model(x), y, reduction='sum') |
ccall.py | import claripy
import logging
from archinfo.arch_arm import is_arm_arch
l = logging.getLogger(name=__name__)
#l.setLevel(logging.DEBUG)
# pylint: disable=R0911
# pylint: disable=W0613
# pylint: disable=W0612
# pylint: disable=invalid-unary-operand-type
###############
### Helpers ###
###############
# There might be a better way of doing this
def calc_paritybit(state, p, msb=7, lsb=0):
if len(p) > msb:
p_part = p[msb:lsb]
else:
p_part = p
b = state.solver.BVV(1, 1)
for i in range(p_part.size()):
b = b ^ p_part[i]
return b
def calc_zerobit(state, p):
return state.solver.If(p == 0, state.solver.BVV(1, 1), state.solver.BVV(0, 1))
def boolean_extend(state, O, a, b, size):
return state.solver.If(O(a, b), state.solver.BVV(1, size), state.solver.BVV(0, size))
def flag_concretize(state, flag):
return state.solver.eval(flag)
#return state.solver.eval_one(flag)
##################
### x86* data ###
##################
data = {
'AMD64': {
'CondTypes': { },
'CondBitOffsets': { },
'CondBitMasks': { },
'OpTypes': { }
}, 'X86': {
'CondTypes': { },
'CondBitOffsets': { },
'CondBitMasks': { },
'OpTypes': { }
}
}
# condition types
data['AMD64']['CondTypes']['CondO'] = 0 # /* overflow */
data['AMD64']['CondTypes']['CondNO'] = 1 # /* no overflow */
data['AMD64']['CondTypes']['CondB'] = 2 # /* below */
data['AMD64']['CondTypes']['CondNB'] = 3 # /* not below */
data['AMD64']['CondTypes']['CondZ'] = 4 # /* zero */
data['AMD64']['CondTypes']['CondNZ'] = 5 # /* not zero */
data['AMD64']['CondTypes']['CondBE'] = 6 # /* below or equal */
data['AMD64']['CondTypes']['CondNBE'] = 7 # /* not below or equal */
data['AMD64']['CondTypes']['CondS'] = 8 # /* negative */
data['AMD64']['CondTypes']['CondNS'] = 9 # /* not negative */
data['AMD64']['CondTypes']['CondP'] = 10 # /* parity even */
data['AMD64']['CondTypes']['CondNP'] = 11 # /* not parity even */
data['AMD64']['CondTypes']['CondL'] = 12 # /* jump less */
data['AMD64']['CondTypes']['CondNL'] = 13 # /* not less */
data['AMD64']['CondTypes']['CondLE'] = 14 # /* less or equal */
data['AMD64']['CondTypes']['CondNLE'] = 15 # /* not less or equal */
# condition bit offsets
data['AMD64']['CondBitOffsets']['G_CC_SHIFT_O'] = 11
data['AMD64']['CondBitOffsets']['G_CC_SHIFT_S'] = 7
data['AMD64']['CondBitOffsets']['G_CC_SHIFT_Z'] = 6
data['AMD64']['CondBitOffsets']['G_CC_SHIFT_A'] = 4
data['AMD64']['CondBitOffsets']['G_CC_SHIFT_C'] = 0
data['AMD64']['CondBitOffsets']['G_CC_SHIFT_P'] = 2
# masks
data['AMD64']['CondBitMasks']['G_CC_MASK_O'] = (1 << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_O'])
data['AMD64']['CondBitMasks']['G_CC_MASK_S'] = (1 << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_S'])
data['AMD64']['CondBitMasks']['G_CC_MASK_Z'] = (1 << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_Z'])
data['AMD64']['CondBitMasks']['G_CC_MASK_A'] = (1 << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_A'])
data['AMD64']['CondBitMasks']['G_CC_MASK_C'] = (1 << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_C'])
data['AMD64']['CondBitMasks']['G_CC_MASK_P'] = (1 << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_P'])
# operation types
data['AMD64']['OpTypes']['G_CC_OP_COPY'] = 0
data['AMD64']['OpTypes']['G_CC_OP_ADDB'] = 1
data['AMD64']['OpTypes']['G_CC_OP_ADDW'] = 2
data['AMD64']['OpTypes']['G_CC_OP_ADDL'] = 3
data['AMD64']['OpTypes']['G_CC_OP_ADDQ'] = 4
data['AMD64']['OpTypes']['G_CC_OP_SUBB'] = 5
data['AMD64']['OpTypes']['G_CC_OP_SUBW'] = 6
data['AMD64']['OpTypes']['G_CC_OP_SUBL'] = 7
data['AMD64']['OpTypes']['G_CC_OP_SUBQ'] = 8
data['AMD64']['OpTypes']['G_CC_OP_ADCB'] = 9
data['AMD64']['OpTypes']['G_CC_OP_ADCW'] = 10
data['AMD64']['OpTypes']['G_CC_OP_ADCL'] = 11
data['AMD64']['OpTypes']['G_CC_OP_ADCQ'] = 12
data['AMD64']['OpTypes']['G_CC_OP_SBBB'] = 13
data['AMD64']['OpTypes']['G_CC_OP_SBBW'] = 14
data['AMD64']['OpTypes']['G_CC_OP_SBBL'] = 15
data['AMD64']['OpTypes']['G_CC_OP_SBBQ'] = 16 | data['AMD64']['OpTypes']['G_CC_OP_LOGICL'] = 19
data['AMD64']['OpTypes']['G_CC_OP_LOGICQ'] = 20
data['AMD64']['OpTypes']['G_CC_OP_INCB'] = 21
data['AMD64']['OpTypes']['G_CC_OP_INCW'] = 22
data['AMD64']['OpTypes']['G_CC_OP_INCL'] = 23
data['AMD64']['OpTypes']['G_CC_OP_INCQ'] = 24
data['AMD64']['OpTypes']['G_CC_OP_DECB'] = 25
data['AMD64']['OpTypes']['G_CC_OP_DECW'] = 26
data['AMD64']['OpTypes']['G_CC_OP_DECL'] = 27
data['AMD64']['OpTypes']['G_CC_OP_DECQ'] = 28
data['AMD64']['OpTypes']['G_CC_OP_SHLB'] = 29
data['AMD64']['OpTypes']['G_CC_OP_SHLW'] = 30
data['AMD64']['OpTypes']['G_CC_OP_SHLL'] = 31
data['AMD64']['OpTypes']['G_CC_OP_SHLQ'] = 32
data['AMD64']['OpTypes']['G_CC_OP_SHRB'] = 33
data['AMD64']['OpTypes']['G_CC_OP_SHRW'] = 34
data['AMD64']['OpTypes']['G_CC_OP_SHRL'] = 35
data['AMD64']['OpTypes']['G_CC_OP_SHRQ'] = 36
data['AMD64']['OpTypes']['G_CC_OP_ROLB'] = 37
data['AMD64']['OpTypes']['G_CC_OP_ROLW'] = 38
data['AMD64']['OpTypes']['G_CC_OP_ROLL'] = 39
data['AMD64']['OpTypes']['G_CC_OP_ROLQ'] = 40
data['AMD64']['OpTypes']['G_CC_OP_RORB'] = 41
data['AMD64']['OpTypes']['G_CC_OP_RORW'] = 42
data['AMD64']['OpTypes']['G_CC_OP_RORL'] = 43
data['AMD64']['OpTypes']['G_CC_OP_RORQ'] = 44
data['AMD64']['OpTypes']['G_CC_OP_UMULB'] = 45
data['AMD64']['OpTypes']['G_CC_OP_UMULW'] = 46
data['AMD64']['OpTypes']['G_CC_OP_UMULL'] = 47
data['AMD64']['OpTypes']['G_CC_OP_UMULQ'] = 48
data['AMD64']['OpTypes']['G_CC_OP_SMULB'] = 49
data['AMD64']['OpTypes']['G_CC_OP_SMULW'] = 50
data['AMD64']['OpTypes']['G_CC_OP_SMULL'] = 51
data['AMD64']['OpTypes']['G_CC_OP_SMULQ'] = 52
data['AMD64']['OpTypes']['G_CC_OP_NUMBER'] = 53
data['X86']['CondTypes']['CondO'] = 0
data['X86']['CondTypes']['CondNO'] = 1
data['X86']['CondTypes']['CondB'] = 2
data['X86']['CondTypes']['CondNB'] = 3
data['X86']['CondTypes']['CondZ'] = 4
data['X86']['CondTypes']['CondNZ'] = 5
data['X86']['CondTypes']['CondBE'] = 6
data['X86']['CondTypes']['CondNBE'] = 7
data['X86']['CondTypes']['CondS'] = 8
data['X86']['CondTypes']['CondNS'] = 9
data['X86']['CondTypes']['CondP'] = 10
data['X86']['CondTypes']['CondNP'] = 11
data['X86']['CondTypes']['CondL'] = 12
data['X86']['CondTypes']['CondNL'] = 13
data['X86']['CondTypes']['CondLE'] = 14
data['X86']['CondTypes']['CondNLE'] = 15
data['X86']['CondTypes']['CondAlways'] = 16
data['X86']['CondBitOffsets']['G_CC_SHIFT_O'] = 11
data['X86']['CondBitOffsets']['G_CC_SHIFT_S'] = 7
data['X86']['CondBitOffsets']['G_CC_SHIFT_Z'] = 6
data['X86']['CondBitOffsets']['G_CC_SHIFT_A'] = 4
data['X86']['CondBitOffsets']['G_CC_SHIFT_C'] = 0
data['X86']['CondBitOffsets']['G_CC_SHIFT_P'] = 2
# masks
data['X86']['CondBitMasks']['G_CC_MASK_O'] = (1 << data['X86']['CondBitOffsets']['G_CC_SHIFT_O'])
data['X86']['CondBitMasks']['G_CC_MASK_S'] = (1 << data['X86']['CondBitOffsets']['G_CC_SHIFT_S'])
data['X86']['CondBitMasks']['G_CC_MASK_Z'] = (1 << data['X86']['CondBitOffsets']['G_CC_SHIFT_Z'])
data['X86']['CondBitMasks']['G_CC_MASK_A'] = (1 << data['X86']['CondBitOffsets']['G_CC_SHIFT_A'])
data['X86']['CondBitMasks']['G_CC_MASK_C'] = (1 << data['X86']['CondBitOffsets']['G_CC_SHIFT_C'])
data['X86']['CondBitMasks']['G_CC_MASK_P'] = (1 << data['X86']['CondBitOffsets']['G_CC_SHIFT_P'])
data['X86']['OpTypes']['G_CC_OP_COPY'] = 0
data['X86']['OpTypes']['G_CC_OP_ADDB'] = 1
data['X86']['OpTypes']['G_CC_OP_ADDW'] = 2
data['X86']['OpTypes']['G_CC_OP_ADDL'] = 3
data['X86']['OpTypes']['G_CC_OP_SUBB'] = 4
data['X86']['OpTypes']['G_CC_OP_SUBW'] = 5
data['X86']['OpTypes']['G_CC_OP_SUBL'] = 6
data['X86']['OpTypes']['G_CC_OP_ADCB'] = 7
data['X86']['OpTypes']['G_CC_OP_ADCW'] = 8
data['X86']['OpTypes']['G_CC_OP_ADCL'] = 9
data['X86']['OpTypes']['G_CC_OP_SBBB'] = 10
data['X86']['OpTypes']['G_CC_OP_SBBW'] = 11
data['X86']['OpTypes']['G_CC_OP_SBBL'] = 12
data['X86']['OpTypes']['G_CC_OP_LOGICB'] = 13
data['X86']['OpTypes']['G_CC_OP_LOGICW'] = 14
data['X86']['OpTypes']['G_CC_OP_LOGICL'] = 15
data['X86']['OpTypes']['G_CC_OP_INCB'] = 16
data['X86']['OpTypes']['G_CC_OP_INCW'] = 17
data['X86']['OpTypes']['G_CC_OP_INCL'] = 18
data['X86']['OpTypes']['G_CC_OP_DECB'] = 19
data['X86']['OpTypes']['G_CC_OP_DECW'] = 20
data['X86']['OpTypes']['G_CC_OP_DECL'] = 21
data['X86']['OpTypes']['G_CC_OP_SHLB'] = 22
data['X86']['OpTypes']['G_CC_OP_SHLW'] = 23
data['X86']['OpTypes']['G_CC_OP_SHLL'] = 24
data['X86']['OpTypes']['G_CC_OP_SHRB'] = 25
data['X86']['OpTypes']['G_CC_OP_SHRW'] = 26
data['X86']['OpTypes']['G_CC_OP_SHRL'] = 27
data['X86']['OpTypes']['G_CC_OP_ROLB'] = 28
data['X86']['OpTypes']['G_CC_OP_ROLW'] = 29
data['X86']['OpTypes']['G_CC_OP_ROLL'] = 30
data['X86']['OpTypes']['G_CC_OP_RORB'] = 31
data['X86']['OpTypes']['G_CC_OP_RORW'] = 32
data['X86']['OpTypes']['G_CC_OP_RORL'] = 33
data['X86']['OpTypes']['G_CC_OP_UMULB'] = 34
data['X86']['OpTypes']['G_CC_OP_UMULW'] = 35
data['X86']['OpTypes']['G_CC_OP_UMULL'] = 36
data['X86']['OpTypes']['G_CC_OP_SMULB'] = 37
data['X86']['OpTypes']['G_CC_OP_SMULW'] = 38
data['X86']['OpTypes']['G_CC_OP_SMULL'] = 39
data['X86']['OpTypes']['G_CC_OP_NUMBER'] = 40
data['X86']['OpTypes']['G_CC_OP_SMULQ'] = None
data['X86']['OpTypes']['G_CC_OP_UMULQ'] = None
data['X86']['OpTypes']['G_CC_OP_RORQ'] = None
data['X86']['OpTypes']['G_CC_OP_ROLQ'] = None
data['X86']['OpTypes']['G_CC_OP_SHRQ'] = None
data['X86']['OpTypes']['G_CC_OP_SHLQ'] = None
data['X86']['OpTypes']['G_CC_OP_DECQ'] = None
data['X86']['OpTypes']['G_CC_OP_INCQ'] = None
data['X86']['OpTypes']['G_CC_OP_LOGICQ'] = None
data['X86']['OpTypes']['G_CC_OP_SBBQ'] = None
data['X86']['OpTypes']['G_CC_OP_ADCQ'] = None
data['X86']['OpTypes']['G_CC_OP_SUBQ'] = None
data['X86']['OpTypes']['G_CC_OP_ADDQ'] = None
data_inverted = { k_arch: { k_data_class: {y:x for (x,y) in d_data_class.items()} for k_data_class, d_data_class in d_arch.items() } for k_arch,d_arch in data.items() }
data['AMD64']['size'] = 64
data['X86']['size'] = 32
#
# AMD64 internal helpers
#
def pc_preamble(state, nbits, platform=None):
data_mask = state.solver.BVV(2 ** nbits - 1, nbits)
sign_mask = 1 << (nbits - 1)
return data_mask, sign_mask
def pc_make_rdata(nbits, cf, pf, af, zf, sf, of, platform=None):
return cf, pf, af, zf, sf, of
def pc_make_rdata_if_necessary(nbits, cf, pf, af, zf, sf, of, platform=None):
vec = [(data[platform]['CondBitOffsets']['G_CC_SHIFT_C'], cf),
(data[platform]['CondBitOffsets']['G_CC_SHIFT_P'], pf),
(data[platform]['CondBitOffsets']['G_CC_SHIFT_A'], af),
(data[platform]['CondBitOffsets']['G_CC_SHIFT_Z'], zf),
(data[platform]['CondBitOffsets']['G_CC_SHIFT_S'], sf),
(data[platform]['CondBitOffsets']['G_CC_SHIFT_O'], of)]
vec.sort(reverse=True)
return _concat_flags(nbits, vec)
def pc_actions_ADD(state, nbits, arg_l, arg_r, cc_ndep, platform=None):
data_mask, sign_mask = pc_preamble(state, nbits, platform=platform)
res = arg_l + arg_r
cf = state.solver.If(state.solver.ULT(res, arg_l), state.solver.BVV(1, 1), state.solver.BVV(0, 1))
pf = calc_paritybit(state, res)
af = (res ^ arg_l ^ arg_r)[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
zf = calc_zerobit(state, res)
sf = res[nbits - 1:nbits - 1]
of = ((arg_l ^ arg_r ^ data_mask) & (arg_l ^ res))[nbits - 1:nbits - 1]
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_SUB(state, nbits, arg_l, arg_r, cc_ndep, platform=None):
data_mask, sign_mask = pc_preamble(state, nbits, platform=platform)
res = arg_l - arg_r
cf = state.solver.If(state.solver.ULT(arg_l, arg_r), state.solver.BVV(1, 1), state.solver.BVV(0, 1))
pf = calc_paritybit(state, res)
af = (res ^ arg_l ^ arg_r)[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
zf = calc_zerobit(state, res)
sf = res[nbits - 1:nbits - 1]
of = ((arg_l ^ arg_r) & (arg_l ^ res))[nbits - 1:nbits - 1]
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_LOGIC(state, nbits, arg_l, arg_r, cc_ndep, platform=None):
data_mask, sign_mask = pc_preamble(state, nbits, platform=platform)
cf = state.solver.BVV(0, 1)
pf = calc_paritybit(state, arg_l)
af = state.solver.BVV(0, 1)
zf = calc_zerobit(state, arg_l)
sf = arg_l[nbits-1]
of = state.solver.BVV(0, 1)
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_DEC(state, nbits, res, _, cc_ndep, platform=None):
data_mask, sign_mask = pc_preamble(state, nbits, platform=platform)
arg_l = res + 1
arg_r = 1
cf = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_C'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_C']]
pf = calc_paritybit(state, res)
af = (res ^ arg_l ^ 1)[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
zf = calc_zerobit(state, res)
sf = res[nbits-1]
of = state.solver.If(sf == arg_l[nbits-1], state.solver.BVV(0, 1), state.solver.BVV(1, 1))
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_ADC(state, nbits, cc_dep1, cc_dep2, cc_ndep, platform=None):
old_c = cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_C']
arg_l = cc_dep1
arg_r = cc_dep2 ^ old_c
res = (arg_l + arg_r) + old_c
cf = state.solver.If(
old_c != 0,
state.solver.If(res <= arg_l, state.solver.BVV(1, 1), state.solver.BVV(0, 1)),
state.solver.If(res < arg_l, state.solver.BVV(1, 1), state.solver.BVV(0, 1))
)
pf = calc_paritybit(state, res)
af = (res ^ arg_l ^ arg_r)[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
zf = calc_zerobit(state, res)
sf = res[nbits - 1]
of = ((arg_l ^ arg_r ^ -1) & (arg_l ^ res))[nbits-1]
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_SBB(state, nbits, cc_dep1, cc_dep2, cc_ndep, platform=None):
data_mask, sign_mask = pc_preamble(state, nbits, platform=platform)
old_c = cc_ndep[data[platform]['CondBitOffsets']['G_CC_SHIFT_C']].zero_extend(nbits-1)
arg_l = cc_dep1
arg_r = cc_dep2 ^ old_c
res = (arg_l - arg_r) - old_c
cf_c = state.solver.If(state.solver.ULE(arg_l, arg_r), state.solver.BVV(1, 1), state.solver.BVV(0, 1))
cf_noc = state.solver.If(state.solver.ULT(arg_l, arg_r), state.solver.BVV(1, 1), state.solver.BVV(0, 1))
cf = state.solver.If(old_c == 1, cf_c, cf_noc)
pf = calc_paritybit(state, res)
af = (res ^ arg_l ^ arg_r)[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
zf = calc_zerobit(state, res)
sf = res[nbits-1]
of = ((arg_l ^ arg_r) & (arg_l ^ res))[nbits-1]
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_INC(state, nbits, res, _, cc_ndep, platform=None):
data_mask, sign_mask = pc_preamble(state, nbits, platform=platform)
arg_l = res - 1
arg_r = 1
cf = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_C'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_C']]
pf = calc_paritybit(state, res)
af = (res ^ arg_l ^ 1)[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
zf = calc_zerobit(state, res)
sf = res[nbits-1]
of = state.solver.If(sf == arg_l[nbits-1], state.solver.BVV(0, 1), state.solver.BVV(1, 1))
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_SHL(state, nbits, remaining, shifted, cc_ndep, platform=None):
cf = ((remaining >> (nbits - 1)) & data[platform]['CondBitMasks']['G_CC_MASK_C'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_C']]
pf = calc_paritybit(state, remaining[7:0])
af = state.solver.BVV(0, 1)
zf = calc_zerobit(state, remaining)
sf = remaining[nbits-1]
of = (remaining[0] ^ shifted[0])[0]
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_SHR(state, nbits, remaining, shifted, cc_ndep, platform=None):
cf = state.solver.If(shifted & 1 != 0, state.solver.BVV(1, 1), state.solver.BVV(0, 1))
pf = calc_paritybit(state, remaining[7:0])
af = state.solver.BVV(0, 1)
zf = calc_zerobit(state, remaining)
sf = remaining[nbits-1]
of = (remaining[0] ^ shifted[0])[0]
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_ROL(state, nbits, res, _, cc_ndep, platform=None):
cf = res[0]
pf = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_P'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_P']]
af = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_A'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
zf = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_Z'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_Z']]
sf = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_S'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_S']]
of = (state.solver.LShR(res, nbits-1) ^ res)[0]
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_ROR(state, nbits, res, _, cc_ndep, platform=None):
cf = res[nbits-1]
pf = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_P'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_P']]
af = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_A'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_A']]
zf = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_Z'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_Z']]
sf = (cc_ndep & data[platform]['CondBitMasks']['G_CC_MASK_S'])[data[platform]['CondBitOffsets']['G_CC_SHIFT_S']]
of = (res[nbits-1] ^ res[nbits-2])
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_UMUL(state, nbits, cc_dep1, cc_dep2, cc_ndep, platform=None):
lo = (cc_dep1 * cc_dep2)[nbits - 1:0]
rr = lo
hi = (rr >> nbits)[nbits - 1:0]
cf = state.solver.If(hi != 0, state.solver.BVV(1, 1), state.solver.BVV(0, 1))
zf = calc_zerobit(state, lo)
pf = calc_paritybit(state, lo)
af = state.solver.BVV(0, 1)
sf = lo[nbits - 1]
of = cf
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_UMULQ(*args, **kwargs):
l.error("Unsupported flag action UMULQ")
raise SimCCallError("Unsupported flag action. Please implement or bug Yan.")
def pc_actions_SMUL(state, nbits, cc_dep1, cc_dep2, cc_ndep, platform=None):
lo = (cc_dep1 * cc_dep2)[nbits - 1:0]
rr = lo
hi = (rr >> nbits)[nbits - 1:0]
cf = state.solver.If(hi != (lo >> (nbits - 1)), state.solver.BVV(1, 1), state.solver.BVV(0, 1))
zf = calc_zerobit(state, lo)
pf = calc_paritybit(state, lo)
af = state.solver.BVV(0, 1)
sf = lo[nbits - 1]
of = cf
return pc_make_rdata(data[platform]['size'], cf, pf, af, zf, sf, of, platform=platform)
def pc_actions_SMULQ(*args, **kwargs):
l.error("Unsupported flag action SMULQ")
raise SimCCallError("Unsupported flag action. Please implement or bug Yan.")
def pc_calculate_rdata_all_WRK(state, cc_op, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=None):
# sanity check
if not isinstance(cc_op, int):
cc_op = flag_concretize(state, cc_op)
if cc_op == data[platform]['OpTypes']['G_CC_OP_COPY']:
l.debug("cc_op == data[platform]['OpTypes']['G_CC_OP_COPY']")
return cc_dep1_formal & (data[platform]['CondBitMasks']['G_CC_MASK_O'] | data[platform]['CondBitMasks']['G_CC_MASK_S'] | data[platform]['CondBitMasks']['G_CC_MASK_Z']
| data[platform]['CondBitMasks']['G_CC_MASK_A'] | data[platform]['CondBitMasks']['G_CC_MASK_C'] | data[platform]['CondBitMasks']['G_CC_MASK_P'])
cc_str = data_inverted[platform]['OpTypes'][cc_op]
nbits = _get_nbits(cc_str)
l.debug("nbits == %d", nbits)
cc_dep1_formal = cc_dep1_formal[nbits-1:0]
cc_dep2_formal = cc_dep2_formal[nbits-1:0]
cc_ndep_formal = cc_ndep_formal[nbits-1:0]
if cc_str in [ 'G_CC_OP_ADDB', 'G_CC_OP_ADDW', 'G_CC_OP_ADDL', 'G_CC_OP_ADDQ' ]:
l.debug("cc_str: ADD")
return pc_actions_ADD(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_ADCB', 'G_CC_OP_ADCW', 'G_CC_OP_ADCL', 'G_CC_OP_ADCQ' ]:
l.debug("cc_str: ADC")
return pc_actions_ADC(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_SUBB', 'G_CC_OP_SUBW', 'G_CC_OP_SUBL', 'G_CC_OP_SUBQ' ]:
l.debug("cc_str: SUB")
return pc_actions_SUB(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_SBBB', 'G_CC_OP_SBBW', 'G_CC_OP_SBBL', 'G_CC_OP_SBBQ' ]:
l.debug("cc_str: SBB")
return pc_actions_SBB(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_LOGICB', 'G_CC_OP_LOGICW', 'G_CC_OP_LOGICL', 'G_CC_OP_LOGICQ' ]:
l.debug("cc_str: LOGIC")
return pc_actions_LOGIC(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_INCB', 'G_CC_OP_INCW', 'G_CC_OP_INCL', 'G_CC_OP_INCQ' ]:
l.debug("cc_str: INC")
return pc_actions_INC(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_DECB', 'G_CC_OP_DECW', 'G_CC_OP_DECL', 'G_CC_OP_DECQ' ]:
l.debug("cc_str: DEC")
return pc_actions_DEC(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_SHLB', 'G_CC_OP_SHLW', 'G_CC_OP_SHLL', 'G_CC_OP_SHLQ' ]:
l.debug("cc_str: SHL")
return pc_actions_SHL(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_SHRB', 'G_CC_OP_SHRW', 'G_CC_OP_SHRL', 'G_CC_OP_SHRQ' ]:
l.debug("cc_str: SHR")
return pc_actions_SHR(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_ROLB', 'G_CC_OP_ROLW', 'G_CC_OP_ROLL', 'G_CC_OP_ROLQ' ]:
l.debug("cc_str: ROL")
return pc_actions_ROL(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_RORB', 'G_CC_OP_RORW', 'G_CC_OP_RORL', 'G_CC_OP_RORQ' ]:
l.debug("cc_str: ROR")
return pc_actions_ROR(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_UMULB', 'G_CC_OP_UMULW', 'G_CC_OP_UMULL', 'G_CC_OP_UMULQ' ]:
l.debug("cc_str: UMUL")
return pc_actions_UMUL(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str == 'G_CC_OP_UMULQ':
l.debug("cc_str: UMULQ")
return pc_actions_UMULQ(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str in [ 'G_CC_OP_SMULB', 'G_CC_OP_SMULW', 'G_CC_OP_SMULL', 'G_CC_OP_SMULQ' ]:
l.debug("cc_str: SMUL")
return pc_actions_SMUL(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
if cc_str == 'G_CC_OP_SMULQ':
l.debug("cc_str: SMULQ")
return pc_actions_SMULQ(state, nbits, cc_dep1_formal, cc_dep2_formal, cc_ndep_formal, platform=platform)
l.error("Unsupported cc_op %d in in pc_calculate_rdata_all_WRK", cc_op)
raise SimCCallError("Unsupported cc_op in pc_calculate_rdata_all_WRK")
# This function returns all the data
def pc_calculate_rdata_all(state, cc_op, cc_dep1, cc_dep2, cc_ndep, platform=None):
rdata_all = pc_calculate_rdata_all_WRK(state, cc_op, cc_dep1, cc_dep2, cc_ndep, platform=platform)
if isinstance(rdata_all, tuple):
return pc_make_rdata_if_necessary(data[platform]['size'], *rdata_all, platform=platform), [ ]
else:
return rdata_all, [ ]
# This function takes a condition that is being checked (ie, zero bit), and basically
# returns that bit
def pc_calculate_condition(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep, platform=None):
rdata_all = pc_calculate_rdata_all_WRK(state, cc_op, cc_dep1, cc_dep2, cc_ndep, platform=platform)
if isinstance(rdata_all, tuple):
cf, pf, af, zf, sf, of = rdata_all
if state.solver.symbolic(cond):
raise SimError("Hit a symbolic 'cond' in pc_calculate_condition. Panic.")
v = flag_concretize(state, cond)
inv = v & 1
l.debug("inv: %d", inv)
if v in [ data[platform]['CondTypes']['CondO'], data[platform]['CondTypes']['CondNO'] ]:
l.debug("CondO")
#of = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_O'])
r = 1 & (inv ^ of)
elif v in [ data[platform]['CondTypes']['CondZ'], data[platform]['CondTypes']['CondNZ'] ]:
l.debug("CondZ")
#zf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_Z'])
r = 1 & (inv ^ zf)
elif v in [ data[platform]['CondTypes']['CondB'], data[platform]['CondTypes']['CondNB'] ]:
l.debug("CondB")
#cf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_C'])
r = 1 & (inv ^ cf)
elif v in [ data[platform]['CondTypes']['CondBE'], data[platform]['CondTypes']['CondNBE'] ]:
l.debug("CondBE")
#cf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_C'])
#zf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_Z'])
r = 1 & (inv ^ (cf | zf))
elif v in [ data[platform]['CondTypes']['CondS'], data[platform]['CondTypes']['CondNS'] ]:
l.debug("CondS")
#sf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_S'])
r = 1 & (inv ^ sf)
elif v in [ data[platform]['CondTypes']['CondP'], data[platform]['CondTypes']['CondNP'] ]:
l.debug("CondP")
#pf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_P'])
r = 1 & (inv ^ pf)
elif v in [ data[platform]['CondTypes']['CondL'], data[platform]['CondTypes']['CondNL'] ]:
l.debug("CondL")
#sf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_S'])
#of = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_O'])
r = 1 & (inv ^ (sf ^ of))
elif v in [ data[platform]['CondTypes']['CondLE'], data[platform]['CondTypes']['CondNLE'] ]:
l.debug("CondLE")
#sf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_S'])
#of = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_O'])
#zf = state.solver.LShR(rdata, data[platform]['G_CC_SHIFT_Z'])
r = 1 & (inv ^ ((sf ^ of) | zf))
return state.solver.Concat(state.solver.BVV(0, state.arch.bits-1), r), [ ]
else:
rdata = rdata_all
if state.solver.symbolic(cond):
raise SimError("Hit a symbolic 'cond' in pc_calculate_condition. Panic.")
v = flag_concretize(state, cond)
inv = v & 1
l.debug("inv: %d", inv)
# THIS IS A FUCKING HACK
if v == 0xe:
# jle
pass
if v in [data[platform]['CondTypes']['CondO'], data[platform]['CondTypes']['CondNO']]:
l.debug("CondO")
of = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_O'])
return 1 & (inv ^ of), []
if v in [data[platform]['CondTypes']['CondZ'], data[platform]['CondTypes']['CondNZ']]:
l.debug("CondZ")
zf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_Z'])
return 1 & (inv ^ zf), []
if v in [data[platform]['CondTypes']['CondB'], data[platform]['CondTypes']['CondNB']]:
l.debug("CondB")
cf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_C'])
return 1 & (inv ^ cf), []
if v in [data[platform]['CondTypes']['CondBE'], data[platform]['CondTypes']['CondNBE']]:
l.debug("CondBE")
cf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_C'])
zf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_Z'])
return 1 & (inv ^ (cf | zf)), []
if v in [data[platform]['CondTypes']['CondS'], data[platform]['CondTypes']['CondNS']]:
l.debug("CondS")
sf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_S'])
return 1 & (inv ^ sf), []
if v in [data[platform]['CondTypes']['CondP'], data[platform]['CondTypes']['CondNP']]:
l.debug("CondP")
pf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_P'])
return 1 & (inv ^ pf), []
if v in [data[platform]['CondTypes']['CondL'], data[platform]['CondTypes']['CondNL']]:
l.debug("CondL")
sf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_S'])
of = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_O'])
return 1 & (inv ^ (sf ^ of)), []
if v in [data[platform]['CondTypes']['CondLE'], data[platform]['CondTypes']['CondNLE']]:
l.debug("CondLE")
sf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_S'])
of = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_O'])
zf = state.solver.LShR(rdata, data[platform]['CondBitOffsets']['G_CC_SHIFT_Z'])
return 1 & (inv ^ ((sf ^ of) | zf)), []
l.error("Unsupported condition %d in in pc_calculate_condition", v)
raise SimCCallError("Unrecognized condition in pc_calculate_condition")
#
# Simplified CCalls
#
# Simplified CCalls (whose names look like `pc_actions_<operation>_<condition>`) are a bunch of methods that generate
# straight-forward ASTs based on the operation and the condition, instead of blindly following the way that a CPU does
# the conditional flags calculation and generating messy and meaningless ASTs. It allows us to have a meaningful AST
# for each conditional flag, which greatly helps static analysis (like VSA).
def _cond_flag(state, condition):
return state.solver.If(condition, state.solver.BVV(1, 1), state.solver.BVV(0, 1))
# TODO: Implement the missing ones
# General ops
def pc_actions_op_SUB(arg_l, arg_r, cc_ndep):
return arg_l - arg_r
def pc_actions_op_DEC(arg_l, arg_r, cc_ndep):
return arg_l - 1
def pc_actions_op_INC(arg_l, arg_r, cc_ndep):
return arg_l + 1
def pc_actions_op_SHR(arg_l, arg_r, cc_ndep):
return arg_l >> arg_r
def pc_actions_op_SHL(arg_l, arg_r, cc_ndep):
return arg_l << arg_r
def pc_actions_op_ADD(arg_l, arg_r, cc_ndep):
return arg_l + arg_r
def pc_actions_op_LOGIC(arg_l, arg_r, cc_ndep):
return arg_l
# General conditions
def pc_actions_cond_CondZ(state, cc_expr):
return _cond_flag(state, cc_expr == 0)
def pc_actions_cond_CondNZ(state, cc_expr):
return _cond_flag(state, cc_expr != 0)
def pc_actions_cond_CondS(state, cc_expr):
return _cond_flag(state, state.solver.SLT(cc_expr, 0))
def pc_actions_cond_CondB(state, cc_expr):
return _cond_flag(state, state.solver.ULT(cc_expr, 0))
def pc_actions_cond_CondBE(state, cc_expr):
return _cond_flag(state, state.solver.ULE(cc_expr, 0))
def pc_actions_cond_CondNBE(state, cc_expr):
return _cond_flag(state, state.solver.UGT(cc_expr, 0))
def pc_actions_cond_CondL(state, cc_expr):
return _cond_flag(state, state.solver.SLT(cc_expr, 0))
def pc_actions_cond_CondLE(state, cc_expr):
return _cond_flag(state, state.solver.SLE(cc_expr, 0))
def pc_actions_cond_CondNLE(state, cc_expr):
return _cond_flag(state, state.solver.SGT(cc_expr, 0))
# Specialized versions of (op,cond) to make claripy happy
def pc_actions_SUB_CondZ(state, arg_l, arg_r, cc_ndep):
return _cond_flag(state, arg_l == arg_r)
def pc_actions_SUB_CondNZ(state, arg_l, arg_r, cc_ndep):
return _cond_flag(state, arg_l != arg_r)
def pc_actions_SUB_CondB(state, arg_l, arg_r, cc_ndep):
return _cond_flag(state, state.solver.ULT(arg_l, arg_r))
def pc_actions_SUB_CondBE(state, arg_l, arg_r, cc_ndep):
return _cond_flag(state, state.solver.ULE(arg_l, arg_r))
def pc_actions_SUB_CondNBE(state, arg_l, arg_r, cc_ndep):
return _cond_flag(state, state.solver.UGT(arg_l, arg_r))
def pc_actions_SUB_CondL(state, arg_l, arg_r, cc_ndep):
return _cond_flag(state, state.solver.SLT(arg_l, arg_r))
def pc_actions_SUB_CondLE(state, arg_l, arg_r, cc_ndep):
return _cond_flag(state, state.solver.SLE(arg_l, arg_r))
def pc_actions_SUB_CondNLE(state, arg_l, arg_r, cc_ndep):
return _cond_flag(state, state.solver.SGT(arg_l, arg_r))
def pc_calculate_condition_simple(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep, platform=None):
"""
A simplified version of pc_calculate_condition(). Please refer to the documentation of Simplified CCalls above.
Limitation: symbolic flags are not supported for now.
"""
if state.solver.symbolic(cond):
raise SimError("Hit a symbolic 'cond' in pc_calculate_condition. Panic.")
v = flag_concretize(state, cond)
# Extract the operation
cc_op = flag_concretize(state, cc_op)
if cc_op == data[platform]['OpTypes']['G_CC_OP_COPY']:
raise SimCCallError("G_CC_OP_COPY is not supported in pc_calculate_condition_simple(). Consider implementing.")
if cc_op == data[platform]['OpTypes']['G_CC_OP_NUMBER']:
raise SimCCallError("G_CC_OP_NUMBER is not supported in pc_calculate_condition_simple(). Consider implementing.")
op = data_inverted[platform]['OpTypes'][cc_op]
nbits = _get_nbits(op)
op = op[8 : -1]
# Extract the condition
cond = None
# TODO: Convert it to a table-lookup later
for key, cond_val in data[platform]['CondTypes'].items():
if cond_val == v:
cond = key
break
cc_dep1_nbits = cc_dep1[nbits-1:0]
cc_dep2_nbits = cc_dep2[nbits-1:0]
# check for a specialized version first
funcname = "pc_actions_%s_%s" % (op, cond)
if funcname in globals():
r = globals()[funcname](state, cc_dep1_nbits, cc_dep2_nbits, cc_ndep)
else:
op_funcname = "pc_actions_op_%s" % op
cond_funcname = "pc_actions_cond_%s" % cond
if op_funcname in globals() and cond_funcname in globals():
cc_expr = globals()[op_funcname](cc_dep1_nbits, cc_dep2_nbits, cc_ndep)
r = globals()[cond_funcname](state, cc_expr)
else:
l.warning('Operation %s with condition %s is not supported in pc_calculate_condition_simple(). Consider implementing.', op, cond)
raise SimCCallError('Operation %s with condition %s not found.' % (op, cond))
return state.solver.Concat(state.solver.BVV(0, state.arch.bits - 1), r), []
def pc_calculate_rdata_c(state, cc_op, cc_dep1, cc_dep2, cc_ndep, platform=None):
cc_op = flag_concretize(state, cc_op)
if cc_op == data[platform]['OpTypes']['G_CC_OP_COPY']:
return state.solver.LShR(cc_dep1, data[platform]['CondBitOffsets']['G_CC_SHIFT_C']) & 1, [ ] # TODO: actual constraints
elif cc_op in ( data[platform]['OpTypes']['G_CC_OP_LOGICQ'], data[platform]['OpTypes']['G_CC_OP_LOGICL'], data[platform]['OpTypes']['G_CC_OP_LOGICW'], data[platform]['OpTypes']['G_CC_OP_LOGICB'] ):
return state.solver.BVV(0, state.arch.bits), [ ] # TODO: actual constraints
rdata_all = pc_calculate_rdata_all_WRK(state, cc_op,cc_dep1,cc_dep2,cc_ndep, platform=platform)
if isinstance(rdata_all, tuple):
cf, pf, af, zf, sf, of = rdata_all
return state.solver.Concat(state.solver.BVV(0, state.arch.bits-1), cf & 1), [ ]
else:
return state.solver.LShR(rdata_all, data[platform]['CondBitOffsets']['G_CC_SHIFT_C']) & 1, []
def generic_rotate_with_carry(state, left, arg, rot_amt, carry_bit_in, sz):
# returns cf, of, result
# make sure sz is not symbolic
if sz.symbolic:
raise SimError('Hit a symbolic "sz" in an x86 rotate with carry instruction. Panic.')
# convert sz to concrete value
sz = state.solver.eval_one(sz)
bits = sz * 8
bits_in = len(arg)
# construct bitvec to use for rotation amount - 9/17/33/65 bits
if bits > len(rot_amt):
raise SimError("Got a rotate instruction for data larger than the provided word size. Panic.")
if bits == len(rot_amt):
sized_amt = (rot_amt & (bits_in - 1)).zero_extend(1)
else:
sized_amt = (rot_amt & (bits_in - 1))[bits:0]
assert len(sized_amt) == bits + 1
# construct bitvec to use for rotating value - 9/17/33/65 bits
sized_arg_in = arg[bits-1:0]
rotatable_in = carry_bit_in.concat(sized_arg_in)
# compute and extract
op = state.solver.RotateLeft if left else state.solver.RotateRight
rotatable_out = op(rotatable_in, sized_amt)
sized_arg_out = rotatable_out[bits-1:0]
carry_bit_out = rotatable_out[bits]
arg_out = sized_arg_out.zero_extend(bits_in - bits)
if left:
overflow_bit_out = carry_bit_out ^ sized_arg_out[bits-1]
else:
overflow_bit_out = sized_arg_out[bits-1] ^ sized_arg_out[bits-2]
# construct final answer
return carry_bit_out, overflow_bit_out, arg_out
###########################
### AMD64-specific ones ###
###########################
# https://github.com/angr/vex/blob/master/priv/guest_amd64_helpers.c#L2272
def amd64g_check_ldmxcsr(state, mxcsr):
# /* Decide on a rounding mode. mxcsr[14:13] holds it. */
# /* NOTE, encoded exactly as per enum IRRoundingMode. */
rmode = (mxcsr >> 13) & 3
# /* Detect any required emulation warnings. */
ew = EmNote_NONE
if ((mxcsr & 0x1F80) != 0x1F80).is_true:
# /* unmasked exceptions! */
ew = EmWarn_X86_sseExns
elif (mxcsr & (1 << 15)).is_true:
# /* FZ is set */
ew = EmWarn_X86_fz
elif (mxcsr & (1 << 6)).is_true:
# /* DAZ is set */
ew = EmWarn_X86_daz
return (ew << 32) | rmode, []
# https://github.com/angr/vex/blob/master/priv/guest_amd64_helpers.c#L2304
def amd64g_create_mxcsr(state, sseround):
sseround &= 3
return 0x1F80 | (sseround << 13), []
# https://github.com/angr/vex/blob/master/priv/guest_amd64_helpers.c#L2316
def amd64g_check_fldcw(state, fpucw):
rmode = (fpucw >> 10) & 3
ew = EmNote_NONE
if ((fpucw & 0x3f) != 0x3f).is_true:
# unmasked exceptions
ew = EmWarn_X86_x87exns
elif (((fpucw >> 8) & 3) != 3).is_true:
ew = EmWarn_X86_x87precision
return (ew << 32) | rmode, []
# https://github.com/angr/vex/blob/master/priv/guest_amd64_helpers.c#L2342
def amd64g_create_fpucw(state, fpround):
fpround &= 3
return 0x037f | (fpround << 10), []
def amd64g_calculate_RCL(state, arg, rot_amt, eflags_in, sz):
want_flags = state.solver.is_true(state.solver.SLT(sz, 0))
if want_flags: sz = -sz
carry_bit_in = eflags_in[data['AMD64']['CondBitOffsets']['G_CC_SHIFT_C']]
carry_bit_out, overflow_bit_out, arg_out = generic_rotate_with_carry(state, True, arg, rot_amt, carry_bit_in, sz)
if want_flags:
cf = carry_bit_out.zero_extend(63)
of = overflow_bit_out.zero_extend(63)
eflags_out = eflags_in
eflags_out &= ~(data['AMD64']['CondBitMasks']['G_CC_MASK_C'] | data['AMD64']['CondBitMasks']['G_CC_MASK_O'])
eflags_out |= (cf << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_C']) | \
(of << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_O'])
return eflags_out, []
else:
return arg_out, []
def amd64g_calculate_RCR(state, arg, rot_amt, eflags_in, sz):
want_flags = state.solver.is_true(state.solver.SLT(sz, 0))
if want_flags: sz = -sz
carry_bit_in = eflags_in[data['AMD64']['CondBitOffsets']['G_CC_SHIFT_C']]
carry_bit_out, overflow_bit_out, arg_out = generic_rotate_with_carry(state, False, arg, rot_amt, carry_bit_in, sz)
if want_flags:
cf = carry_bit_out.zero_extend(63)
of = overflow_bit_out.zero_extend(63)
eflags_out = eflags_in
eflags_out &= ~(data['AMD64']['CondBitMasks']['G_CC_MASK_C'] | data['AMD64']['CondBitMasks']['G_CC_MASK_O'])
eflags_out |= (cf << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_C']) | \
(of << data['AMD64']['CondBitOffsets']['G_CC_SHIFT_O'])
return eflags_out, []
else:
return arg_out, []
def amd64g_calculate_mmx_pmaddwd(_state, xx, yy):
xx_3, xx_2, xx_1, xx_0 = xx.chop(16)
yy_3, yy_2, yy_1, yy_0 = yy.chop(16)
xx_3 = xx_3.sign_extend(16)
xx_2 = xx_2.sign_extend(16)
xx_1 = xx_1.sign_extend(16)
xx_0 = xx_0.sign_extend(16)
yy_3 = yy_3.sign_extend(16)
yy_2 = yy_2.sign_extend(16)
yy_1 = yy_1.sign_extend(16)
yy_0 = yy_0.sign_extend(16)
res_1 = xx_3 * yy_3 + xx_2 * yy_2
res_0 = xx_1 * yy_1 + xx_0 * yy_0
return claripy.Concat(res_1, res_0), []
def amd64g_calculate_condition(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep):
if USE_SIMPLIFIED_CCALLS in state.options:
try:
return pc_calculate_condition_simple(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep, platform='AMD64')
except KeyError:
pass
return pc_calculate_condition(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep, platform='AMD64')
def amd64g_calculate_rflags_all(state, cc_op, cc_dep1, cc_dep2, cc_ndep):
return pc_calculate_rdata_all(state, cc_op, cc_dep1, cc_dep2, cc_ndep, platform='AMD64')
def amd64g_calculate_rflags_c(state, cc_op, cc_dep1, cc_dep2, cc_ndep):
return pc_calculate_rdata_c(state, cc_op, cc_dep1, cc_dep2, cc_ndep, platform='AMD64')
###########################
### X86-specific ones ###
###########################
def x86g_calculate_RCL(state, arg, rot_amt, eflags_in, sz):
carry_bit_in = eflags_in[data['X86']['CondBitOffsets']['G_CC_SHIFT_C']]
carry_bit_out, overflow_bit_out, arg_out = generic_rotate_with_carry(state, True, arg, rot_amt, carry_bit_in, sz)
cf = carry_bit_out.zero_extend(31)
of = overflow_bit_out.zero_extend(31)
eflags_out = eflags_in
eflags_out &= ~(data['X86']['CondBitMasks']['G_CC_MASK_C'] | data['X86']['CondBitMasks']['G_CC_MASK_O'])
eflags_out |= (cf << data['X86']['CondBitOffsets']['G_CC_SHIFT_C']) | \
(of << data['X86']['CondBitOffsets']['G_CC_SHIFT_O'])
return eflags_out.concat(arg_out), []
def x86g_calculate_RCR(state, arg, rot_amt, eflags_in, sz):
carry_bit_in = eflags_in[data['X86']['CondBitOffsets']['G_CC_SHIFT_C']]
carry_bit_out, overflow_bit_out, arg_out = generic_rotate_with_carry(state, False, arg, rot_amt, carry_bit_in, sz)
cf = carry_bit_out.zero_extend(31)
of = overflow_bit_out.zero_extend(31)
eflags_out = eflags_in
eflags_out &= ~(data['X86']['CondBitMasks']['G_CC_MASK_C'] | data['X86']['CondBitMasks']['G_CC_MASK_O'])
eflags_out |= (cf << data['X86']['CondBitOffsets']['G_CC_SHIFT_C']) | \
(of << data['X86']['CondBitOffsets']['G_CC_SHIFT_O'])
return eflags_out.concat(arg_out), []
def x86g_calculate_condition(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep):
if USE_SIMPLIFIED_CCALLS in state.options:
return pc_calculate_condition_simple(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep, platform='X86')
else:
return pc_calculate_condition(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep, platform='X86')
def x86g_calculate_eflags_all(state, cc_op, cc_dep1, cc_dep2, cc_ndep):
return pc_calculate_rdata_all(state, cc_op, cc_dep1, cc_dep2, cc_ndep, platform='X86')
def x86g_calculate_eflags_c(state, cc_op, cc_dep1, cc_dep2, cc_ndep):
return pc_calculate_rdata_c(state, cc_op, cc_dep1, cc_dep2, cc_ndep, platform='X86')
def x86g_check_fldcw(state, fpucw):
return ((fpucw >> 10) & 3).zero_extend(32), ()
def x86g_create_fpucw(state, fpround):
return 0x037f | ((fpround & 3) << 10), ()
def x86g_calculate_daa_das_aaa_aas(state, flags_and_AX, opcode):
assert len(flags_and_AX) == 32
assert not opcode.symbolic
opcode = state.solver.eval(opcode)
r_O = flags_and_AX[data['X86']['CondBitOffsets']['G_CC_SHIFT_O'] + 16].zero_extend(31)
r_S = flags_and_AX[data['X86']['CondBitOffsets']['G_CC_SHIFT_S'] + 16].zero_extend(31)
r_Z = flags_and_AX[data['X86']['CondBitOffsets']['G_CC_SHIFT_Z'] + 16].zero_extend(31)
r_A = flags_and_AX[data['X86']['CondBitOffsets']['G_CC_SHIFT_A'] + 16].zero_extend(31)
r_C = flags_and_AX[data['X86']['CondBitOffsets']['G_CC_SHIFT_C'] + 16].zero_extend(31)
r_P = flags_and_AX[data['X86']['CondBitOffsets']['G_CC_SHIFT_P'] + 16].zero_extend(31)
r_AL = (flags_and_AX >> 0) & 0xFF
r_AH = (flags_and_AX >> 8) & 0xFF
zero = state.solver.BVV(0, 32)
one = state.solver.BVV(1, 32)
if opcode == 0x27: # DAA
old_AL = r_AL
old_C = r_C
condition = state.solver.Or((r_AL & 0xF) > 9, r_A == 1)
r_AL = state.solver.If(condition, r_AL + 6, old_AL)
r_C = state.solver.If(condition, state.solver.If(r_AL >= 0x100, one, old_C), zero)
r_A = state.solver.If(condition, one, zero)
condition = state.solver.Or(old_AL > 0x99, old_C == 1)
r_AL = state.solver.If(condition, r_AL + 0x60, r_AL)
r_C = state.solver.If(condition, one, zero)
r_AL = r_AL&0xFF
r_O = zero
r_S = state.solver.If((r_AL & 0x80) != 0, one, zero)
r_Z = state.solver.If(r_AL == 0, one, zero)
r_P = calc_paritybit(state, r_AL).zero_extend(31)
elif opcode == 0x2F: # DAS
old_AL = r_AL
old_C = r_C
condition = state.solver.Or((r_AL & 0xF) > 9, r_A == 1)
r_AL = state.solver.If(condition, r_AL - 6, old_AL)
r_C = state.solver.If(condition, state.solver.If(r_AL < 6, one, zero), zero)
r_A = state.solver.If(condition, one, zero)
condition = state.solver.Or(old_AL > 0x99, old_C == 1)
r_AL = state.solver.If(condition, r_AL - 0x60, r_AL)
r_C = state.solver.If(condition, one, zero)
r_AL &= 0xFF
r_O = zero
r_S = state.solver.If((r_AL & 0x80) != 0, one, zero)
r_Z = state.solver.If(r_AL == 0, one, zero)
r_P = calc_paritybit(state, r_AL).zero_extend(31)
elif opcode == 0x37: # AAA
nudge = r_AL > 0xF9
condition = state.solver.Or((r_AL & 0xF) > 9, r_A == 1)
r_AL = state.solver.If(condition, (r_AL + 6) & 0xF, r_AL & 0xF)
r_AH = state.solver.If(condition, state.solver.If(nudge, r_AH + 2, r_AH + 1), r_AH)
r_A = state.solver.If(condition, one, zero)
r_C = state.solver.If(condition, one, zero)
r_O = r_S = r_Z = r_P = 0
elif opcode == 0x3F: # AAS
nudge = r_AL < 0x06
condition = state.solver.Or((r_AL & 0xF) > 9, r_A == 1)
r_AL = state.solver.If(condition, (r_AL - 6) & 0xF, r_AL & 0xF)
r_AH = state.solver.If(condition, state.solver.If(nudge, r_AH - 2, r_AH - 1), r_AH)
r_A = state.solver.If(condition, one, zero)
r_C = state.solver.If(condition, one, zero)
r_O = r_S = r_Z = r_P = 0
result = ( (r_O & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_O']) ) \
| ( (r_S & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_S']) ) \
| ( (r_Z & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_Z']) ) \
| ( (r_A & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_A']) ) \
| ( (r_C & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_C']) ) \
| ( (r_P & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_P']) ) \
| ( (r_AH & 0xFF) << 8 ) \
| ( (r_AL & 0xFF) << 0 )
return result, []
def x86g_calculate_aad_aam(state, flags_and_AX, opcode):
assert len(flags_and_AX) == 32
assert not opcode.symbolic
opcode = state.solver.eval(opcode)
r_AL = (flags_and_AX >> 0) & 0xFF
r_AH = (flags_and_AX >> 8) & 0xFF
if opcode == 0xD4: # AAM
r_AH = r_AL // 10
r_AL = r_AL % 10
elif opcode == 0xD5: # AAD
r_AL = ((r_AH * 10) + r_AL) & 0xff
r_AH = state.solver.BVV(0, 32)
else:
raise SimCCallError("Unknown opcode %#x in AAD/AAM ccall" % opcode)
r_O = state.solver.BVV(0, 32)
r_C = state.solver.BVV(0, 32)
r_A = state.solver.BVV(0, 32)
r_S = r_AL[7].zero_extend(31)
r_Z = state.solver.If(r_AL == 0, state.solver.BVV(1, 32), state.solver.BVV(0, 32))
r_P = calc_paritybit(state, r_AL).zero_extend(31)
result = ( (r_O & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_O']) ) \
| ( (r_S & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_S']) ) \
| ( (r_Z & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_Z']) ) \
| ( (r_A & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_A']) ) \
| ( (r_C & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_C']) ) \
| ( (r_P & 1) << (16 + data['X86']['CondBitOffsets']['G_CC_SHIFT_P']) ) \
| ( (r_AH & 0xFF) << 8 ) \
| ( (r_AL & 0xFF) << 0 )
return result, []
#
# x86 segment selection
#
# Reference for the GDT entry layout
# http://wiki.osdev.org/Global_Descriptor_Table
def get_segdescr_base(state, descriptor):
lo = descriptor[31:16]
mid = descriptor[39:32]
hi = descriptor[63:56]
return state.solver.Concat(hi, mid, lo)
def get_segdescr_limit(state, descriptor):
granularity = descriptor[55]
lo = descriptor[15:0]
hi = descriptor[51:48]
limit = state.solver.Concat(hi, lo).zero_extend(12)
if state.solver.is_true(granularity == 0):
return limit
else:
return (limit << 12) | 0xfff
def x86g_use_seg_selector(state, ldt, gdt, seg_selector, virtual_addr):
# TODO Read/write/exec bit handling
def bad(msg):
if msg:
l.warning("x86g_use_seg_selector: %s", msg)
return state.solver.BVV(1 << 32, state.arch.bits).zero_extend(32), ()
if state.solver.is_true(seg_selector & ~0xFFFF != 0):
return bad("invalid selector (" + str(seg_selector) + ")")
if virtual_addr.length == 16:
virtual_addr = virtual_addr.zero_extend(16)
# are we in real mode?
if state.arch.vex_archinfo['x86_cr0'] & 1 == 0:
return ((seg_selector << 4) + virtual_addr).zero_extend(32), ()
seg_selector &= 0x0000FFFF
segment_selector_val = state.solver.eval(seg_selector >> 3)
if state.project.simos.name == "Win32" and segment_selector_val == 0x6 and state.project.concrete_target is not None:
return bad("angr doesn't support Windows Heaven's gate calls http://rce.co/knockin-on-heavens-gate-dynamic-processor-mode-switching/ \n"
"Please use the native 32 bit libs (not WoW64) or implement a simprocedure to avoid executing these instructions"
)
# RPL=11 check
#if state.solver.is_true((seg_selector & 3) != 3):
# return bad()
tiBit = (seg_selector >> 2) & 1
if state.solver.is_true(tiBit == 0):
# GDT access
gdt_value = state.solver.eval_one(gdt)
if gdt_value == 0:
return ((seg_selector << 16) + virtual_addr).zero_extend(32), ()
seg_selector >>= 3 # bit 3 to 15 are the index in the table
seg_selector = seg_selector.zero_extend(32)
gdt_limit = gdt[15:0]
if state.solver.is_true(seg_selector >= gdt_limit.zero_extend(48)):
return bad("index out of range")
gdt_base = gdt[47:16]
gdt_base_value = state.solver.eval_one(gdt_base)
descriptor = state.memory.load(gdt_base_value + seg_selector * 8, 8, endness='Iend_LE')
else:
# LDT access
ldt_value = state.solver.eval_one(ldt)
if ldt_value == 0:
return ((seg_selector << 16) + virtual_addr).zero_extend(32), ()
seg_selector >>= 3 # bit 3 to 15 are the index in the table
seg_selector = seg_selector.zero_extend(32)
ldt_limit = ldt[15:0]
if state.solver.is_true(seg_selector >= ldt_limit.zero_extend(48)):
return bad("index out of range")
ldt_base = ldt[47:16]
ldt_base_value = state.solver.eval_one(ldt_base)
ldt_value = state.solver.eval_one(ldt_base)
descriptor = state.memory.load(ldt_value + seg_selector * 8, 8, endness='Iend_LE')
present = descriptor[47]
if state.solver.is_true(present == 0):
return bad("present bit set to 0")
base = get_segdescr_base(state, descriptor)
limit = get_segdescr_limit(state, descriptor)
# When a concrete target is set and memory is read directly from the process sometimes a negative offset
# from a segment register is used
# if state.solver.is_true(virtual_addr >= limit) and state.project.concrete_target is None:
# return bad("virtual_addr >= limit")
r = (base + virtual_addr).zero_extend(32)
l.debug("x86g_use_seg_selector: addr=%s", str(r))
return r, ()
#
# other amd64 craziness
#
EmNote_NONE = 0
EmWarn_X86_x87exns = 1
EmWarn_X86_x87precision = 2
EmWarn_X86_sseExns = 3
EmWarn_X86_fz = 4
EmWarn_X86_daz = 5
EmWarn_X86_acFlag = 6
EmWarn_PPCexns = 7
EmWarn_PPC64_redir_overflow = 8
EmWarn_PPC64_redir_underflow = 9
EmWarn_S390X_fpext_rounding = 10
EmWarn_S390X_invalid_rounding = 11
EmFail_S390X_stfle = 12
EmFail_S390X_stckf = 13
EmFail_S390X_ecag = 14
EmFail_S390X_pfpo = 15
EmFail_S390X_DFP_insn = 16
EmFail_S390X_fpext = 17
EmFail_S390X_invalid_PFPO_rounding_mode = 18
EmFail_S390X_invalid_PFPO_function = 19
def amd64g_create_mxcsr(state, sseround):
return 0x1F80 | ((sseround & 3) << 13), ()
def amd64g_check_ldmxcsr(state, mxcsr):
rmode = state.solver.LShR(mxcsr, 13) & 3
ew = state.solver.If(
(mxcsr & 0x1F80) != 0x1F80,
state.solver.BVV(EmWarn_X86_sseExns, 64),
state.solver.If(
mxcsr & (1<<15) != 0,
state.solver.BVV(EmWarn_X86_fz, 64),
state.solver.If(
mxcsr & (1<<6) != 0,
state.solver.BVV(EmWarn_X86_daz, 64),
state.solver.BVV(EmNote_NONE, 64)
)
)
)
return (ew << 32) | rmode, ()
#################
### ARM Flags ###
#################
ARMCondEQ = 0 # /* equal : Z=1 */
ARMCondNE = 1 # /* not equal : Z=0 */
ARMCondHS = 2 # /* >=u (higher or same) : C=1 */
ARMCondLO = 3 # /* <u (lower) : C=0 */
ARMCondMI = 4 # /* minus (negative) : N=1 */
ARMCondPL = 5 # /* plus (zero or +ve) : N=0 */
ARMCondVS = 6 # /* overflow : V=1 */
ARMCondVC = 7 # /* no overflow : V=0 */
ARMCondHI = 8 # /* >u (higher) : C=1 && Z=0 */
ARMCondLS = 9 # /* <=u (lower or same) : C=0 || Z=1 */
ARMCondGE = 10 # /* >=s (signed greater or equal) : N=V */
ARMCondLT = 11 # /* <s (signed less than) : N!=V */
ARMCondGT = 12 # /* >s (signed greater) : Z=0 && N=V */
ARMCondLE = 13 # /* <=s (signed less or equal) : Z=1 || N!=V */
ARMCondAL = 14 # /* always (unconditional) : 1 */
ARMCondNV = 15 # /* never (unconditional): : 0 */
ARMG_CC_OP_COPY = 0 # /* DEP1 = NZCV in 31:28, DEP2 = 0, DEP3 = 0 just copy DEP1 to output */
ARMG_CC_OP_ADD = 1 # /* DEP1 = argL (Rn) = DEP2 = argR (shifter_op) = DEP3 = 0 */
ARMG_CC_OP_SUB = 2 # /* DEP1 = argL (Rn) = DEP2 = argR (shifter_op) = DEP3 = 0 */
ARMG_CC_OP_ADC = 3 # /* DEP1 = argL (Rn) = DEP2 = arg2 (shifter_op) = DEP3 = oldC (in LSB) */
ARMG_CC_OP_SBB = 4 # /* DEP1 = argL (Rn) = DEP2 = arg2 (shifter_op) = DEP3 = oldC (in LSB) */
ARMG_CC_OP_LOGIC = 5 # /* DEP1 = result = DEP2 = shifter_carry_out (in LSB) = DEP3 = old V flag (in LSB) */
ARMG_CC_OP_MUL = 6 # /* DEP1 = result = DEP2 = 0 = DEP3 = oldC:old_V (in bits 1:0) */
ARMG_CC_OP_MULL = 7 # /* DEP1 = resLO32 = DEP2 = resHI32 = DEP3 = oldC:old_V (in bits 1:0) */
ARMG_CC_OP_NUMBER = 8
ARMG_CC_SHIFT_N = 31
ARMG_CC_SHIFT_Z = 30
ARMG_CC_SHIFT_C = 29
ARMG_CC_SHIFT_V = 28
ARMG_CC_SHIFT_Q = 27
ARMG_NBITS = 32
def armg_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
concrete_op = flag_concretize(state, cc_op)
flag = None
if concrete_op == ARMG_CC_OP_COPY:
flag = state.solver.LShR(cc_dep1, ARMG_CC_SHIFT_N) & 1
elif concrete_op == ARMG_CC_OP_ADD:
res = cc_dep1 + cc_dep2
flag = state.solver.LShR(res, 31)
elif concrete_op == ARMG_CC_OP_SUB:
res = cc_dep1 - cc_dep2
flag = state.solver.LShR(res, 31)
elif concrete_op == ARMG_CC_OP_ADC:
res = cc_dep1 + cc_dep2 + cc_dep3
flag = state.solver.LShR(res, 31)
elif concrete_op == ARMG_CC_OP_SBB:
res = cc_dep1 - cc_dep2 - (cc_dep3^1)
flag = state.solver.LShR(res, 31)
elif concrete_op == ARMG_CC_OP_LOGIC:
flag = state.solver.LShR(cc_dep1, 31)
elif concrete_op == ARMG_CC_OP_MUL:
flag = state.solver.LShR(cc_dep1, 31)
elif concrete_op == ARMG_CC_OP_MULL:
flag = state.solver.LShR(cc_dep2, 31)
if flag is not None: return flag, [ cc_op == concrete_op ]
l.error("Unknown cc_op %s (armg_calculate_flag_n)", cc_op)
raise SimCCallError("Unknown cc_op %s" % cc_op)
def arm_zerobit(state, x):
return calc_zerobit(state, x).zero_extend(31)
def armg_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
concrete_op = flag_concretize(state, cc_op)
flag = None
if concrete_op == ARMG_CC_OP_COPY:
flag = state.solver.LShR(cc_dep1, ARMG_CC_SHIFT_Z) & 1
elif concrete_op == ARMG_CC_OP_ADD:
res = cc_dep1 + cc_dep2
flag = arm_zerobit(state, res)
elif concrete_op == ARMG_CC_OP_SUB:
res = cc_dep1 - cc_dep2
flag = arm_zerobit(state, res)
elif concrete_op == ARMG_CC_OP_ADC:
res = cc_dep1 + cc_dep2 + cc_dep3
flag = arm_zerobit(state, res)
elif concrete_op == ARMG_CC_OP_SBB:
res = cc_dep1 - cc_dep2 - (cc_dep3^1)
flag = arm_zerobit(state, res)
elif concrete_op == ARMG_CC_OP_LOGIC:
flag = arm_zerobit(state, cc_dep1)
elif concrete_op == ARMG_CC_OP_MUL:
flag = arm_zerobit(state, cc_dep1)
elif concrete_op == ARMG_CC_OP_MULL:
flag = arm_zerobit(state, cc_dep1 | cc_dep2)
if flag is not None: return flag, [ cc_op == concrete_op ]
l.error("Unknown cc_op %s (armg_calculate_flag_z)", concrete_op)
raise SimCCallError("Unknown cc_op %s" % concrete_op)
def armg_calculate_flag_c(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
concrete_op = flag_concretize(state, cc_op)
flag = None
if concrete_op == ARMG_CC_OP_COPY:
flag = state.solver.LShR(cc_dep1, ARMG_CC_SHIFT_C) & 1
elif concrete_op == ARMG_CC_OP_ADD:
res = cc_dep1 + cc_dep2
flag = boolean_extend(state, state.solver.ULT, res, cc_dep1, 32)
elif concrete_op == ARMG_CC_OP_SUB:
flag = boolean_extend(state, state.solver.UGE, cc_dep1, cc_dep2, 32)
elif concrete_op == ARMG_CC_OP_ADC:
res = cc_dep1 + cc_dep2 + cc_dep3
flag = state.solver.If(cc_dep3 != 0, boolean_extend(state, state.solver.ULE, res, cc_dep1, 32), boolean_extend(state, state.solver.ULT, res, cc_dep1, 32))
elif concrete_op == ARMG_CC_OP_SBB:
flag = state.solver.If(cc_dep3 != 0, boolean_extend(state, state.solver.UGE, cc_dep1, cc_dep2, 32), boolean_extend(state, state.solver.UGT, cc_dep1, cc_dep2, 32))
elif concrete_op == ARMG_CC_OP_LOGIC:
flag = cc_dep2
elif concrete_op == ARMG_CC_OP_MUL:
flag = (state.solver.LShR(cc_dep3, 1)) & 1
elif concrete_op == ARMG_CC_OP_MULL:
flag = (state.solver.LShR(cc_dep3, 1)) & 1
if flag is not None: return flag, [ cc_op == concrete_op ]
l.error("Unknown cc_op %s (armg_calculate_flag_c)", cc_op)
raise SimCCallError("Unknown cc_op %s" % cc_op)
def armg_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
concrete_op = flag_concretize(state, cc_op)
flag = None
if concrete_op == ARMG_CC_OP_COPY:
flag = state.solver.LShR(cc_dep1, ARMG_CC_SHIFT_V) & 1
elif concrete_op == ARMG_CC_OP_ADD:
res = cc_dep1 + cc_dep2
v = ((res ^ cc_dep1) & (res ^ cc_dep2))
flag = state.solver.LShR(v, 31)
elif concrete_op == ARMG_CC_OP_SUB:
res = cc_dep1 - cc_dep2
v = ((cc_dep1 ^ cc_dep2) & (cc_dep1 ^ res))
flag = state.solver.LShR(v, 31)
elif concrete_op == ARMG_CC_OP_ADC:
res = cc_dep1 + cc_dep2 + cc_dep3
v = ((res ^ cc_dep1) & (res ^ cc_dep2))
flag = state.solver.LShR(v, 31)
elif concrete_op == ARMG_CC_OP_SBB:
res = cc_dep1 - cc_dep2 - (cc_dep3^1)
v = ((cc_dep1 ^ cc_dep2) & (cc_dep1 ^ res))
flag = state.solver.LShR(v, 31)
elif concrete_op == ARMG_CC_OP_LOGIC:
flag = cc_dep3
elif concrete_op == ARMG_CC_OP_MUL:
flag = cc_dep3 & 1
elif concrete_op == ARMG_CC_OP_MULL:
flag = cc_dep3 & 1
if flag is not None: return flag, [ cc_op == concrete_op ]
l.error("Unknown cc_op %s (armg_calculate_flag_v)", cc_op)
raise SimCCallError("Unknown cc_op %s" % cc_op)
def armg_calculate_flags_nzcv(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
# NOTE: adding constraints afterwards works here *only* because the constraints are actually useless, because we require
# cc_op to be unique. If we didn't, we'd need to pass the constraints into any functions called after the constraints were
# created.
n, c1 = armg_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
z, c2 = armg_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
c, c3 = armg_calculate_flag_c(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
v, c4 = armg_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
vec = [(ARMG_CC_SHIFT_N, state.solver.Extract(0, 0, n)),
(ARMG_CC_SHIFT_Z, state.solver.Extract(0, 0, z)),
(ARMG_CC_SHIFT_C, state.solver.Extract(0, 0, c)),
(ARMG_CC_SHIFT_V, state.solver.Extract(0, 0, v))]
return _concat_flags(ARMG_NBITS, vec), c1 + c2 + c3 + c4
def armg_calculate_condition(state, cond_n_op, cc_dep1, cc_dep2, cc_dep3):
cond = state.solver.LShR(cond_n_op, 4)
cc_op = cond_n_op & 0xF
inv = cond & 1
concrete_cond = flag_concretize(state, cond)
flag = None
c1,c2,c3 = [ ], [ ], [ ]
# NOTE: adding constraints afterwards works here *only* because the constraints are actually useless, because we require
# cc_op to be unique. If we didn't, we'd need to pass the constraints into any functions called after the constraints were
# created.
if concrete_cond == ARMCondAL:
flag = state.solver.BVV(1, 32)
elif concrete_cond in [ ARMCondEQ, ARMCondNE ]:
zf, c1 = armg_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ zf
elif concrete_cond in [ ARMCondHS, ARMCondLO ]:
cf, c1 = armg_calculate_flag_c(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ cf
elif concrete_cond in [ ARMCondMI, ARMCondPL ]:
nf, c1 = armg_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ nf
elif concrete_cond in [ ARMCondVS, ARMCondVC ]:
vf, c1 = armg_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ vf
elif concrete_cond in [ ARMCondHI, ARMCondLS ]:
cf, c1 = armg_calculate_flag_c(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
zf, c2 = armg_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ (cf & ~zf)
elif concrete_cond in [ ARMCondGE, ARMCondLT ]:
nf, c1 = armg_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
vf, c2 = armg_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ (1 & ~(nf ^ vf))
elif concrete_cond in [ ARMCondGT, ARMCondLE ]:
nf, c1 = armg_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
vf, c2 = armg_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
zf, c3 = armg_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ (1 & ~(zf | (nf ^ vf)))
if flag is not None: return flag, [ cond == concrete_cond ] + c1 + c2 + c3
l.error("Unrecognized condition %d in armg_calculate_condition", concrete_cond)
raise SimCCallError("Unrecognized condition %d in armg_calculate_condition" % concrete_cond)
ARM64G_CC_SHIFT_N = 31
ARM64G_CC_SHIFT_Z = 30
ARM64G_CC_SHIFT_C = 29
ARM64G_CC_SHIFT_V = 28
ARM64G_CC_OP_COPY=0 #/* DEP1 = NZCV in 31:28, DEP2 = 0, DEP3 = 0 just copy DEP1 to output */
ARM64G_CC_OP_ADD32=1 #/* DEP1 = argL (Rn), DEP2 = argR (shifter_op), DEP3 = 0 */
ARM64G_CC_OP_ADD64=2 #/* DEP1 = argL (Rn), DEP2 = argR (shifter_op), DEP3 = 0 */
ARM64G_CC_OP_SUB32=3 #/* DEP1 = argL (Rn), DEP2 = argR (shifter_op), DEP3 = 0 */
ARM64G_CC_OP_SUB64=4 #/* DEP1 = argL (Rn), DEP2 = argR (shifter_op), DEP3 = 0 */
ARM64G_CC_OP_ADC32=5 #/* DEP1 = argL (Rn), DEP2 = arg2 (shifter_op), DEP3 = oldC (in LSB) */
ARM64G_CC_OP_ADC64=6 #/* DEP1 = argL (Rn), DEP2 = arg2 (shifter_op), DEP3 = oldC (in LSB) */
ARM64G_CC_OP_SBC32=7 #/* DEP1 = argL (Rn), DEP2 = arg2 (shifter_op), DEP3 = oldC (in LSB) */
ARM64G_CC_OP_SBC64=8 #/* DEP1 = argL (Rn), DEP2 = arg2 (shifter_op), DEP3 = oldC (in LSB) */
ARM64G_CC_OP_LOGIC32=9 #/* DEP1 = result, DEP2 = 0, DEP3 = 0 */
ARM64G_CC_OP_LOGIC64=10 #/* DEP1 = result, DEP2 = 0, DEP3 = 0 */
ARM64G_CC_OP_NUMBER=11 #
ARM64CondEQ = 0 #/* equal : Z=1 */
ARM64CondNE = 1 #/* not equal : Z=0 */
ARM64CondCS = 2 #/* >=u (higher or same) (aka HS) : C=1 */
ARM64CondCC = 3 #/* <u (lower) (aka LO) : C=0 */
ARM64CondMI = 4 #/* minus (negative) : N=1 */
ARM64CondPL = 5 #/* plus (zero or +ve) : N=0 */
ARM64CondVS = 6 #/* overflow : V=1 */
ARM64CondVC = 7 #/* no overflow : V=0 */
ARM64CondHI = 8 #/* >u (higher) : C=1 && Z=0 */
ARM64CondLS = 9 #/* <=u (lower or same) : C=0 || Z=1 */
ARM64CondGE = 10 #/* >=s (signed greater or equal) : N=V */
ARM64CondLT = 11 #/* <s (signed less than) : N!=V */
ARM64CondGT = 12 #/* >s (signed greater) : Z=0 && N=V */
ARM64CondLE = 13 #/* <=s (signed less or equal) : Z=1 || N!=V */
ARM64CondAL = 14 #/* always (unconditional) : 1 */
ARM64CondNV = 15 #/* always (unconditional) : 1 */
ARM64G_NBITS = 64
def arm64g_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
concrete_op = flag_concretize(state, cc_op)
flag = None
cc_dep1, cc_dep2, cc_dep3 = arm64g_32bit_truncate_operands(concrete_op, cc_dep1, cc_dep2, cc_dep3)
if concrete_op == ARM64G_CC_OP_COPY:
flag = state.solver.LShR(cc_dep1, ARM64G_CC_SHIFT_N) & 1
elif concrete_op == ARM64G_CC_OP_ADD32:
res = cc_dep1 + cc_dep2
flag = state.solver.LShR(res, 31)
elif concrete_op == ARM64G_CC_OP_ADD64:
res = cc_dep1 + cc_dep2
flag = state.solver.LShR(res, 63)
elif concrete_op == ARM64G_CC_OP_SUB32:
res = cc_dep1 - cc_dep2
flag = state.solver.LShR(res, 31)
elif concrete_op == ARM64G_CC_OP_SUB64:
res = cc_dep1 - cc_dep2
flag = state.solver.LShR(res, 63)
elif concrete_op == ARM64G_CC_OP_ADC32:
res = cc_dep1 + cc_dep2 + cc_dep3
flag = state.solver.LShR(res, 31)
elif concrete_op == ARM64G_CC_OP_ADC64:
res = cc_dep1 + cc_dep2 + cc_dep3
flag = state.solver.LShR(res, 63)
elif concrete_op == ARM64G_CC_OP_SBC32:
res = cc_dep1 - cc_dep2 - (cc_dep3^1)
flag = state.solver.LShR(res, 31)
elif concrete_op == ARM64G_CC_OP_SBC64:
res = cc_dep1 - cc_dep2 - (cc_dep3^1)
flag = state.solver.LShR(res, 63)
elif concrete_op == ARM64G_CC_OP_LOGIC32:
flag = state.solver.LShR(cc_dep1, 31)
elif concrete_op == ARM64G_CC_OP_LOGIC64:
flag = state.solver.LShR(cc_dep1, 63)
if flag is not None: return flag, [ cc_op == concrete_op ]
l.error("Unknown cc_op %s (arm64g_calculate_flag_n)", cc_op)
raise SimCCallError("Unknown cc_op %s" % cc_op)
def arm64_zerobit(state, x):
return calc_zerobit(state, x).zero_extend(63)
def u64_to_u32(n):
return n[31:0]
def arm64g_32bit_truncate_operands(cc_op, cc_dep1, cc_dep2, cc_dep3):
# Truncate operands if in 32-bit mode
if cc_op in {ARM64G_CC_OP_ADD32, ARM64G_CC_OP_SUB32}:
cc_dep1 = u64_to_u32(cc_dep1)
cc_dep2 = u64_to_u32(cc_dep2)
elif cc_op in {ARM64G_CC_OP_ADC32, ARM64G_CC_OP_SBC32}:
cc_dep1 = u64_to_u32(cc_dep1)
cc_dep2 = u64_to_u32(cc_dep2)
cc_dep3 = u64_to_u32(cc_dep3)
elif cc_op == ARM64G_CC_OP_LOGIC32:
cc_dep1 = u64_to_u32(cc_dep1)
return cc_dep1, cc_dep2, cc_dep3
def arm64g_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
concrete_op = flag_concretize(state, cc_op)
flag = None
cc_dep1, cc_dep2, cc_dep3 = arm64g_32bit_truncate_operands(concrete_op, cc_dep1, cc_dep2, cc_dep3)
if concrete_op == ARM64G_CC_OP_COPY:
flag = state.solver.LShR(cc_dep1, ARM64G_CC_SHIFT_Z) & 1
elif concrete_op in (ARM64G_CC_OP_ADD32, ARM64G_CC_OP_ADD64):
res = cc_dep1 + cc_dep2
flag = arm64_zerobit(state, res)
elif concrete_op in (ARM64G_CC_OP_SUB32, ARM64G_CC_OP_SUB64):
res = cc_dep1 - cc_dep2
flag = arm64_zerobit(state, res)
elif concrete_op in (ARM64G_CC_OP_ADC32, ARM64G_CC_OP_ADC64):
res = cc_dep1 + cc_dep2 + cc_dep3
flag = arm64_zerobit(state, res)
elif concrete_op in (ARM64G_CC_OP_SBC32, ARM64G_CC_OP_SBC64):
res = cc_dep1 - cc_dep2 - (cc_dep3^1)
flag = arm64_zerobit(state, res)
elif concrete_op in (ARM64G_CC_OP_LOGIC32, ARM64G_CC_OP_LOGIC64):
flag = arm64_zerobit(state, cc_dep1)
if flag is not None: return flag, [ cc_op == concrete_op ]
l.error("Unknown cc_op %s (arm64g_calculate_flag_z)", concrete_op)
raise SimCCallError("Unknown cc_op %s" % concrete_op)
def arm64g_calculate_flag_c(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
concrete_op = flag_concretize(state, cc_op)
flag = None
cc_dep1, cc_dep2, cc_dep3 = arm64g_32bit_truncate_operands(concrete_op, cc_dep1, cc_dep2, cc_dep3)
if concrete_op == ARM64G_CC_OP_COPY:
flag = state.solver.LShR(cc_dep1, ARM64G_CC_SHIFT_C) & 1
elif concrete_op in (ARM64G_CC_OP_ADD32, ARM64G_CC_OP_ADD64):
res = cc_dep1 + cc_dep2
flag = boolean_extend(state, state.solver.ULT, res, cc_dep1, 64)
elif concrete_op in (ARM64G_CC_OP_SUB32, ARM64G_CC_OP_SUB64):
flag = boolean_extend(state, state.solver.UGE, cc_dep1, cc_dep2, 64)
elif concrete_op in (ARM64G_CC_OP_ADC32, ARM64G_CC_OP_ADC64):
res = cc_dep1 + cc_dep2 + cc_dep3
flag = state.solver.If(cc_dep2 != 0, boolean_extend(state, state.solver.ULE, res, cc_dep1, 64), boolean_extend(state, state.solver.ULT, res, cc_dep1, 64))
elif concrete_op in (ARM64G_CC_OP_SBC32, ARM64G_CC_OP_SBC64):
flag = state.solver.If(cc_dep2 != 0, boolean_extend(state, state.solver.UGE, cc_dep1, cc_dep2, 64), boolean_extend(state, state.solver.UGT, cc_dep1, cc_dep2, 64))
elif concrete_op in (ARM64G_CC_OP_LOGIC32, ARM64G_CC_OP_LOGIC64):
flag = state.solver.BVV(0, 64) # C after logic is zero on arm64
if flag is not None: return flag, [ cc_op == concrete_op ]
l.error("Unknown cc_op %s (arm64g_calculate_flag_c)", cc_op)
raise SimCCallError("Unknown cc_op %s" % cc_op)
def arm64g_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
concrete_op = flag_concretize(state, cc_op)
flag = None
cc_dep1, cc_dep2, cc_dep3 = arm64g_32bit_truncate_operands(concrete_op, cc_dep1, cc_dep2, cc_dep3)
if concrete_op == ARM64G_CC_OP_COPY:
flag = state.solver.LShR(cc_dep1, ARM64G_CC_SHIFT_V) & 1
elif concrete_op == ARM64G_CC_OP_ADD32:
cc_dep1 = cc_dep1[31:0]
cc_dep2 = cc_dep2[31:0]
res = cc_dep1 + cc_dep2
v = ((res ^ cc_dep1) & (res ^ cc_dep2))
flag = state.solver.LShR(v, 31).zero_extend(32)
elif concrete_op == ARM64G_CC_OP_ADD64:
res = cc_dep1 + cc_dep2
v = ((res ^ cc_dep1) & (res ^ cc_dep2))
flag = state.solver.LShR(v, 63)
elif concrete_op == ARM64G_CC_OP_SUB32:
cc_dep1 = cc_dep1[31:0]
cc_dep2 = cc_dep2[31:0]
res = cc_dep1 - cc_dep2
v = ((cc_dep1 ^ cc_dep2) & (cc_dep1 ^ res))
flag = state.solver.LShR(v, 31).zero_extend(32)
elif concrete_op == ARM64G_CC_OP_SUB64:
res = cc_dep1 - cc_dep2
v = ((cc_dep1 ^ cc_dep2) & (cc_dep1 ^ res))
flag = state.solver.LShR(v, 63)
elif concrete_op == ARM64G_CC_OP_ADC32:
cc_dep1 = cc_dep1[31:0]
cc_dep2 = cc_dep2[31:0]
res = cc_dep1 + cc_dep2 + cc_dep3
v = ((res ^ cc_dep1) & (res ^ cc_dep2))
flag = state.solver.LShR(v, 31).zero_extend(32)
elif concrete_op == ARM64G_CC_OP_ADC64:
res = cc_dep1 + cc_dep2 + cc_dep3
v = ((res ^ cc_dep1) & (res ^ cc_dep2))
flag = state.solver.LShR(v, 63)
elif concrete_op == ARM64G_CC_OP_SBC32:
cc_dep1 = cc_dep1[31:0]
cc_dep2 = cc_dep2[31:0]
res = cc_dep1 - cc_dep2 - (cc_dep3^1)
v = ((cc_dep1 ^ cc_dep2) & (cc_dep1 ^ res))
flag = state.solver.LShR(v, 31).zero_extend(32)
elif concrete_op == ARM64G_CC_OP_SBC64:
res = cc_dep1 - cc_dep2 - (cc_dep3^1)
v = ((cc_dep1 ^ cc_dep2) & (cc_dep1 ^ res))
flag = state.solver.LShR(v, 63)
elif concrete_op in (ARM64G_CC_OP_LOGIC32, ARM64G_CC_OP_LOGIC64):
flag = state.solver.BVV(0, 64)
if flag is not None: return flag, [ cc_op == concrete_op ]
l.error("Unknown cc_op %s (arm64g_calculate_flag_v)", cc_op)
raise SimCCallError("Unknown cc_op %s" % cc_op)
def arm64g_calculate_data_nzcv(state, cc_op, cc_dep1, cc_dep2, cc_dep3):
# NOTE: adding constraints afterwards works here *only* because the constraints are actually useless, because we require
# cc_op to be unique. If we didn't, we'd need to pass the constraints into any functions called after the constraints were
# created.
n, c1 = arm64g_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
z, c2 = arm64g_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
c, c3 = arm64g_calculate_flag_c(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
v, c4 = arm64g_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
vec = [(ARM64G_CC_SHIFT_N, state.solver.Extract(0, 0, n)),
(ARM64G_CC_SHIFT_Z, state.solver.Extract(0, 0, z)),
(ARM64G_CC_SHIFT_C, state.solver.Extract(0, 0, c)),
(ARM64G_CC_SHIFT_V, state.solver.Extract(0, 0, v))]
return _concat_flags(ARM64G_NBITS, vec), c1 + c2 + c3 + c4
def arm64g_calculate_condition(state, cond_n_op, cc_dep1, cc_dep2, cc_dep3):
cond = state.solver.LShR(cond_n_op, 4)
cc_op = cond_n_op & 0xF
inv = cond & 1
concrete_cond = flag_concretize(state, cond)
flag = None
c1,c2,c3 = [ ], [ ], [ ]
if concrete_cond in (ARM64CondAL, ARM64CondNV):
flag = state.solver.BVV(1, 64)
elif concrete_cond in (ARM64CondEQ, ARM64CondNE):
zf, c1 = arm64g_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ zf
elif concrete_cond in (ARM64CondCS, ARM64CondCC):
cf, c1 = arm64g_calculate_flag_c(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ cf
elif concrete_cond in (ARM64CondMI, ARM64CondPL):
nf, c1 = arm64g_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ nf
elif concrete_cond in (ARM64CondVS, ARM64CondVC):
vf, c1 = arm64g_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ vf
elif concrete_cond in (ARM64CondHI, ARM64CondLS):
cf, c1 = arm64g_calculate_flag_c(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
zf, c2 = arm64g_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ (1 & (cf & ~zf))
elif concrete_cond in (ARM64CondGE, ARM64CondLT):
nf, c1 = arm64g_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
vf, c2 = arm64g_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ (1 & ~(nf ^ vf))
elif concrete_cond in (ARM64CondGT, ARM64CondLE):
nf, c1 = arm64g_calculate_flag_n(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
vf, c2 = arm64g_calculate_flag_v(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
zf, c3 = arm64g_calculate_flag_z(state, cc_op, cc_dep1, cc_dep2, cc_dep3)
flag = inv ^ (1 & ~(zf | (nf ^ vf)))
if flag is not None: return flag, [ cond == concrete_cond ] + c1 + c2 + c3
l.error("Unrecognized condition %d in arm64g_calculate_condition", concrete_cond)
raise SimCCallError("Unrecognized condition %d in arm64g_calculate_condition" % concrete_cond)
#
# Some helpers
#
def _get_flags(state):
if state.arch.name == 'X86':
return x86g_calculate_eflags_all(state, state.regs.cc_op, state.regs.cc_dep1, state.regs.cc_dep2, state.regs.cc_ndep)
elif state.arch.name == 'AMD64':
return amd64g_calculate_rflags_all(state, state.regs.cc_op, state.regs.cc_dep1, state.regs.cc_dep2, state.regs.cc_ndep)
elif is_arm_arch(state.arch):
return armg_calculate_flags_nzcv(state, state.regs.cc_op, state.regs.cc_dep1, state.regs.cc_dep2, state.regs.cc_ndep)
elif state.arch.name == 'AARCH64':
return arm64g_calculate_data_nzcv(state, state.regs.cc_op, state.regs.cc_dep1, state.regs.cc_dep2, state.regs.cc_ndep)
else:
l.warning("No such thing as a flags register for arch %s", state.arch.name)
return None
def _concat_flags(nbits, flags_vec):
"""
Concatenate different flag BVs to a single BV. Currently used for ARM, X86
and AMD64.
:param nbits : platform size in bits.
:param flags_vec: vector of flag BVs and their offset in the resulting BV.
:type nbits : int
:type flags_vec : list
:return : the resulting flag BV.
:rtype : claripy.BVV
"""
result = claripy.BVV(0, 0)
for offset, bit in flags_vec:
current_position = nbits - 1 - result.length
result = result.concat(claripy.BVV(0, current_position - offset), bit)
result = result.concat(claripy.BVV(0, nbits - result.length))
return result
def _get_nbits(cc_str):
nbits = None
if cc_str.endswith('B'):
nbits = 8
elif cc_str.endswith('W'):
nbits = 16
elif cc_str.endswith('L'):
nbits = 32
elif cc_str.endswith('Q'):
nbits = 64
return nbits
from ...errors import SimError, SimCCallError
from ...sim_options import USE_SIMPLIFIED_CCALLS | data['AMD64']['OpTypes']['G_CC_OP_LOGICB'] = 17
data['AMD64']['OpTypes']['G_CC_OP_LOGICW'] = 18 |
appStudioValidator.ts | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license. | import axios, { AxiosInstance } from "axios";
import * as chai from "chai";
import MockAppStudioTokenProvider from "../../src/commonlib/appStudioLoginUserPassword";
import { AppStudioTokenProvider } from "@microsoft/teamsfx-api";
export class AppStudioValidator {
public static provider: AppStudioTokenProvider;
public static init(provider?: AppStudioTokenProvider) {
AppStudioValidator.provider = provider || MockAppStudioTokenProvider;
}
public static async validatePublish(appId: string): Promise<void> {
const token = await this.provider.getAccessToken();
chai.assert.isNotEmpty(token);
const requester = this.createRequesterWithToken(token!);
const response = await requester.get(`/api/publishing/${appId}`);
if (response.data.error) {
chai.assert.fail(`Publish failed, code: ${response.data.error.code}, message: ${response.data.error.message}`);
}
}
private static createRequesterWithToken(appStudioToken: string): AxiosInstance {
const instance = axios.create({
baseURL: "https://dev.teams.microsoft.com",
});
instance.defaults.headers.common["Authorization"] = `Bearer ${appStudioToken}`;
return instance;
}
} | |
MesosClient.ts | import { request } from "@dcos/mesos-client";
import { Observable } from "rxjs";
import { catchError, map } from "rxjs/operators";
import * as ValidatorUtil from "#SRC/js/utils/ValidatorUtil";
import { QuotaData, quotaFields } from "../types/Quota";
import { UpdateQuotaError } from "./errors/UpdateQuotaError";
import { OvercommitQuotaError } from "./errors/OvercommitQuotaError";
interface QuotaRequestValue {
value: number;
}
interface QuotaConfig {
role: string;
guarantees?: Record<string, QuotaRequestValue>;
limits?: Record<string, QuotaRequestValue>;
}
interface UpdateQuota {
force?: boolean;
quota_configs: QuotaConfig[];
}
interface UpdateQuotaRequest {
type: "UPDATE_QUOTA";
update_quota: UpdateQuota;
}
function roleFromGroupId(groupId: string): string {
return groupId.split("/").pop() || groupId;
}
function limitsFromQuotaFormData(
quotaData: QuotaData
): Record<string, QuotaRequestValue> {
const result: Record<string, QuotaRequestValue> = {};
for (const field of quotaFields) {
const value = (quotaData[field] + "").trim();
if (!ValidatorUtil.isEmpty(value)) {
result[field] = {
value: parseFloat(value),
};
}
}
return result;
}
function makeUpdateQuota(groupId: string, quotaData: QuotaData): UpdateQuota {
return {
force: quotaData.force,
quota_configs: [
{
role: roleFromGroupId(groupId),
limits: limitsFromQuotaFormData(quotaData),
},
],
}; | export function updateQuota(
groupId: string,
quotaData: QuotaData
): Observable<string> {
const updateQuotaReq: UpdateQuotaRequest = {
type: "UPDATE_QUOTA",
update_quota: makeUpdateQuota(groupId, quotaData),
};
return request(updateQuotaReq, "/mesos/api/v1?UPDATE_QUOTA").pipe(
map((response: string) => {
if (response === "") {
return "SUCCESS";
}
if (OvercommitQuotaError.isOvercommitError(response)) {
throw new OvercommitQuotaError(response, 400);
}
throw new UpdateQuotaError(response);
}),
catchError((resp) => {
const message = resp.response || resp.message;
if (OvercommitQuotaError.isOvercommitError(message)) {
throw new OvercommitQuotaError(message, resp.code);
}
throw new UpdateQuotaError(message, resp.code);
})
);
} | }
|
restapi.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package channelparticipation
import (
"encoding/json"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"path"
"strconv"
"strings"
"github.com/golang/protobuf/proto"
"github.com/gorilla/mux"
cb "github.com/hyperledger/fabric-protos-go/common"
"github.com/hyperledger/fabric/common/configtx"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/orderer/common/localconfig"
"github.com/hyperledger/fabric/orderer/common/types"
"github.com/pkg/errors"
)
const (
URLBaseV1 = "/participation/v1/"
URLBaseV1Channels = URLBaseV1 + "channels"
FormDataConfigBlockKey = "config-block"
RemoveStorageQueryKey = "removeStorage"
channelIDKey = "channelID"
urlWithChannelIDKey = URLBaseV1Channels + "/{" + channelIDKey + "}"
)
//go:generate counterfeiter -o mocks/channel_management.go -fake-name ChannelManagement . ChannelManagement
type ChannelManagement interface {
// ChannelList returns a slice of ChannelInfoShort containing all application channels (excluding the system
// channel), and ChannelInfoShort of the system channel (nil if does not exist).
// The URL fields are empty, and are to be completed by the caller.
ChannelList() types.ChannelList
// ChannelInfo provides extended status information about a channel.
// The URL field is empty, and is to be completed by the caller.
ChannelInfo(channelID string) (types.ChannelInfo, error)
// JoinChannel instructs the orderer to create a channel and join it with the provided config block.
JoinChannel(channelID string, configBlock *cb.Block, isAppChannel bool) (types.ChannelInfo, error)
// RemoveChannel instructs the orderer to remove a channel.
// Depending on the removeStorage parameter, the storage resources are either removed or archived.
RemoveChannel(channelID string, removeStorage bool) error
}
// HTTPHandler handles all the HTTP requests to the channel participation API.
type HTTPHandler struct {
logger *flogging.FabricLogger
config localconfig.ChannelParticipation
registrar ChannelManagement
router *mux.Router
// TODO skeleton
}
func | (config localconfig.ChannelParticipation, registrar ChannelManagement) *HTTPHandler {
handler := &HTTPHandler{
logger: flogging.MustGetLogger("orderer.commmon.channelparticipation"),
config: config,
registrar: registrar,
router: mux.NewRouter(),
}
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveListOne).Methods(http.MethodGet)
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveJoin).Methods(http.MethodPost).HeadersRegexp(
"Content-Type", "multipart/form-data*")
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveBadContentType).Methods(http.MethodPost)
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveRemove).Methods(http.MethodDelete)
handler.router.HandleFunc(urlWithChannelIDKey, handler.serveNotAllowed)
handler.router.HandleFunc(URLBaseV1Channels, handler.serveListAll).Methods(http.MethodGet)
handler.router.HandleFunc(URLBaseV1Channels, handler.serveNotAllowed)
handler.router.HandleFunc(URLBaseV1, handler.redirectBaseV1).Methods(http.MethodGet)
return handler
}
func (h *HTTPHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
if !h.config.Enabled {
err := errors.New("channel participation API is disabled")
h.sendResponseJsonError(resp, http.StatusServiceUnavailable, err)
return
}
h.router.ServeHTTP(resp, req)
}
// List all channels
func (h *HTTPHandler) serveListAll(resp http.ResponseWriter, req *http.Request) {
_, err := negotiateContentType(req) // Only application/json responses for now
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotAcceptable, err)
return
}
channelList := h.registrar.ChannelList()
if channelList.SystemChannel != nil && channelList.SystemChannel.Name != "" {
channelList.SystemChannel.URL = path.Join(URLBaseV1Channels, channelList.SystemChannel.Name)
}
for i, info := range channelList.Channels {
channelList.Channels[i].URL = path.Join(URLBaseV1Channels, info.Name)
}
resp.Header().Set("Cache-Control", "no-store")
h.sendResponseOK(resp, channelList)
}
// List a single channel
func (h *HTTPHandler) serveListOne(resp http.ResponseWriter, req *http.Request) {
_, err := negotiateContentType(req) // Only application/json responses for now
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotAcceptable, err)
return
}
channelID, err := h.extractChannelID(req, resp)
if err != nil {
return
}
infoFull, err := h.registrar.ChannelInfo(channelID)
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotFound, err)
return
}
resp.Header().Set("Cache-Control", "no-store")
h.sendResponseOK(resp, infoFull)
}
func (h *HTTPHandler) redirectBaseV1(resp http.ResponseWriter, req *http.Request) {
http.Redirect(resp, req, URLBaseV1Channels, http.StatusFound)
}
// Join a channel.
// Expect multipart/form-data.
func (h *HTTPHandler) serveJoin(resp http.ResponseWriter, req *http.Request) {
_, err := negotiateContentType(req) // Only application/json responses for now
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotAcceptable, err)
return
}
channelID, err := h.extractChannelID(req, resp)
if err != nil {
return
}
_, params, err := mime.ParseMediaType(req.Header.Get("Content-Type"))
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot parse Mime media type"))
return
}
block := h.multipartFormDataBodyToBlock(params, req, resp)
if block == nil {
return
}
isAppChannel, err := ValidateJoinBlock(channelID, block)
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "invalid join block"))
return
}
info, err := h.registrar.JoinChannel(channelID, block, isAppChannel)
if err == nil {
info.URL = path.Join(URLBaseV1Channels, info.Name)
h.logger.Debugf("Successfully joined channel: %s", info.URL)
h.sendResponseCreated(resp, info.URL, info)
return
}
h.sendJoinError(err, resp)
}
// Expect a multipart/form-data with a single part, of type file, with key FormDataConfigBlockKey.
func (h *HTTPHandler) multipartFormDataBodyToBlock(params map[string]string, req *http.Request, resp http.ResponseWriter) *cb.Block {
boundary := params["boundary"]
reader := multipart.NewReader(req.Body, boundary)
form, err := reader.ReadForm(100 * 1024 * 1024)
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot read form from request body"))
return nil
}
if _, exist := form.File[FormDataConfigBlockKey]; !exist {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Errorf("form does not contains part key: %s", FormDataConfigBlockKey))
return nil
}
if len(form.File) != 1 || len(form.Value) != 0 {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.New("form contains too many parts"))
return nil
}
fileHeader := form.File[FormDataConfigBlockKey][0]
file, err := fileHeader.Open()
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrapf(err, "cannot open file part %s from request body", FormDataConfigBlockKey))
return nil
}
blockBytes, err := ioutil.ReadAll(file)
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrapf(err, "cannot read file part %s from request body", FormDataConfigBlockKey))
return nil
}
block := &cb.Block{}
err = proto.Unmarshal(blockBytes, block)
if err != nil {
h.logger.Debugf("Failed to unmarshal blockBytes: %s", err)
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrapf(err, "cannot unmarshal file part %s into a block", FormDataConfigBlockKey))
return nil
}
return block
}
func (h *HTTPHandler) extractChannelID(req *http.Request, resp http.ResponseWriter) (string, error) {
channelID, ok := mux.Vars(req)[channelIDKey]
if !ok {
err := errors.New("missing channel ID")
h.sendResponseJsonError(resp, http.StatusInternalServerError, err)
return "", err
}
if err := configtx.ValidateChannelID(channelID); err != nil {
err = errors.Wrap(err, "invalid channel ID")
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
return "", err
}
return channelID, nil
}
func (h *HTTPHandler) sendJoinError(err error, resp http.ResponseWriter) {
h.logger.Debugf("Failed to JoinChannel: %s", err)
switch err {
case types.ErrSystemChannelExists:
// The client is trying to join an app-channel, but the system channel exists: only GET is allowed on app channels.
h.sendResponseNotAllowed(resp, errors.Wrap(err, "cannot join"), http.MethodGet)
case types.ErrChannelAlreadyExists:
// The client is trying to join an app-channel that exists, but the system channel does not;
// The client is trying to join the system-channel, and it exists. GET & DELETE are allowed on the channel.
h.sendResponseNotAllowed(resp, errors.Wrap(err, "cannot join"), http.MethodGet, http.MethodDelete)
case types.ErrAppChannelsAlreadyExists:
// The client is trying to join the system-channel that does not exist, but app channels exist.
h.sendResponseJsonError(resp, http.StatusForbidden, errors.Wrap(err, "cannot join"))
default:
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot join"))
}
}
// Remove a channel
// Expecting an optional query: "removeStorage=true" or "removeStorage=false".
func (h *HTTPHandler) serveRemove(resp http.ResponseWriter, req *http.Request) {
_, err := negotiateContentType(req) // Only application/json responses for now
if err != nil {
h.sendResponseJsonError(resp, http.StatusNotAcceptable, err)
return
}
channelID, err := h.extractChannelID(req, resp)
if err != nil {
return
}
removeStorage, err := h.extractRemoveStorageQuery(req, resp)
if err != nil {
return
}
err = h.registrar.RemoveChannel(channelID, removeStorage)
if err == nil {
h.logger.Debugf("Successfully removed channel: %s", channelID)
resp.WriteHeader(http.StatusNoContent)
return
}
h.logger.Debugf("Failed to remove channel: %s, err: %s", channelID, err)
switch err {
case types.ErrSystemChannelExists:
h.sendResponseNotAllowed(resp, errors.Wrap(err, "cannot remove"), http.MethodGet)
case types.ErrChannelNotExist:
h.sendResponseJsonError(resp, http.StatusNotFound, errors.Wrap(err, "cannot remove"))
default:
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot remove"))
}
}
func (h *HTTPHandler) extractRemoveStorageQuery(req *http.Request, resp http.ResponseWriter) (bool, error) {
removeStorage := h.config.RemoveStorage
queryVal := req.URL.Query()
if len(queryVal) > 1 {
err := errors.New("cannot remove: too many query keys")
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
return false, err
}
if values, ok := queryVal[RemoveStorageQueryKey]; ok {
var err error
if len(values) != 1 {
err = errors.New("cannot remove: too many query parameters")
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
return false, err
}
removeStorage, err = strconv.ParseBool(values[0])
if err != nil {
h.sendResponseJsonError(resp, http.StatusBadRequest, errors.Wrap(err, "cannot remove: invalid query parameter"))
return false, err
}
} else if len(queryVal) > 0 {
err := errors.New("cannot remove: invalid query key")
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
return false, err
}
return removeStorage, nil
}
func (h *HTTPHandler) serveBadContentType(resp http.ResponseWriter, req *http.Request) {
err := errors.Errorf("unsupported Content-Type: %s", req.Header.Values("Content-Type"))
h.sendResponseJsonError(resp, http.StatusBadRequest, err)
}
func (h *HTTPHandler) serveNotAllowed(resp http.ResponseWriter, req *http.Request) {
err := errors.Errorf("invalid request method: %s", req.Method)
if _, ok := mux.Vars(req)[channelIDKey]; ok {
h.sendResponseNotAllowed(resp, err, http.MethodGet, http.MethodPost, http.MethodDelete)
return
}
h.sendResponseNotAllowed(resp, err, http.MethodGet)
}
func negotiateContentType(req *http.Request) (string, error) {
acceptReq := req.Header.Get("Accept")
if len(acceptReq) == 0 {
return "application/json", nil
}
options := strings.Split(acceptReq, ",")
for _, opt := range options {
if strings.Contains(opt, "application/json") ||
strings.Contains(opt, "application/*") ||
strings.Contains(opt, "*/*") {
return "application/json", nil
}
}
return "", errors.New("response Content-Type is application/json only")
}
func (h *HTTPHandler) sendResponseJsonError(resp http.ResponseWriter, code int, err error) {
encoder := json.NewEncoder(resp)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(code)
if err := encoder.Encode(&types.ErrorResponse{Error: err.Error()}); err != nil {
h.logger.Errorf("failed to encode error, err: %s", err)
}
}
func (h *HTTPHandler) sendResponseOK(resp http.ResponseWriter, content interface{}) {
encoder := json.NewEncoder(resp)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(http.StatusOK)
if err := encoder.Encode(content); err != nil {
h.logger.Errorf("failed to encode content, err: %s", err)
}
}
func (h *HTTPHandler) sendResponseCreated(resp http.ResponseWriter, location string, content interface{}) {
encoder := json.NewEncoder(resp)
resp.Header().Set("Location", location)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(http.StatusCreated)
if err := encoder.Encode(content); err != nil {
h.logger.Errorf("failed to encode content, err: %s", err)
}
}
func (h *HTTPHandler) sendResponseNotAllowed(resp http.ResponseWriter, err error, allow ...string) {
encoder := json.NewEncoder(resp)
allowVal := strings.Join(allow, ", ")
resp.Header().Set("Allow", allowVal)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(http.StatusMethodNotAllowed)
if err := encoder.Encode(&types.ErrorResponse{Error: err.Error()}); err != nil {
h.logger.Errorf("failed to encode error, err: %s", err)
}
}
| NewHTTPHandler |
mod.rs | use crate::utils;
use std::collections::HashMap;
use std::fmt;
use std::iter::FromIterator;
use std::time::SystemTime;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
struct | {
left: usize,
right: usize,
}
impl fmt::Display for TwoIndexes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}+{}", self.left, self.right)
}
}
const PREAMBLE: usize = 25;
fn part1(input: &Vec<u64>) {
let now = SystemTime::now();
let mut result = 0;
for pos in PREAMBLE..input.len() {
let start = pos - PREAMBLE;
let stop = pos;
let previous_values = Vec::from_iter(input[start..stop].iter().cloned());
if !is_sum_in_list(input[pos], &previous_values) {
result = input[pos];
break;
}
}
println!("Part 1: {}", result);
println!("Part 1 took: {}ms", now.elapsed().unwrap().as_millis());
}
fn is_sum_in_list(input: u64, list: &Vec<u64>) -> bool {
let mut map: HashMap<usize, bool> = HashMap::with_capacity(list.len());
for value in list {
map.insert(*value as usize, true);
}
for value in list {
if *value > input {
continue;
}
let rest = input - *value;
// do not allow x + x to validate y
if rest == *value {
continue;
}
if map.contains_key(&(rest as usize)) {
return true;
}
}
return false;
}
fn part2(input: &Vec<u64>) {
let now = SystemTime::now();
let mut target = 0;
let mut target_pos: usize = 0;
let mut result = 0;
for pos in PREAMBLE..input.len() {
let start = pos - PREAMBLE;
let stop = pos;
let previous_values = Vec::from_iter(input[start..stop].iter().cloned());
if !is_sum_in_list(input[pos], &previous_values) {
target = input[pos];
target_pos = pos;
break;
}
}
for sequence_size in 2..target_pos {
if result > 0 {
break;
}
for sequence_start in 0..target_pos - sequence_size + 1 {
let mut sum = 0;
let mut min = input[sequence_start];
let mut max = input[sequence_start];
for i in sequence_start..sequence_start + sequence_size {
if input[i] > max {
max = input[i];
}
if input[i] < min {
min = input[i];
}
sum += input[i];
}
if sum == target {
result = min + max;
break;
}
}
}
println!("Part 2: {}", result);
println!("Part 2 took: {}ms", now.elapsed().unwrap().as_millis());
}
pub fn run() {
println!("Running day9");
let now = SystemTime::now();
let input: String = utils::input::read("day9");
let input_lines: Vec<&str> = input.split("\n").collect();
let mut numbers: Vec<u64> = Vec::with_capacity(input_lines.len());
for line in input_lines {
numbers.push(line.parse().unwrap());
}
println!("Parsing took: {}ms", now.elapsed().unwrap().as_millis());
part1(&numbers);
part2(&numbers);
}
| TwoIndexes |
main.go | package main
import "github.com/jeinfeldt/raytracer/cmd"
func main() | {
cmd.Execute()
} |
|
getRouteFilterRule.go | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package v20190201
import (
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// Route Filter Rule Resource
func LookupRouteFilterRule(ctx *pulumi.Context, args *LookupRouteFilterRuleArgs, opts ...pulumi.InvokeOption) (*LookupRouteFilterRuleResult, error) |
type LookupRouteFilterRuleArgs struct {
// The name of the resource group.
ResourceGroupName string `pulumi:"resourceGroupName"`
// The name of the route filter.
RouteFilterName string `pulumi:"routeFilterName"`
// The name of the rule.
RuleName string `pulumi:"ruleName"`
}
// Route Filter Rule Resource
type LookupRouteFilterRuleResult struct {
// The access type of the rule.
Access string `pulumi:"access"`
// The collection for bgp community values to filter on. e.g. ['12076:5010','12076:5020']
Communities []string `pulumi:"communities"`
// A unique read-only string that changes whenever the resource is updated.
Etag string `pulumi:"etag"`
// Resource ID.
Id *string `pulumi:"id"`
// Resource location.
Location *string `pulumi:"location"`
// The name of the resource that is unique within a resource group. This name can be used to access the resource.
Name *string `pulumi:"name"`
// The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', 'Succeeded' and 'Failed'.
ProvisioningState string `pulumi:"provisioningState"`
// The rule type of the rule. Valid value is: 'Community'
RouteFilterRuleType string `pulumi:"routeFilterRuleType"`
}
| {
var rv LookupRouteFilterRuleResult
err := ctx.Invoke("azure-native:network/v20190201:getRouteFilterRule", args, &rv, opts...)
if err != nil {
return nil, err
}
return &rv, nil
} |
saver.go | package httptransport
import (
"bytes"
"errors"
"io"
"io/ioutil"
"net/http"
"net/http/httptrace"
"time"
"github.com/ooni/probe-cli/v3/internal/engine/netx/trace"
)
// SaverPerformanceHTTPTransport is a RoundTripper that saves
// performance events occurring during the round trip
type SaverPerformanceHTTPTransport struct {
RoundTripper
Saver *trace.Saver
}
// RoundTrip implements RoundTripper.RoundTrip
func (txp SaverPerformanceHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
tracep := httptrace.ContextClientTrace(req.Context())
if tracep == nil {
tracep = &httptrace.ClientTrace{
WroteHeaders: func() {
txp.Saver.Write(trace.Event{Name: "http_wrote_headers", Time: time.Now()})
},
WroteRequest: func(httptrace.WroteRequestInfo) {
txp.Saver.Write(trace.Event{Name: "http_wrote_request", Time: time.Now()})
},
GotFirstResponseByte: func() {
txp.Saver.Write(trace.Event{
Name: "http_first_response_byte", Time: time.Now()})
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), tracep))
}
return txp.RoundTripper.RoundTrip(req)
}
// SaverMetadataHTTPTransport is a RoundTripper that saves
// events related to HTTP request and response metadata
type SaverMetadataHTTPTransport struct {
RoundTripper
Saver *trace.Saver
Transport string
}
// RoundTrip implements RoundTripper.RoundTrip
func (txp SaverMetadataHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
txp.Saver.Write(trace.Event{
HTTPHeaders: req.Header,
HTTPMethod: req.Method,
HTTPURL: req.URL.String(),
Transport: txp.Transport,
Name: "http_request_metadata",
Time: time.Now(),
})
resp, err := txp.RoundTripper.RoundTrip(req)
if err != nil {
return nil, err
}
txp.Saver.Write(trace.Event{
HTTPHeaders: resp.Header,
HTTPStatusCode: resp.StatusCode,
Name: "http_response_metadata",
Time: time.Now(),
})
return resp, err
}
// SaverTransactionHTTPTransport is a RoundTripper that saves
// events related to the HTTP transaction
type SaverTransactionHTTPTransport struct {
RoundTripper
Saver *trace.Saver
}
// RoundTrip implements RoundTripper.RoundTrip
func (txp SaverTransactionHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
txp.Saver.Write(trace.Event{
Name: "http_transaction_start",
Time: time.Now(),
})
resp, err := txp.RoundTripper.RoundTrip(req)
txp.Saver.Write(trace.Event{
Err: err,
Name: "http_transaction_done",
Time: time.Now(),
})
return resp, err
}
// SaverBodyHTTPTransport is a RoundTripper that saves
// body events occurring during the round trip
type SaverBodyHTTPTransport struct {
RoundTripper
Saver *trace.Saver
SnapshotSize int
}
// RoundTrip implements RoundTripper.RoundTrip
func (txp SaverBodyHTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
const defaultSnapSize = 1 << 17
snapsize := defaultSnapSize
if txp.SnapshotSize != 0 {
snapsize = txp.SnapshotSize
}
if req.Body != nil {
data, err := saverSnapRead(req.Body, snapsize)
if err != nil {
return nil, err
}
req.Body = saverCompose(data, req.Body)
txp.Saver.Write(trace.Event{
DataIsTruncated: len(data) >= snapsize,
Data: data,
Name: "http_request_body_snapshot",
Time: time.Now(),
})
}
resp, err := txp.RoundTripper.RoundTrip(req)
if err != nil {
return nil, err
}
data, err := saverSnapRead(resp.Body, snapsize)
err = ignoreExpectedEOF(err, resp)
if err != nil {
resp.Body.Close()
return nil, err
}
resp.Body = saverCompose(data, resp.Body)
txp.Saver.Write(trace.Event{
DataIsTruncated: len(data) >= snapsize,
Data: data,
Name: "http_response_body_snapshot",
Time: time.Now(),
})
return resp, nil
}
// ignoreExpectedEOF converts an error signalling the end of the body
// into a success. We know that we are in such condition when the
// resp.Close hint flag is set to true. (Thanks, stdlib!)
//
// See https://github.com/ooni/probe-engine/issues/1191 for an analysis
// of how this error was impacting measurements and data quality.
func ignoreExpectedEOF(err error, resp *http.Response) error {
if err == nil {
return nil
}
if errors.Is(err, io.EOF) && resp.Close {
return nil
}
return err
}
func saverSnapRead(r io.ReadCloser, snapsize int) ([]byte, error) {
return ioutil.ReadAll(io.LimitReader(r, int64(snapsize)))
}
func saverCompose(data []byte, r io.ReadCloser) io.ReadCloser |
type saverReadCloser struct {
io.Closer
io.Reader
}
var _ RoundTripper = SaverPerformanceHTTPTransport{}
var _ RoundTripper = SaverMetadataHTTPTransport{}
var _ RoundTripper = SaverBodyHTTPTransport{}
var _ RoundTripper = SaverTransactionHTTPTransport{}
| {
return saverReadCloser{Closer: r, Reader: io.MultiReader(bytes.NewReader(data), r)}
} |
plugin.py | ################################################################################
#
# Copyright (c) 2019, the Perspective Authors.
#
# This file is part of the Perspective library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
from enum import Enum
class Plugin(Enum):
'''The plugins (grids/charts) available in Perspective. Pass these into
the `plugin` arg in `PerspectiveWidget` or `PerspectiveViewer`.
Examples:
>>> widget = PerspectiveWidget(data, plugin=Plugin.TREEMAP)
'''
HYPERGRID = 'hypergrid' # hypergrid
GRID = 'hypergrid' # hypergrid
YBAR = 'y_bar' # highcharts
XBAR = 'x_bar' # highcharts
YLINE = 'y_line' # highcharts
YAREA = 'y_area' # highcharts
YSCATTER = 'y_scatter' # highcharts
XYLINE = 'xy_line' # highcharts
XYSCATTER = 'xy_scatter' # highcharts
TREEMAP = 'treemap' # highcharts
SUNBURST = 'sunburst' # highcharts
HEATMAP = 'heatmap' # highcharts
YBAR_D3 = 'd3_y_bar' # d3fc
XBAR_D3 = 'd3_x_bar' # d3fc
YLINE_D3 = 'd3_y_line' # d3fc
YAREA_D3 = 'd3_y_area' # d3fc
YSCATTER_D3 = 'd3_y_scatter' # d3fc
XYSCATTER_D3 = 'd3_xy_scatter' # d3fc
TREEMAP_D3 = 'd3_treemap' # d3fc
SUNBURST_D3 = 'd3_sunburst' # d3fc
HEATMAP_D3 = 'd3_heatmap' # d3fc
CANDLESTICK = 'd3_candlestick' # d3fc
CANDLESTICK_D3 = 'd3_candlestick' # d3fc
OHLC = 'd3_ohlc' # d3fc
OHLC_D3 = 'd3_ohlc' # d3fc
@staticmethod
def | ():
return list(c.value for c in Plugin)
| options |
auto_scan_test.py | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import unittest
import abc
import os
import enum
import logging
import paddle
import paddle.fluid as fluid
from paddle.fluid.initializer import NumpyArrayInitializer
import paddle.fluid.core as core
from paddle import compat as cpt
import paddle.inference as paddle_infer
from typing import Optional, List, Callable, Dict, Any, Set
from program_config import TensorConfig, OpConfig, ProgramConfig, create_fake_model, create_quant_model
logging.basicConfig(level=logging.INFO, format="%(message)s")
class SkipReasons(enum.Enum):
# Paddle not support, but trt support, we need to add the feature.
TRT_NOT_IMPLEMENTED = 0
# TRT not support.
TRT_NOT_SUPPORT = 1
class AutoScanTest(unittest.TestCase):
def __init__(self, methodName='runTest'):
np.random.seed(1024)
paddle.enable_static()
super(AutoScanTest, self).__init__(methodName)
self.skip_cases = []
@abc.abstractmethod
def sample_program_configs(self) -> List[ProgramConfig]:
'''
Generate all config with the combination of different Input tensor shape and
different Attr values.
'''
raise NotImplementedError
@abc.abstractmethod
def sample_predictor_configs(self) -> List[paddle_infer.Config]:
|
@abc.abstractmethod
def add_skip_case(
self,
teller: [Callable[[ProgramConfig, paddle_infer.Config], bool]],
reason: SkipReasons,
note: str):
self.skip_cases.append((teller, reason, note))
@abc.abstractmethod
def is_program_valid(self, program_config: ProgramConfig) -> bool:
raise NotImplementedError
def run_test_config(self, model, params, prog_config, pred_config,
feed_data) -> Dict[str, np.ndarray]:
'''
Test a single case.
'''
pred_config.set_model_buffer(model, len(model), params, len(params))
predictor = paddle_infer.create_predictor(pred_config)
for name, _ in prog_config.inputs.items():
input_tensor = predictor.get_input_handle(name)
input_tensor.copy_from_cpu(feed_data[name]['data'])
if feed_data[name]['lod'] is not None:
input_tensor.set_lod(feed_data[name]['lod'])
predictor.run()
result = {}
for out_name, o_name in zip(prog_config.outputs,
predictor.get_output_names()):
result[out_name] = predictor.get_output_handle(o_name).copy_to_cpu()
return result
def assert_tensors_near(self,
threshold: float,
tensors: List[Dict[str, np.array]]):
assert len(tensors) > 1
first = tensors[0]
for group in tensors[1:]:
for key, arr in group.items():
self.assertTrue(
np.allclose(
first[key], arr, atol=threshold),
"Output has diff between GPU and TensorRT. ")
@abc.abstractmethod
def run_test(self, quant=False):
raise NotImplementedError
| raise NotImplementedError |
items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class | (scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
| UniversalItem |
Main.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
class Main extends egret.DisplayObjectContainer {
/**
* 加载进度界面
* Process interface loading
*/
private loadingView:LoadingUI;
private click = 0;
//定义控件
private title:egret.TextField;
private content:egret.TextField;
private content1:egret.TextField;
private content2:egret.TextField;
private content3:egret.TextField;
private content4:egret.TextField;
private content5:egret.TextField;
private page1Content1 : egret.TextField;
private headSculpture : egret.Bitmap;
private headSculpture1 : egret.Bitmap;
private page1;
private page2;
private stageW : number;
private stageH : number;
private movedistance;
//记录当前舞台的Y值,为stageH的整数倍
private currentPageY;
private starttouchpointY;
private headSculptureTween;
private headSculpture1Tween;
public constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
private onAddToStage(event:egret.Event) {
//设置加载进度界面
//Config to load process interface
this.loadingView = new LoadingUI();
this.stage.addChild(this.loadingView);
//初始化Resource资源加载库
//initiate Resource loading library
RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
RES.loadConfig("resource/default.res.json", "resource/");
}
/**
* 配置文件加载完成,开始预加载preload资源组。
* configuration file loading is completed, start to pre-load the preload resource group
*/
private onConfigComplete(event:RES.ResourceEvent):void {
RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
RES.loadGroup("preload");
}
/**
* preload资源组加载完成
* Preload resource group is loaded
*/
private onResourceLoadComplete(event:RES.ResourceEvent):void {
if (event.groupName == "preload") {
this.stage.removeChild(this.loadingView);
RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
this.createGameScene();
}
}
/**
* 资源组加载出错
* The resource group loading failed
*/
private onItemLoadError(event:RES.ResourceEvent):void {
console.warn("Url:" + event.resItem.url + " has failed to load");
}
/**
* 资源组加载出错
* The resource group loading failed
*/
private onResourceLoadError(event:RES.ResourceEvent):void {
//TODO
console.warn("Group:" + event.groupName + " has failed to load");
//忽略加载失败的项目
//Ignore the loading failed projects
this.onResourceLoadComplete(event);
}
/**
* preload资源组加载进度
* Loading process of preload resource group
*/
private onResourceProgress(event:RES.ResourceEvent):void {
if (event.groupName == "preload") {
this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
}
}
/**
* 创建游戏场景
* Create a game scene
*/
private createGameScene():void {
/*
滑动的三个步骤:点,滑,松
设置三个事件,分别监听TouchEvent.TOUCH_BEGIN,TouchEvent.TOUCH_MOVE,TouchEvent.TOUCH_END
最后根据移动的距离判断是否换页
*/
this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.startScroll, this);
this.addEventListener(egret.TouchEvent.TOUCH_END, this.stopScroll, this);
this.stageW = this.stage.stageWidth;
this.stageH= this.stage.stageHeight;
//两页的滑块
this.scrollRect= new egret.Rectangle(0 ,0 , this.stageW, this.stageH * 2);
this.cacheAsBitmap = true;
this.touchEnabled = true;
this.starttouchpointY = 0;
this.currentPageY = 0;
this.movedistance = 0;
//创建第一个界面,位置默认为左上角,即X=0,Y=0
this.page1 = new egret.DisplayObjectContainer();
this.addChild(this.page1);
var bg1:egret.Bitmap = this.createBitmapByName("bg_jpg");
bg1.width = this.stageW;
bg1.height = this.stageH;
this.page1.addChild(bg1);
this.headSculpture = this.createBitmapByName("egret_icon_png");
this.headSculpture.x = 40;
this.headSculpture.y = 40;
this.page1.addChild(this.headSculpture);
this.headSculpture1 = this.createBitmapByName("egret_icon_png");
this.headSculpture1.x = 40;
this. headSculpture1.y = 720;
this.page1.addChild(this.headSculpture1);
this.page1Content1 = new egret.TextField();
this.page1Content1.text = "个人简介";
this.page1Content1.textColor = 0xFFFF00;
this.page1Content1.y = 200;
this.page1Content1.x = 200;
this.page1Content1.size = 60;
this.page1.addChild(this.page1Content1);
//第二个界面,X默认为0,Y指定为StageH,即在第一个界面正下方
this.page2 = new egret.DisplayObjectContainer();
this.page2.width = this.stageW;
this.page2.height = this.stageH;
this.page2.y = this.stageH
this.addChild(this.page2);
var bg:egret.Bitmap = this.createBitmapByName("bg_jpg");
bg.width = this.stageW;
bg.height = this.stageH;
this.page2.addChild(bg);
this.title= new egret.TextField();
this.title.text = "个人简介 .";
this.title.size = 55;
this.title.y = 60;
this.title.width = this.stage.width;
this.title.textColor = 0xFFFF00;
this.title.textAlign = egret.HorizontalAlign.CENTER
this.title.touchEnabled = true;
//注册事件监听器,点击显示详细内容
this.title.addEventListener( egret.TouchEvent.TOUCH_TAP, this.touchTitle, this );
this.page2.addChild(this.title);
this.content= new egret.TextField();
this.content.text = "姓名:卢健";
this.content.textColor = 0xFFFF00;
this.content.y = 200;
this.content.x = 30;
this.content.size = 30;
this.page2.addChild(this.content);
| this.content1.text = "学号:14081226";
this.content1.textColor = 0xFFFF00;
this.content1.y = 300;
this.content1.x = 30;
this.content1.size = 30;
this.page2.addChild(this.content1);
this.content2= new egret.TextField();
this.content2.text = "专业:数字媒体技术";
this.content2.textColor = 0xFFFF00;
this.content2.y = 400;
this.content2.x = 30;
this.content2.size = 30;
this.page2.addChild(this.content2);
this.content3= new egret.TextField();
this.content3.text = "游戏爱好:LOL";
this.content3.textColor = 0xFFFF00;
this.content3.y = 500;
this.content3.x = 30;
this.content3.size = 30;
this.page2.addChild(this.content3);
this.content4= new egret.TextField();
this.content4.text = "喜欢旅游,美食";
this.content4.textColor = 0xFFFF00;
this.content4.y = 600;
this.content4.x = 30;
this.content4.size = 30;
this.page2.addChild(this.content4);
this.content5= new egret.TextField();
this.content5.text = "未来方向:还在考虑......";
this.content5.textColor = 0xFFFF00;
this.content5.y = 700;
this.content5.x = 30;
this.content5.size = 30;
this.page2.addChild(this.content5);
/*to方法包含三个参数。
首先是动画目标属性组,这个参数可以对目标对象本身的各项属性进行设定,就是动画结束时的状态,可以设定一个或多个属性。
第二个参数是动画时间,以毫秒计。
第三个参数是补间方程,即对动画区间内每个时间点的属性值设定分布。
*/
this.headSculptureTween = egret.Tween.get(this.headSculpture,{loop:true});
this.headSculpture1Tween = egret.Tween.get(this.headSculpture1,{loop:true});
//每个Tween对象按顺序执行逻辑
this.headSculptureTween.to( { y:this.headSculpture1.y }, 1500, egret.Ease.sineIn);
this.headSculpture1Tween.to( { y:this.headSculpture.y }, 1500, egret.Ease.sineIn);
this.headSculptureTween.to({"rotation" : 10}, 500, egret.Ease.sineIn);
this.headSculptureTween.to({"rotation" : 0}, 500, egret.Ease.sineIn);
this.headSculpture1Tween.to({"rotation" : 10}, 500, egret.Ease.sineIn);
this.headSculpture1Tween.to({"rotation" : 0}, 500, egret.Ease.sineIn);
//改变字体内容及颜色
this.change();
}
/**
* 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
* Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
*/
private createBitmapByName(name:string):egret.Bitmap {
var result = new egret.Bitmap();
var texture:egret.Texture = RES.getRes(name);
result.texture = texture;
return result;
}
private touchTitle( evt:egret.TouchEvent ):void{
if(this.click == 0){
this.title.text = "↓↓↓↓↓↓(?)"
this.title.textColor = 0x00FF00
this.content.textColor = 0xFFFF00;
this.content1.textColor = 0xFFFF00;
this.content2.textColor = 0xFFFF00;
this.content3.textColor = 0xFFFF00;
this.content4.textColor = 0xFFFF00;
this.content5.textColor = 0xFFFF00;
this.click = 1;
}else{
this.title.text = "";
this.content.text = "";
this.content1.text = "";
this.content2.text = "";
this.content3.text = "";
this.content4.text = "";
this.content5.text = "";
this.click = 0;
}
}
private change() : void{
this.page1Content1.textColor = 0x000000;
this.page1Content1.text = "个人简介"
egret.setTimeout(function(){this.page1Content1.textColor = 0xFFFFF0;this.page1Content1.text = "请翻至下页";}, this, 1500);
egret.setTimeout(function(){this.change()}, this, 3000);
}
//第一次触摸屏幕时
private startScroll(e: egret.TouchEvent): void {
//正常情况下scrollRect.y是stageH的整数倍;如果图片位置错误,返回上一个正确位置;
if((this.scrollRect.y % this.stageH)!= 0) {
this.scrollRect.y = this.currentPageY;
}
//记录下刚触摸屏幕时的y值
this.starttouchpointY = e.stageY;
//此时scrollRect已停留在一个page上
this.currentPageY = this.scrollRect.y;
//TouchEvent.TOUCH_MOVE:连续触摸时调用
this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onScroll, this);
}
//连续触摸时调用,计算出每时每刻移动的距离,并控制屏幕滑动
private onScroll(e: egret.TouchEvent): void {
var rect : egret.Rectangle = this.scrollRect;
this.movedistance = this.starttouchpointY - e.stageY;
//实时改变scrollRect的位置
if((this.currentPageY == 0 && this.movedistance < 0) || (this.currentPageY == this.stageH && this.movedistance > 0)){
}else{
rect.y = (this.currentPageY + this.movedistance);
this.scrollRect = rect;
}
}
private stopScroll(e: egret.TouchEvent): void {
var rect: egret.Rectangle = this.scrollRect;
//向下滑动超过屏幕的三分之一,将scrollRect向下平移一个屏幕
if((this.movedistance>=(this.stage.stageHeight/3)) && this.currentPageY!= this.stageH) {
rect.y = this.currentPageY + this.stageH;
this.scrollRect = rect;
//向上滑动超过屏幕的三分之一,将scrollRect向上平移一个屏幕
}else if((this.movedistance<=(-(this.stage.stageHeight/3))) && this.currentPageY!=0) {
rect.y = this.currentPageY - this.stageH;
this.scrollRect = rect;
//保持当前界面,即不移动scrollRect
}else {
rect.y = this.currentPageY;
this.scrollRect = rect;
}
this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE,this.onScroll,this);
}
} | this.content1= new egret.TextField(); |
category_repository.go | package link
import (
"golang.org/x/net/context"
"github.com/almighty/almighty-core/app"
"github.com/almighty/almighty-core/errors"
"github.com/almighty/almighty-core/log"
"github.com/jinzhu/gorm"
satoriuuid "github.com/satori/go.uuid"
)
// WorkItemLinkCategoryRepository encapsulates storage & retrieval of work item link categories
type WorkItemLinkCategoryRepository interface {
Create(ctx context.Context, name *string, description *string) (*app.WorkItemLinkCategorySingle, error)
Load(ctx context.Context, ID string) (*app.WorkItemLinkCategorySingle, error)
List(ctx context.Context) (*app.WorkItemLinkCategoryList, error)
Delete(ctx context.Context, ID string) error
Save(ctx context.Context, linkCat app.WorkItemLinkCategorySingle) (*app.WorkItemLinkCategorySingle, error)
}
// NewWorkItemLinkCategoryRepository creates a work item link category repository based on gorm
func | (db *gorm.DB) *GormWorkItemLinkCategoryRepository {
return &GormWorkItemLinkCategoryRepository{db}
}
// GormWorkItemLinkCategoryRepository implements WorkItemLinkCategoryRepository using gorm
type GormWorkItemLinkCategoryRepository struct {
db *gorm.DB
}
// Create creates a new work item link category in the repository.
// Returns BadParameterError, ConversionError or InternalError
func (r *GormWorkItemLinkCategoryRepository) Create(ctx context.Context, name *string, description *string) (*app.WorkItemLinkCategorySingle, error) {
if name == nil || *name == "" {
return nil, errors.NewBadParameterError("name", name)
}
created := WorkItemLinkCategory{
// Omit "lifecycle" and "ID" fields as they will be filled by the DB
Name: *name,
Description: description,
}
db := r.db.Create(&created)
if db.Error != nil {
return nil, errors.NewInternalError(db.Error.Error())
}
// Convert the created link category entry into a JSONAPI response
result := ConvertLinkCategoryFromModel(created)
return &result, nil
}
// Load returns the work item link category for the given ID.
// Returns NotFoundError, ConversionError or InternalError
func (r *GormWorkItemLinkCategoryRepository) Load(ctx context.Context, ID string) (*app.WorkItemLinkCategorySingle, error) {
id, err := satoriuuid.FromString(ID)
if err != nil {
// treat as not found: clients don't know it must be a UUID
return nil, errors.NewNotFoundError("work item link category", ID)
}
log.Info(ctx, map[string]interface{}{
"pkg": "link",
"wilcID": ID,
}, "Loading work item link category")
res := WorkItemLinkCategory{}
db := r.db.Model(&res).Where("id=?", ID).First(&res)
if db.RecordNotFound() {
log.Error(ctx, map[string]interface{}{
"wilcID": ID,
}, "work item link category not found by id ", ID)
return nil, errors.NewNotFoundError("work item link category", id.String())
}
if db.Error != nil {
return nil, errors.NewInternalError(db.Error.Error())
}
// Convert the created link category entry into a JSONAPI response
result := ConvertLinkCategoryFromModel(res)
return &result, nil
}
// LoadCategoryFromDB return work item link category for the name
func (r *GormWorkItemLinkCategoryRepository) LoadCategoryFromDB(ctx context.Context, name string) (*WorkItemLinkCategory, error) {
log.Info(ctx, map[string]interface{}{
"pkg": "link",
"categoryName": name,
}, "Loading work item link category: %s", name)
res := WorkItemLinkCategory{}
db := r.db.Model(&res).Where("name=?", name).First(&res)
if db.RecordNotFound() {
log.Error(ctx, map[string]interface{}{
"wilcName": name,
}, "work item link category not found")
return nil, errors.NewNotFoundError("work item link category", name)
}
if db.Error != nil {
return nil, errors.NewInternalError(db.Error.Error())
}
return &res, nil
}
// List returns all work item link categories
// TODO: Handle pagination
func (r *GormWorkItemLinkCategoryRepository) List(ctx context.Context) (*app.WorkItemLinkCategoryList, error) {
var rows []WorkItemLinkCategory
db := r.db.Find(&rows)
if db.Error != nil {
return nil, db.Error
}
res := app.WorkItemLinkCategoryList{}
res.Data = make([]*app.WorkItemLinkCategoryData, len(rows))
for index, value := range rows {
cat := ConvertLinkCategoryFromModel(value)
res.Data[index] = cat.Data
}
// TODO: When adding pagination, this must not be len(rows) but
// the overall total number of elements from all pages.
res.Meta = &app.WorkItemLinkCategoryListMeta{
TotalCount: len(rows),
}
return &res, nil
}
// Delete deletes the work item link category with the given id
// returns NotFoundError or InternalError
func (r *GormWorkItemLinkCategoryRepository) Delete(ctx context.Context, ID string) error {
id, err := satoriuuid.FromString(ID)
if err != nil {
// treat as not found: clients don't know it must be a UUID
return errors.NewNotFoundError("work item link category", ID)
}
var cat = WorkItemLinkCategory{
ID: id,
}
log.Info(ctx, map[string]interface{}{
"pkg": "link",
"wilcID": ID,
}, "Work item link category to delete")
db := r.db.Delete(&cat)
if db.Error != nil {
return errors.NewInternalError(db.Error.Error())
}
if db.RowsAffected == 0 {
return errors.NewNotFoundError("work item link category", id.String())
}
return nil
}
// Save updates the given work item link category in storage. Version must be the same as the one int the stored version.
// returns NotFoundError, VersionConflictError, ConversionError or InternalError
func (r *GormWorkItemLinkCategoryRepository) Save(ctx context.Context, linkCat app.WorkItemLinkCategorySingle) (*app.WorkItemLinkCategorySingle, error) {
res := WorkItemLinkCategory{}
if linkCat.Data.ID == nil {
return nil, errors.NewBadParameterError("data.id", linkCat.Data.ID)
}
id, err := satoriuuid.FromString(*linkCat.Data.ID)
if err != nil {
log.Error(ctx, map[string]interface{}{
"wilcID": *linkCat.Data.ID,
"err": err,
}, "error when converting %s to UUID: %s", *linkCat.Data.ID, err.Error())
// treat as not found: clients don't know it must be a UUID
return nil, errors.NewNotFoundError("work item link category", id.String())
}
if linkCat.Data.Type != EndpointWorkItemLinkCategories {
return nil, errors.NewBadParameterError("data.type", linkCat.Data.Type).Expected(EndpointWorkItemLinkCategories)
}
// If the name is not nil, it MUST NOT be empty
if linkCat.Data.Attributes.Name != nil && *linkCat.Data.Attributes.Name == "" {
return nil, errors.NewBadParameterError("data.attributes.name", *linkCat.Data.Attributes.Name)
}
db := r.db.Model(&res).Where("id=?", *linkCat.Data.ID).First(&res)
if db.RecordNotFound() {
log.Error(ctx, map[string]interface{}{
"wilcID": *linkCat.Data.ID,
}, "work item link category not found")
return nil, errors.NewNotFoundError("work item link category", id.String())
}
if db.Error != nil {
log.Error(ctx, map[string]interface{}{
"wilcID": *linkCat.Data.ID,
"err": db.Error,
}, "unable to find work item link category")
return nil, errors.NewInternalError(db.Error.Error())
}
if linkCat.Data.Attributes.Version == nil || res.Version != *linkCat.Data.Attributes.Version {
return nil, errors.NewVersionConflictError("version conflict")
}
newLinkCat := WorkItemLinkCategory{
ID: id,
Version: *linkCat.Data.Attributes.Version + 1,
}
if linkCat.Data.Attributes.Name != nil {
newLinkCat.Name = *linkCat.Data.Attributes.Name
}
if linkCat.Data.Attributes.Description != nil {
newLinkCat.Description = linkCat.Data.Attributes.Description
}
db = db.Save(&newLinkCat)
if db.Error != nil {
log.Error(ctx, map[string]interface{}{
"wilcID": newLinkCat.ID,
"err": db.Error,
}, "unable to save work item link category repository")
return nil, errors.NewInternalError(db.Error.Error())
}
log.Info(ctx, map[string]interface{}{
"pkg": "link",
"wilcID": newLinkCat.ID,
"newLinkCategory": newLinkCat,
}, "Work item link category updated")
result := ConvertLinkCategoryFromModel(newLinkCat)
return &result, nil
}
| NewWorkItemLinkCategoryRepository |
log.rs | #[derive(Copy, Clone, Debug)]
pub enum Verbosity {
None,
Info,
Verbose,
}
pub struct Log {
verbosity: Verbosity,
}
impl From<u64> for Log {
fn from(other: u64) -> Log {
Log {
verbosity: match other {
0 => Verbosity::None,
1 => Verbosity::Info,
2 => Verbosity::Verbose, | }
}
}
impl Log {
pub fn log(&self, verbosity: Verbosity, text: String) {
if self.verbosity as usize >= verbosity as usize {
println!("{}", text);
}
}
pub fn verbose(&self, text: String) {
self.log(Verbosity::Verbose, text)
}
pub fn info(&self, text: String) {
self.log(Verbosity::Info, text)
}
} | _ => Verbosity::Verbose,
}, |
module_graph.rs | // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::checksum;
use crate::file_fetcher::map_file_extension;
use crate::file_fetcher::SourceFile;
use crate::file_fetcher::SourceFileFetcher;
use crate::import_map::ImportMap;
use crate::msg::MediaType;
use crate::permissions::Permissions;
use crate::swc_util::Location;
use crate::tsc::pre_process_file;
use crate::tsc::ImportDesc;
use crate::tsc::TsReferenceDesc;
use crate::tsc::TsReferenceKind;
use crate::tsc::AVAILABLE_LIBS;
use crate::version;
use deno_core::ErrBox;
use deno_core::ModuleSpecifier;
use futures::stream::FuturesUnordered;
use futures::stream::StreamExt;
use futures::Future;
use futures::FutureExt;
use serde::Serialize;
use serde::Serializer;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;
use std::pin::Pin;
// TODO(bartlomieju): it'd be great if this function returned
// more structured data and possibly format the same as TS diagnostics.
/// Decorate error with location of import that caused the error.
fn err_with_location(e: ErrBox, maybe_location: Option<&Location>) -> ErrBox {
if let Some(location) = maybe_location {
let location_str = format!(
"\nImported from \"{}:{}\"",
location.filename, location.line
);
let err_str = e.to_string();
ErrBox::error(format!("{}{}", err_str, location_str))
} else {
e
}
}
/// Disallow http:// imports from modules loaded over https://
fn validate_no_downgrade(
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<&ModuleSpecifier>,
maybe_location: Option<&Location>,
) -> Result<(), ErrBox> {
if let Some(referrer) = maybe_referrer.as_ref() {
if let "https" = referrer.as_url().scheme() {
if let "http" = module_specifier.as_url().scheme() {
let e = ErrBox::new("PermissionDenied",
"Modules loaded over https:// are not allowed to import modules over http://"
);
return Err(err_with_location(e, maybe_location));
};
};
};
Ok(())
}
/// Verify that remote file doesn't try to statically import local file.
fn validate_no_file_from_remote(
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<&ModuleSpecifier>,
maybe_location: Option<&Location>,
) -> Result<(), ErrBox> {
if let Some(referrer) = maybe_referrer.as_ref() {
let referrer_url = referrer.as_url();
match referrer_url.scheme() {
"http" | "https" => {
let specifier_url = module_specifier.as_url();
match specifier_url.scheme() {
"http" | "https" => {}
_ => {
let e = ErrBox::new(
"PermissionDenied",
"Remote modules are not allowed to statically import local \
modules. Use dynamic import instead.",
);
return Err(err_with_location(e, maybe_location));
}
}
}
_ => {}
}
}
Ok(())
}
// TODO(bartlomieju): handle imports/references in ambient contexts/TS modules
// https://github.com/denoland/deno/issues/6133
fn resolve_imports_and_references(
referrer: ModuleSpecifier,
maybe_import_map: Option<&ImportMap>,
import_descs: Vec<ImportDesc>,
ref_descs: Vec<TsReferenceDesc>,
) -> Result<(Vec<ImportDescriptor>, Vec<ReferenceDescriptor>), ErrBox> {
let mut imports = vec![];
let mut references = vec![];
for import_desc in import_descs {
let maybe_resolved = if let Some(import_map) = maybe_import_map.as_ref() {
import_map.resolve(&import_desc.specifier, &referrer.to_string())?
} else {
None
};
let resolved_specifier = if let Some(resolved) = maybe_resolved {
resolved
} else {
ModuleSpecifier::resolve_import(
&import_desc.specifier,
&referrer.to_string(),
)?
};
let resolved_type_directive =
if let Some(types_specifier) = import_desc.deno_types.as_ref() {
Some(ModuleSpecifier::resolve_import(
&types_specifier,
&referrer.to_string(),
)?)
} else {
None
};
let import_descriptor = ImportDescriptor {
specifier: import_desc.specifier.to_string(),
resolved_specifier,
type_directive: import_desc.deno_types.clone(),
resolved_type_directive,
location: import_desc.location,
};
imports.push(import_descriptor);
}
for ref_desc in ref_descs {
if AVAILABLE_LIBS.contains(&ref_desc.specifier.as_str()) {
continue;
}
let resolved_specifier = ModuleSpecifier::resolve_import(
&ref_desc.specifier,
&referrer.to_string(),
)?;
let reference_descriptor = ReferenceDescriptor {
specifier: ref_desc.specifier.to_string(),
resolved_specifier,
kind: ref_desc.kind,
location: ref_desc.location,
};
references.push(reference_descriptor);
}
Ok((imports, references))
}
fn serialize_module_specifier<S>(
spec: &ModuleSpecifier,
s: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(&spec.to_string())
}
fn serialize_option_module_specifier<S>(
maybe_spec: &Option<ModuleSpecifier>,
s: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if let Some(spec) = maybe_spec {
serialize_module_specifier(spec, s)
} else {
s.serialize_none()
}
}
const SUPPORTED_MEDIA_TYPES: [MediaType; 4] = [
MediaType::JavaScript,
MediaType::TypeScript,
MediaType::JSX,
MediaType::TSX,
];
pub type ModuleGraph = HashMap<String, ModuleGraphFile>;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ImportDescriptor {
pub specifier: String,
#[serde(serialize_with = "serialize_module_specifier")]
pub resolved_specifier: ModuleSpecifier,
// These two fields are for support of @deno-types directive
// directly prepending import statement
pub type_directive: Option<String>,
#[serde(serialize_with = "serialize_option_module_specifier")]
pub resolved_type_directive: Option<ModuleSpecifier>,
#[serde(skip)]
pub location: Location,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceDescriptor {
pub specifier: String,
#[serde(serialize_with = "serialize_module_specifier")]
pub resolved_specifier: ModuleSpecifier,
#[serde(skip)]
pub kind: TsReferenceKind,
#[serde(skip)]
pub location: Location,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModuleGraphFile {
pub specifier: String,
pub url: String,
pub redirect: Option<String>,
pub filename: String,
pub version_hash: String,
pub imports: Vec<ImportDescriptor>,
pub referenced_files: Vec<ReferenceDescriptor>,
pub lib_directives: Vec<ReferenceDescriptor>,
pub types_directives: Vec<ReferenceDescriptor>,
pub type_headers: Vec<ReferenceDescriptor>,
pub media_type: MediaType,
pub source_code: String,
}
type SourceFileFuture =
Pin<Box<dyn Future<Output = Result<(ModuleSpecifier, SourceFile), ErrBox>>>>;
pub struct ModuleGraphLoader {
permissions: Permissions,
file_fetcher: SourceFileFetcher,
maybe_import_map: Option<ImportMap>,
pending_downloads: FuturesUnordered<SourceFileFuture>,
has_downloaded: HashSet<ModuleSpecifier>,
graph: ModuleGraph,
is_dyn_import: bool,
analyze_dynamic_imports: bool,
}
impl ModuleGraphLoader {
pub fn new(
file_fetcher: SourceFileFetcher,
maybe_import_map: Option<ImportMap>,
permissions: Permissions,
is_dyn_import: bool,
analyze_dynamic_imports: bool,
) -> Self {
Self {
file_fetcher,
permissions,
maybe_import_map,
pending_downloads: FuturesUnordered::new(),
has_downloaded: HashSet::new(),
graph: ModuleGraph::new(),
is_dyn_import,
analyze_dynamic_imports,
}
}
/// This method is used to add specified module and all of its
/// dependencies to the graph.
///
/// It resolves when all dependent modules have been fetched and analyzed.
///
/// This method can be called multiple times.
pub async fn add_to_graph(
&mut self,
specifier: &ModuleSpecifier,
maybe_referrer: Option<ModuleSpecifier>,
) -> Result<(), ErrBox> |
/// This method is used to create a graph from in-memory files stored in
/// a hash map. Useful for creating module graph for code received from
/// the runtime.
pub fn build_local_graph(
&mut self,
_root_name: &str,
source_map: &HashMap<String, String>,
) -> Result<(), ErrBox> {
for (spec, source_code) in source_map.iter() {
self.visit_memory_module(spec.to_string(), source_code.to_string())?;
}
Ok(())
}
/// Consumes the loader and returns created graph.
pub fn get_graph(self) -> ModuleGraph {
self.graph
}
fn visit_memory_module(
&mut self,
specifier: String,
source_code: String,
) -> Result<(), ErrBox> {
let mut referenced_files = vec![];
let mut lib_directives = vec![];
let mut types_directives = vec![];
// FIXME(bartlomieju):
// The resolveModules op only handles fully qualified URLs for referrer.
// However we will have cases where referrer is "/foo.ts". We add this dummy
// prefix "memory://" in order to use resolution logic.
let module_specifier =
if let Ok(spec) = ModuleSpecifier::resolve_url(&specifier) {
spec
} else {
ModuleSpecifier::resolve_url(&format!("memory://{}", specifier))?
};
let (raw_imports, raw_references) = pre_process_file(
&module_specifier.to_string(),
map_file_extension(&PathBuf::from(&specifier)),
&source_code,
self.analyze_dynamic_imports,
)?;
let (imports, references) = resolve_imports_and_references(
module_specifier.clone(),
self.maybe_import_map.as_ref(),
raw_imports,
raw_references,
)?;
for ref_descriptor in references {
match ref_descriptor.kind {
TsReferenceKind::Lib => {
lib_directives.push(ref_descriptor);
}
TsReferenceKind::Types => {
types_directives.push(ref_descriptor);
}
TsReferenceKind::Path => {
referenced_files.push(ref_descriptor);
}
}
}
self.graph.insert(
module_specifier.to_string(),
ModuleGraphFile {
specifier: specifier.to_string(),
url: specifier.to_string(),
redirect: None,
version_hash: "".to_string(),
media_type: map_file_extension(&PathBuf::from(specifier.clone())),
filename: specifier,
source_code,
imports,
referenced_files,
lib_directives,
types_directives,
type_headers: vec![],
},
);
Ok(())
}
// TODO(bartlomieju): decorate errors with import location in the source code
// https://github.com/denoland/deno/issues/5080
fn download_module(
&mut self,
module_specifier: ModuleSpecifier,
maybe_referrer: Option<ModuleSpecifier>,
maybe_location: Option<Location>,
) -> Result<(), ErrBox> {
if self.has_downloaded.contains(&module_specifier) {
return Ok(());
}
validate_no_downgrade(
&module_specifier,
maybe_referrer.as_ref(),
maybe_location.as_ref(),
)?;
if !self.is_dyn_import {
validate_no_file_from_remote(
&module_specifier,
maybe_referrer.as_ref(),
maybe_location.as_ref(),
)?;
}
self.has_downloaded.insert(module_specifier.clone());
let spec = module_specifier;
let file_fetcher = self.file_fetcher.clone();
let perms = self.permissions.clone();
let load_future = async move {
let spec_ = spec.clone();
let source_file = file_fetcher
.fetch_source_file(&spec_, maybe_referrer, perms)
.await
.map_err(|e| err_with_location(e, maybe_location.as_ref()))?;
Ok((spec_.clone(), source_file))
}
.boxed_local();
self.pending_downloads.push(load_future);
Ok(())
}
fn visit_module(
&mut self,
module_specifier: &ModuleSpecifier,
source_file: SourceFile,
) -> Result<(), ErrBox> {
let mut imports = vec![];
let mut referenced_files = vec![];
let mut lib_directives = vec![];
let mut types_directives = vec![];
let mut type_headers = vec![];
// IMPORTANT: source_file.url might be different than requested
// module_specifier because of HTTP redirects. In such
// situation we add an "empty" ModuleGraphFile with 'redirect'
// field set that will be later used in TS worker when building
// map of available source file. It will perform substitution
// for proper URL point to redirect target.
if module_specifier.as_url() != &source_file.url {
// TODO(bartlomieju): refactor, this is a band-aid
self.graph.insert(
module_specifier.to_string(),
ModuleGraphFile {
specifier: module_specifier.to_string(),
url: module_specifier.to_string(),
redirect: Some(source_file.url.to_string()),
filename: source_file.filename.to_str().unwrap().to_string(),
version_hash: checksum::gen(&[
&source_file.source_code.as_bytes(),
version::DENO.as_bytes(),
]),
media_type: source_file.media_type,
source_code: "".to_string(),
imports: vec![],
referenced_files: vec![],
lib_directives: vec![],
types_directives: vec![],
type_headers: vec![],
},
);
}
let module_specifier = ModuleSpecifier::from(source_file.url.clone());
let version_hash = checksum::gen(&[
&source_file.source_code.as_bytes(),
version::DENO.as_bytes(),
]);
let source_code = source_file.source_code.to_string()?;
if SUPPORTED_MEDIA_TYPES.contains(&source_file.media_type) {
if let Some(types_specifier) = source_file.types_header {
let type_header = ReferenceDescriptor {
specifier: types_specifier.to_string(),
resolved_specifier: ModuleSpecifier::resolve_import(
&types_specifier,
&module_specifier.to_string(),
)?,
kind: TsReferenceKind::Types,
// TODO(bartlomieju): location is not needed in here and constructing
// location by hand is bad
location: Location {
filename: module_specifier.to_string(),
line: 0,
col: 0,
},
};
self.download_module(
type_header.resolved_specifier.clone(),
Some(module_specifier.clone()),
None,
)?;
type_headers.push(type_header);
}
let (raw_imports, raw_refs) = pre_process_file(
&module_specifier.to_string(),
source_file.media_type,
&source_code,
self.analyze_dynamic_imports,
)?;
let (imports_, references) = resolve_imports_and_references(
module_specifier.clone(),
self.maybe_import_map.as_ref(),
raw_imports,
raw_refs,
)?;
for import_descriptor in imports_ {
self.download_module(
import_descriptor.resolved_specifier.clone(),
Some(module_specifier.clone()),
Some(import_descriptor.location.clone()),
)?;
if let Some(type_dir_url) =
import_descriptor.resolved_type_directive.as_ref()
{
self.download_module(
type_dir_url.clone(),
Some(module_specifier.clone()),
Some(import_descriptor.location.clone()),
)?;
}
imports.push(import_descriptor);
}
for ref_descriptor in references {
self.download_module(
ref_descriptor.resolved_specifier.clone(),
Some(module_specifier.clone()),
Some(ref_descriptor.location.clone()),
)?;
match ref_descriptor.kind {
TsReferenceKind::Lib => {
lib_directives.push(ref_descriptor);
}
TsReferenceKind::Types => {
types_directives.push(ref_descriptor);
}
TsReferenceKind::Path => {
referenced_files.push(ref_descriptor);
}
}
}
}
self.graph.insert(
module_specifier.to_string(),
ModuleGraphFile {
specifier: module_specifier.to_string(),
url: module_specifier.to_string(),
redirect: None,
version_hash,
filename: source_file.filename.to_str().unwrap().to_string(),
media_type: source_file.media_type,
source_code,
imports,
referenced_files,
lib_directives,
types_directives,
type_headers,
},
);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::global_state::GlobalState;
async fn build_graph(
module_specifier: &ModuleSpecifier,
) -> Result<ModuleGraph, ErrBox> {
let global_state = GlobalState::new(Default::default()).unwrap();
let mut graph_loader = ModuleGraphLoader::new(
global_state.file_fetcher.clone(),
None,
Permissions::allow_all(),
false,
false,
);
graph_loader.add_to_graph(&module_specifier, None).await?;
Ok(graph_loader.get_graph())
}
// TODO(bartlomieju): this test is flaky, because it's using 019_media_types
// file, reenable once Python server is replaced with Rust one.
#[ignore]
#[tokio::test]
async fn source_graph_fetch() {
let _http_server_guard = test_util::http_server();
let module_specifier = ModuleSpecifier::resolve_url_or_path(
"http://localhost:4545/cli/tests/019_media_types.ts",
)
.unwrap();
let graph = build_graph(&module_specifier)
.await
.expect("Failed to build graph");
let a = graph
.get("http://localhost:4545/cli/tests/019_media_types.ts")
.unwrap();
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/subdir/mt_text_ecmascript.j3.js"
));
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/subdir/mt_video_vdn.t2.ts"
));
assert!(graph.contains_key("http://localhost:4545/cli/tests/subdir/mt_application_x_typescript.t4.ts"));
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/subdir/mt_video_mp2t.t3.ts"
));
assert!(graph.contains_key("http://localhost:4545/cli/tests/subdir/mt_application_x_javascript.j4.js"));
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/subdir/mt_application_ecmascript.j2.js"
));
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/subdir/mt_text_javascript.j1.js"
));
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/subdir/mt_text_typescript.t1.ts"
));
assert_eq!(
serde_json::to_value(&a.imports).unwrap(),
json!([
{
"specifier": "http://localhost:4545/cli/tests/subdir/mt_text_typescript.t1.ts",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/mt_text_typescript.t1.ts",
"typeDirective": null,
"resolvedTypeDirective": null,
},
{
"specifier": "http://localhost:4545/cli/tests/subdir/mt_video_vdn.t2.ts",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/mt_video_vdn.t2.ts",
"typeDirective": null,
"resolvedTypeDirective": null,
},
{
"specifier": "http://localhost:4545/cli/tests/subdir/mt_video_mp2t.t3.ts",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/mt_video_mp2t.t3.ts",
"typeDirective": null,
"resolvedTypeDirective": null,
},
{
"specifier": "http://localhost:4545/cli/tests/subdir/mt_application_x_typescript.t4.ts",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/mt_application_x_typescript.t4.ts",
"typeDirective": null,
"resolvedTypeDirective": null,
},
{
"specifier": "http://localhost:4545/cli/tests/subdir/mt_text_javascript.j1.js",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/mt_text_javascript.j1.js",
"typeDirective": null,
"resolvedTypeDirective": null,
},
{
"specifier": "http://localhost:4545/cli/tests/subdir/mt_application_ecmascript.j2.js",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/mt_application_ecmascript.j2.js",
"typeDirective": null,
"resolvedTypeDirective": null,
},
{
"specifier": "http://localhost:4545/cli/tests/subdir/mt_text_ecmascript.j3.js",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/mt_text_ecmascript.j3.js",
"typeDirective": null,
"resolvedTypeDirective": null,
},
{
"specifier": "http://localhost:4545/cli/tests/subdir/mt_application_x_javascript.j4.js",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/mt_application_x_javascript.j4.js",
"typeDirective": null,
"resolvedTypeDirective": null,
},
])
);
}
#[tokio::test]
async fn source_graph_type_references() {
let _http_server_guard = test_util::http_server();
let module_specifier = ModuleSpecifier::resolve_url_or_path(
"http://localhost:4545/cli/tests/type_definitions.ts",
)
.unwrap();
let graph = build_graph(&module_specifier)
.await
.expect("Failed to build graph");
eprintln!("json {:#?}", serde_json::to_value(&graph).unwrap());
let a = graph
.get("http://localhost:4545/cli/tests/type_definitions.ts")
.unwrap();
assert_eq!(
serde_json::to_value(&a.imports).unwrap(),
json!([
{
"specifier": "./type_definitions/foo.js",
"resolvedSpecifier": "http://localhost:4545/cli/tests/type_definitions/foo.js",
"typeDirective": "./type_definitions/foo.d.ts",
"resolvedTypeDirective": "http://localhost:4545/cli/tests/type_definitions/foo.d.ts"
},
{
"specifier": "./type_definitions/fizz.js",
"resolvedSpecifier": "http://localhost:4545/cli/tests/type_definitions/fizz.js",
"typeDirective": "./type_definitions/fizz.d.ts",
"resolvedTypeDirective": "http://localhost:4545/cli/tests/type_definitions/fizz.d.ts"
},
{
"specifier": "./type_definitions/qat.ts",
"resolvedSpecifier": "http://localhost:4545/cli/tests/type_definitions/qat.ts",
"typeDirective": null,
"resolvedTypeDirective": null,
},
])
);
assert!(graph
.contains_key("http://localhost:4545/cli/tests/type_definitions/foo.js"));
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/type_definitions/foo.d.ts"
));
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/type_definitions/fizz.js"
));
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/type_definitions/fizz.d.ts"
));
assert!(graph
.contains_key("http://localhost:4545/cli/tests/type_definitions/qat.ts"));
}
#[tokio::test]
async fn source_graph_type_references2() {
let _http_server_guard = test_util::http_server();
let module_specifier = ModuleSpecifier::resolve_url_or_path(
"http://localhost:4545/cli/tests/type_directives_02.ts",
)
.unwrap();
let graph = build_graph(&module_specifier)
.await
.expect("Failed to build graph");
eprintln!("{:#?}", serde_json::to_value(&graph).unwrap());
let a = graph
.get("http://localhost:4545/cli/tests/type_directives_02.ts")
.unwrap();
assert_eq!(
serde_json::to_value(&a.imports).unwrap(),
json!([
{
"specifier": "./subdir/type_reference.js",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/type_reference.js",
"typeDirective": null,
"resolvedTypeDirective": null,
}
])
);
assert!(graph.contains_key(
"http://localhost:4545/cli/tests/subdir/type_reference.d.ts"
));
let b = graph
.get("http://localhost:4545/cli/tests/subdir/type_reference.js")
.unwrap();
assert_eq!(
serde_json::to_value(&b.types_directives).unwrap(),
json!([
{
"specifier": "./type_reference.d.ts",
"resolvedSpecifier": "http://localhost:4545/cli/tests/subdir/type_reference.d.ts",
}
])
);
}
#[tokio::test]
async fn source_graph_type_references3() {
let _http_server_guard = test_util::http_server();
let module_specifier = ModuleSpecifier::resolve_url_or_path(
"http://localhost:4545/cli/tests/type_directives_01.ts",
)
.unwrap();
let graph = build_graph(&module_specifier)
.await
.expect("Failed to build graph");
let ts = graph
.get("http://localhost:4545/cli/tests/type_directives_01.ts")
.unwrap();
assert_eq!(
serde_json::to_value(&ts.imports).unwrap(),
json!([
{
"specifier": "http://127.0.0.1:4545/xTypeScriptTypes.js",
"resolvedSpecifier": "http://127.0.0.1:4545/xTypeScriptTypes.js",
"typeDirective": null,
"resolvedTypeDirective": null,
}
])
);
let headers = graph
.get("http://127.0.0.1:4545/xTypeScriptTypes.js")
.unwrap();
assert_eq!(
serde_json::to_value(&headers.type_headers).unwrap(),
json!([
{
"specifier": "./xTypeScriptTypes.d.ts",
"resolvedSpecifier": "http://127.0.0.1:4545/xTypeScriptTypes.d.ts"
}
])
);
}
#[tokio::test]
async fn source_graph_different_langs() {
let _http_server_guard = test_util::http_server();
// ModuleGraphLoader was mistakenly parsing this file as TSX
// https://github.com/denoland/deno/issues/5867
let module_specifier = ModuleSpecifier::resolve_url_or_path(
"http://localhost:4545/cli/tests/ts_with_generic.ts",
)
.unwrap();
build_graph(&module_specifier)
.await
.expect("Failed to build graph");
}
}
// TODO(bartlomieju): use baseline tests from TSC to ensure
// compatibility
#[test]
fn test_pre_process_file() {
let source = r#"
// This comment is placed to make sure that directives are parsed
// even when they start on non-first line
/// <reference lib="dom" />
/// <reference types="./type_reference.d.ts" />
/// <reference path="./type_reference/dep.ts" />
// @deno-types="./type_definitions/foo.d.ts"
import { foo } from "./type_definitions/foo.js";
// @deno-types="./type_definitions/fizz.d.ts"
import "./type_definitions/fizz.js";
/// <reference path="./type_reference/dep2.ts" />
import * as qat from "./type_definitions/qat.ts";
console.log(foo);
console.log(fizz);
console.log(qat.qat);
"#;
let (imports, references) =
pre_process_file("some/file.ts", MediaType::TypeScript, source, true)
.expect("Failed to parse");
assert_eq!(
imports,
vec![
ImportDesc {
specifier: "./type_definitions/foo.js".to_string(),
deno_types: Some("./type_definitions/foo.d.ts".to_string()),
location: Location {
filename: "some/file.ts".to_string(),
line: 9,
col: 0,
},
},
ImportDesc {
specifier: "./type_definitions/fizz.js".to_string(),
deno_types: Some("./type_definitions/fizz.d.ts".to_string()),
location: Location {
filename: "some/file.ts".to_string(),
line: 11,
col: 0,
},
},
ImportDesc {
specifier: "./type_definitions/qat.ts".to_string(),
deno_types: None,
location: Location {
filename: "some/file.ts".to_string(),
line: 15,
col: 0,
},
},
]
);
// According to TS docs (https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)
// directives that are not at the top of the file are ignored, so only
// 3 references should be captured instead of 4.
assert_eq!(
references,
vec![
TsReferenceDesc {
specifier: "dom".to_string(),
kind: TsReferenceKind::Lib,
location: Location {
filename: "some/file.ts".to_string(),
line: 5,
col: 0,
},
},
TsReferenceDesc {
specifier: "./type_reference.d.ts".to_string(),
kind: TsReferenceKind::Types,
location: Location {
filename: "some/file.ts".to_string(),
line: 6,
col: 0,
},
},
TsReferenceDesc {
specifier: "./type_reference/dep.ts".to_string(),
kind: TsReferenceKind::Path,
location: Location {
filename: "some/file.ts".to_string(),
line: 7,
col: 0,
},
},
]
);
}
| {
self.download_module(specifier.clone(), maybe_referrer, None)?;
loop {
let (specifier, source_file) =
self.pending_downloads.next().await.unwrap()?;
self.visit_module(&specifier, source_file)?;
if self.pending_downloads.is_empty() {
break;
}
}
Ok(())
} |
sideauxpow.go | package auxpow
import (
"io"
"github.com/elastos/Elastos.ELA/auxpow"
"github.com/elastos/Elastos.ELA/common"
ela "github.com/elastos/Elastos.ELA/core/types"
"github.com/elastos/Elastos.ELA/core/types/payload"
)
type SideAuxPow struct {
SideAuxMerkleBranch []common.Uint256
SideAuxMerkleIndex int
SideAuxBlockTx ela.Transaction
MainBlockHeader ela.Header
}
func NewSideAuxPow(sideAuxMerkleBranch []common.Uint256,
sideAuxMerkleIndex int,
sideAuxBlockTx ela.Transaction,
mainBlockHeader ela.Header) *SideAuxPow {
return &SideAuxPow{
SideAuxMerkleBranch: sideAuxMerkleBranch,
SideAuxMerkleIndex: sideAuxMerkleIndex,
SideAuxBlockTx: sideAuxBlockTx,
MainBlockHeader: mainBlockHeader,
}
}
func (sap *SideAuxPow) Serialize(w io.Writer) error {
err := sap.SideAuxBlockTx.Serialize(w)
if err != nil {
return err
}
err = common.WriteUint32(w, uint32(len(sap.SideAuxMerkleBranch)))
if err != nil {
return err
}
for _, branch := range sap.SideAuxMerkleBranch {
err = branch.Serialize(w)
if err != nil {
return err
}
}
err = common.WriteUint32(w, uint32(sap.SideAuxMerkleIndex))
if err != nil {
return err
}
return sap.MainBlockHeader.Serialize(w)
}
func (sap *SideAuxPow) Deserialize(r io.Reader) error {
err := sap.SideAuxBlockTx.Deserialize(r)
if err != nil {
return err
}
count, err := common.ReadUint32(r)
if err != nil {
return err
}
sap.SideAuxMerkleBranch = make([]common.Uint256, 0, count)
for i := uint32(0); i < count; i++ {
var branch common.Uint256
err = branch.Deserialize(r)
if err != nil {
return err
}
sap.SideAuxMerkleBranch = append(sap.SideAuxMerkleBranch, branch)
}
| if err != nil {
return err
}
sap.SideAuxMerkleIndex = int(index)
return sap.MainBlockHeader.Deserialize(r)
}
func (sap *SideAuxPow) SideAuxPowCheck(hashAuxBlock common.Uint256) bool {
mainBlockHeader := sap.MainBlockHeader
mainBlockHeaderHash := mainBlockHeader.Hash()
if !mainBlockHeader.AuxPow.Check(&mainBlockHeaderHash, auxpow.AuxPowChainID) {
return false
}
sideAuxPowMerkleRoot := auxpow.GetMerkleRoot(sap.SideAuxBlockTx.Hash(), sap.SideAuxMerkleBranch, sap.SideAuxMerkleIndex)
if sideAuxPowMerkleRoot != sap.MainBlockHeader.MerkleRoot {
return false
}
payloadData := sap.SideAuxBlockTx.Payload.Data(payload.SideChainPowVersion)
payloadHashData := payloadData[0:32]
payloadHash, err := common.Uint256FromBytes(payloadHashData)
if err != nil {
return false
}
if *payloadHash != hashAuxBlock {
return false
}
return true
} | index, err := common.ReadUint32(r) |
085_Higher_Version.py | # https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/vsKRjYKv4SCjzJc8r/
def | (ver1, ver2):
# Split by dots, convert individual elements to ints.
ver1 = [int(x) for x in ver1.split(".")]
ver2 = [int(x) for x in ver2.split(".")]
# This will do a comparison item-wise of all elements in the iterable arrays.
return ver1 > ver2
| higherVersion |
parser.go | // Package parser implements the parsing of lighthouse reports into Go types
package parser
import (
"encoding/json"
"github.com/giantswarm/microerror"
)
// ParseReportJSON consumes lighthouse report JSON and returns a pointer to
// a Report object.
func | (jsonBlob []byte) (*Report, error) {
var report *Report
err := json.Unmarshal(jsonBlob, &report)
if err != nil {
return nil, microerror.Mask(err)
}
return report, nil
}
| ParseReportJSON |
comment_delete_test.go | package main
import (
"testing"
"time"
)
func TestCommentDeleteBasics(t *testing.T) {
failTestOnError(t, setupTestEnv())
commenterHex := "temp-commenter-hex"
commentHex, _ := commentNew(commenterHex, "example.com", "/path.html", "root", "**foo**", "approved", time.Now().UTC())
commentNew(commenterHex, "example.com", "/path.html", commentHex, "**bar**", "approved", time.Now().UTC()) | }
c, _, _ := commentList(commenterHex, "example.com", "/path.html", false)
if len(c) != 0 {
t.Errorf("expected no comments found %d comments", len(c))
return
}
}
func TestCommentDeleteEmpty(t *testing.T) {
failTestOnError(t, setupTestEnv())
if err := commentDelete("", "test-commenter-hex"); err == nil {
t.Errorf("expected error deleting comment with empty commentHex")
return
}
} |
if err := commentDelete(commentHex, commenterHex); err != nil {
t.Errorf("unexpected error deleting comment: %v", err)
return |
mod.rs | pub fn init(fzf: bool) -> String {
let completion = include_str!("completion.zsh");
let work = if fzf {
include_str!("fzf.zsh")
} else | ;
format!("{}\n{}", completion, work)
}
| {
include_str!("work.zsh")
} |
session.rs | use minibankdb::UserBase;
use std::sync::{Arc,Mutex};
use std::collections::HashMap;
pub struct Session{
pub ub:UserBase,
data:Arc<Mutex<HashMap<u64,String>>>,
}
impl Session{
pub fn new(dbfile:&str)->Self{
Session{
ub:UserBase::new(dbfile),
data:Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn add_session(&self,uname:String)->u64{
let mut mp = self.data.lock().unwrap();
let mut r:u64 = rand::random();
while let Some(_) = mp.get(&r){
r = rand::random();
}
mp.insert(r,uname);
r | mp.get(&s).map(|s|s.clone())
}
}
#[cfg(test)]
mod test{
use super::*;
fn test_sess(){
let ss = Session::new("");
let id = ss.add_session("dave".to_string());
assert_eq!(&ss.get_session(id).unwrap(),"dave");
assert!(&ss.get_session(3).is_none());
}
} | }
pub fn get_session(&self,s:u64)->Option<String>{
let mp = self.data.lock().unwrap(); |
ndarray.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# coding: utf-8
# pylint: disable=invalid-name, protected-access, too-many-arguments
# pylint: disable=global-statement, unused-import
"""NDArray configuration API."""
from __future__ import absolute_import as _abs
import ctypes
from ..base import _LIB
from ..base import c_str_array, c_handle_array
from ..base import NDArrayHandle, CachedOpHandle
from ..base import check_call
def _monitor_callback_wrapper(callback):
"""A wrapper for the user-defined handle."""
def callback_handle(name, opr_name, array, _):
""" ctypes function """
callback(name, opr_name, array)
return callback_handle
class NDArrayBase(object):
"""Base data structure for ndarray"""
__slots__ = ["handle", "writable"]
# pylint: disable= no-member
def __init__(self, handle, writable=True):
"""initialize a new NDArray
Parameters
----------
handle : NDArrayHandle
NDArray handle of C API
"""
if handle is not None:
assert isinstance(handle, NDArrayHandle)
self.handle = handle
self.writable = writable
def __del__(self):
check_call(_LIB.MXNDArrayFree(self.handle))
def __reduce__(self):
return (_ndarray_cls, (None,), self.__getstate__())
_ndarray_cls = None
_np_ndarray_cls = None
def _set_ndarray_class(cls):
"""Set the symbolic class to be cls"""
global _ndarray_cls
_ndarray_cls = cls
def | (cls):
"""Set the symbolic class to be cls"""
global _np_ndarray_cls
_np_ndarray_cls = cls
def _imperative_invoke(handle, ndargs, keys, vals, out, is_np_op, output_is_list):
"""ctypes implementation of imperative invoke wrapper"""
if out is not None:
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(out)
output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))
else:
original_output = None
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
# return output stypes to avoid the c_api call for checking
# a handle's stype in _ndarray_cls
out_stypes = ctypes.POINTER(ctypes.c_int)()
check_call(_LIB.MXImperativeInvokeEx(
ctypes.c_void_p(handle),
ctypes.c_int(len(ndargs)),
c_handle_array(ndargs),
ctypes.byref(num_output),
ctypes.byref(output_vars),
ctypes.c_int(len(keys)),
c_str_array(keys),
c_str_array([str(s) for s in vals]),
ctypes.byref(out_stypes)))
create_ndarray_fn = _np_ndarray_cls if is_np_op else _ndarray_cls
if original_output is not None:
return original_output
if num_output.value == 1 and not output_is_list:
return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle),
stype=out_stypes[0])
else:
return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle),
stype=out_stypes[i]) for i in range(num_output.value)]
class CachedOp(object):
"""Cached operator handle."""
__slots__ = ["handle", "is_np_sym", "_monitor_callback"]
def __init__(self, sym, flags=()):
self.handle = CachedOpHandle()
self._monitor_callback = None
from ..symbol.numpy._symbol import _Symbol
self.is_np_sym = bool(isinstance(sym, _Symbol))
check_call(_LIB.MXCreateCachedOpEx(
sym.handle,
len(flags),
c_str_array([key for key, _ in flags]),
c_str_array([str(val) for _, val in flags]),
ctypes.byref(self.handle)))
def __del__(self):
check_call(_LIB.MXFreeCachedOp(self.handle))
def __call__(self, *args, **kwargs):
"""ctypes implementation of imperative invoke wrapper"""
out = kwargs.pop('out', None)
if out is not None:
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(out)
output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))
else:
original_output = None
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
if kwargs:
raise TypeError(
"CachedOp.__call__ got unexpected keyword argument(s): " + \
', '.join(kwargs.keys()))
# return output stypes to avoid the c_api call for checking
# a handle's stype in _ndarray_cls
out_stypes = ctypes.POINTER(ctypes.c_int)()
check_call(_LIB.MXInvokeCachedOpEx(
self.handle,
ctypes.c_int(len(args)),
c_handle_array(args),
ctypes.byref(num_output),
ctypes.byref(output_vars),
ctypes.byref(out_stypes)))
if original_output is not None:
return original_output
create_ndarray_fn = _np_ndarray_cls if self.is_np_sym else _ndarray_cls
if num_output.value == 1:
return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle),
stype=out_stypes[0])
else:
return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle),
stype=out_stypes[i]) for i in range(num_output.value)]
def _register_op_hook(self, callback, monitor_all=False):
"""Install callback for monitor.
Parameters
----------
callback : function
Takes a string for node_name, string for op_name and a NDArrayHandle.
monitor_all : bool, default False
If true, monitor both input _imperative_invoked output, otherwise monitor output only.
"""
cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p)
if callback:
self._monitor_callback = cb_type(_monitor_callback_wrapper(callback))
check_call(_LIB.MXCachedOpRegisterOpHook(
self.handle,
self._monitor_callback,
ctypes.c_int(monitor_all)))
| _set_np_ndarray_class |
multiview_multisampled_render_to_texture.py | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLES2 import _types as _cs
# End users want this...
from OpenGL.raw.GLES2._types import *
from OpenGL.raw.GLES2 import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GLES2_OVR_multiview_multisampled_render_to_texture'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GLES2,'GLES2_OVR_multiview_multisampled_render_to_texture',error_checker=_errors._error_checker)
@_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLuint,_cs.GLint,_cs.GLsizei,_cs.GLint,_cs.GLsizei)
def | (target,attachment,texture,level,samples,baseViewIndex,numViews):pass
| glFramebufferTextureMultisampleMultiviewOVR |
cluster.go | package redis
import (
"fmt"
"math/rand"
"net"
"sync"
"sync/atomic"
"time"
"github.com/go-redis/redis/internal"
"github.com/go-redis/redis/internal/hashtag"
"github.com/go-redis/redis/internal/pool"
"github.com/go-redis/redis/internal/proto"
)
var errClusterNoNodes = internal.RedisError("redis: cluster has no nodes")
var errNilClusterState = internal.RedisError("redis: cannot load cluster slots")
// ClusterOptions are used to configure a cluster client and should be
// passed to NewClusterClient.
type ClusterOptions struct {
// A seed list of host:port addresses of cluster nodes.
Addrs []string
// The maximum number of retries before giving up. Command is retried
// on network errors and MOVED/ASK redirects.
// Default is 16.
MaxRedirects int
// Enables read queries for a connection to a Redis Cluster slave node.
ReadOnly bool
// Enables routing read-only queries to the closest master or slave node.
RouteByLatency bool
// Following options are copied from Options struct.
OnConnect func(*Conn) error
MaxRetries int
Password string
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
// PoolSize applies per cluster node and not for the whole cluster.
PoolSize int
PoolTimeout time.Duration
IdleTimeout time.Duration
IdleCheckFrequency time.Duration
}
func (opt *ClusterOptions) init() {
if opt.MaxRedirects == -1 {
opt.MaxRedirects = 0
} else if opt.MaxRedirects == 0 {
opt.MaxRedirects = 16
}
if opt.RouteByLatency {
opt.ReadOnly = true
}
}
func (opt *ClusterOptions) clientOptions() *Options {
const disableIdleCheck = -1
return &Options{
OnConnect: opt.OnConnect,
MaxRetries: opt.MaxRetries,
Password: opt.Password,
ReadOnly: opt.ReadOnly,
DialTimeout: opt.DialTimeout,
ReadTimeout: opt.ReadTimeout,
WriteTimeout: opt.WriteTimeout,
PoolSize: opt.PoolSize,
PoolTimeout: opt.PoolTimeout,
IdleTimeout: opt.IdleTimeout,
IdleCheckFrequency: disableIdleCheck,
}
}
//------------------------------------------------------------------------------
type clusterNode struct {
Client *Client
Latency time.Duration
loading time.Time
}
func newClusterNode(clOpt *ClusterOptions, addr string) *clusterNode {
opt := clOpt.clientOptions()
opt.Addr = addr
node := clusterNode{
Client: NewClient(opt),
}
if clOpt.RouteByLatency {
node.updateLatency()
}
return &node
}
func (n *clusterNode) updateLatency() {
const probes = 10
for i := 0; i < probes; i++ {
start := time.Now()
n.Client.Ping()
n.Latency += time.Since(start)
}
n.Latency = n.Latency / probes
}
func (n *clusterNode) Loading() bool {
return !n.loading.IsZero() && time.Since(n.loading) < time.Minute
}
//------------------------------------------------------------------------------
type clusterNodes struct {
opt *ClusterOptions
mu sync.RWMutex
addrs []string
nodes map[string]*clusterNode
closed bool
}
func | (opt *ClusterOptions) *clusterNodes {
return &clusterNodes{
opt: opt,
nodes: make(map[string]*clusterNode),
}
}
func (c *clusterNodes) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return nil
}
c.closed = true
var firstErr error
for _, node := range c.nodes {
if err := node.Client.Close(); err != nil && firstErr == nil {
firstErr = err
}
}
c.addrs = nil
c.nodes = nil
return firstErr
}
func (c *clusterNodes) All() ([]*clusterNode, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if c.closed {
return nil, pool.ErrClosed
}
nodes := make([]*clusterNode, 0, len(c.nodes))
for _, node := range c.nodes {
nodes = append(nodes, node)
}
return nodes, nil
}
func (c *clusterNodes) Get(addr string) (*clusterNode, error) {
var node *clusterNode
var ok bool
c.mu.RLock()
if !c.closed {
node, ok = c.nodes[addr]
}
c.mu.RUnlock()
if ok {
return node, nil
}
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return nil, pool.ErrClosed
}
node, ok = c.nodes[addr]
if ok {
return node, nil
}
c.addrs = append(c.addrs, addr)
node = newClusterNode(c.opt, addr)
c.nodes[addr] = node
return node, nil
}
func (c *clusterNodes) Random() (*clusterNode, error) {
c.mu.RLock()
closed := c.closed
addrs := c.addrs
c.mu.RUnlock()
if closed {
return nil, pool.ErrClosed
}
if len(addrs) == 0 {
return nil, errClusterNoNodes
}
var nodeErr error
for i := 0; i <= c.opt.MaxRedirects; i++ {
n := rand.Intn(len(addrs))
node, err := c.Get(addrs[n])
if err != nil {
return nil, err
}
nodeErr = node.Client.ClusterInfo().Err()
if nodeErr == nil {
return node, nil
}
}
return nil, nodeErr
}
//------------------------------------------------------------------------------
type clusterState struct {
nodes *clusterNodes
slots [][]*clusterNode
}
func newClusterState(nodes *clusterNodes, slots []ClusterSlot, origin string) (*clusterState, error) {
c := clusterState{
nodes: nodes,
slots: make([][]*clusterNode, hashtag.SlotNumber),
}
isLoopbackOrigin := isLoopbackAddr(origin)
for _, slot := range slots {
var nodes []*clusterNode
for _, slotNode := range slot.Nodes {
addr := slotNode.Addr
if !isLoopbackOrigin && isLoopbackAddr(addr) {
addr = origin
}
node, err := c.nodes.Get(addr)
if err != nil {
return nil, err
}
nodes = append(nodes, node)
}
for i := slot.Start; i <= slot.End; i++ {
c.slots[i] = nodes
}
}
return &c, nil
}
func (c *clusterState) slotMasterNode(slot int) (*clusterNode, error) {
nodes := c.slotNodes(slot)
if len(nodes) > 0 {
return nodes[0], nil
}
return c.nodes.Random()
}
func (c *clusterState) slotSlaveNode(slot int) (*clusterNode, error) {
nodes := c.slotNodes(slot)
switch len(nodes) {
case 0:
return c.nodes.Random()
case 1:
return nodes[0], nil
case 2:
if slave := nodes[1]; !slave.Loading() {
return slave, nil
}
return nodes[0], nil
default:
var slave *clusterNode
for i := 0; i < 10; i++ {
n := rand.Intn(len(nodes)-1) + 1
slave = nodes[n]
if !slave.Loading() {
break
}
}
return slave, nil
}
}
func (c *clusterState) slotClosestNode(slot int) (*clusterNode, error) {
const threshold = time.Millisecond
nodes := c.slotNodes(slot)
if len(nodes) == 0 {
return c.nodes.Random()
}
var node *clusterNode
for _, n := range nodes {
if n.Loading() {
continue
}
if node == nil || node.Latency-n.Latency > threshold {
node = n
}
}
return node, nil
}
func (c *clusterState) slotNodes(slot int) []*clusterNode {
if slot < len(c.slots) {
return c.slots[slot]
}
return nil
}
//------------------------------------------------------------------------------
// ClusterClient is a Redis Cluster client representing a pool of zero
// or more underlying connections. It's safe for concurrent use by
// multiple goroutines.
type ClusterClient struct {
cmdable
opt *ClusterOptions
nodes *clusterNodes
_state atomic.Value
cmdsInfoOnce internal.Once
cmdsInfo map[string]*CommandInfo
// Reports where slots reloading is in progress.
reloading uint32
}
// NewClusterClient returns a Redis Cluster client as described in
// http://redis.io/topics/cluster-spec.
func NewClusterClient(opt *ClusterOptions) *ClusterClient {
opt.init()
c := &ClusterClient{
opt: opt,
nodes: newClusterNodes(opt),
}
c.setProcessor(c.Process)
// Add initial nodes.
for _, addr := range opt.Addrs {
_, _ = c.nodes.Get(addr)
}
// Preload cluster slots.
for i := 0; i < 10; i++ {
state, err := c.reloadSlots()
if err == nil {
c._state.Store(state)
break
}
}
if opt.IdleCheckFrequency > 0 {
go c.reaper(opt.IdleCheckFrequency)
}
return c
}
// Options returns read-only Options that were used to create the client.
func (c *ClusterClient) Options() *ClusterOptions {
return c.opt
}
func (c *ClusterClient) state() *clusterState {
v := c._state.Load()
if v != nil {
return v.(*clusterState)
}
c.lazyReloadSlots()
return nil
}
func (c *ClusterClient) cmdInfo(name string) *CommandInfo {
err := c.cmdsInfoOnce.Do(func() error {
node, err := c.nodes.Random()
if err != nil {
return err
}
cmdsInfo, err := node.Client.Command().Result()
if err != nil {
return err
}
c.cmdsInfo = cmdsInfo
return nil
})
if err != nil {
return nil
}
return c.cmdsInfo[name]
}
func (c *ClusterClient) cmdSlotAndNode(state *clusterState, cmd Cmder) (int, *clusterNode, error) {
if state == nil {
node, err := c.nodes.Random()
return 0, node, err
}
cmdInfo := c.cmdInfo(cmd.Name())
firstKey := cmd.arg(cmdFirstKeyPos(cmd, cmdInfo))
slot := hashtag.Slot(firstKey)
if cmdInfo != nil && cmdInfo.ReadOnly && c.opt.ReadOnly {
if c.opt.RouteByLatency {
node, err := state.slotClosestNode(slot)
return slot, node, err
}
node, err := state.slotSlaveNode(slot)
return slot, node, err
}
node, err := state.slotMasterNode(slot)
return slot, node, err
}
func (c *ClusterClient) Watch(fn func(*Tx) error, keys ...string) error {
state := c.state()
var node *clusterNode
var err error
if state != nil && len(keys) > 0 {
node, err = state.slotMasterNode(hashtag.Slot(keys[0]))
} else {
node, err = c.nodes.Random()
}
if err != nil {
return err
}
return node.Client.Watch(fn, keys...)
}
// Close closes the cluster client, releasing any open resources.
//
// It is rare to Close a ClusterClient, as the ClusterClient is meant
// to be long-lived and shared between many goroutines.
func (c *ClusterClient) Close() error {
return c.nodes.Close()
}
func (c *ClusterClient) Process(cmd Cmder) error {
slot, node, err := c.cmdSlotAndNode(c.state(), cmd)
if err != nil {
cmd.setErr(err)
return err
}
var ask bool
for attempt := 0; attempt <= c.opt.MaxRedirects; attempt++ {
if ask {
pipe := node.Client.Pipeline()
pipe.Process(NewCmd("ASKING"))
pipe.Process(cmd)
_, err = pipe.Exec()
pipe.Close()
ask = false
} else {
err = node.Client.Process(cmd)
}
// If there is no (real) error - we are done.
if err == nil {
return nil
}
// If slave is loading - read from master.
if c.opt.ReadOnly && internal.IsLoadingError(err) {
node.loading = time.Now()
continue
}
// On network errors try random node.
if internal.IsRetryableError(err) {
node, err = c.nodes.Random()
if err != nil {
cmd.setErr(err)
return err
}
continue
}
var moved bool
var addr string
moved, ask, addr = internal.IsMovedError(err)
if moved || ask {
state := c.state()
if state != nil && slot >= 0 {
master, _ := state.slotMasterNode(slot)
if moved && (master == nil || master.Client.getAddr() != addr) {
c.lazyReloadSlots()
}
}
node, err = c.nodes.Get(addr)
if err != nil {
cmd.setErr(err)
return err
}
continue
}
break
}
return cmd.Err()
}
// ForEachNode concurrently calls the fn on each ever known node in the cluster.
// It returns the first error if any.
func (c *ClusterClient) ForEachNode(fn func(client *Client) error) error {
nodes, err := c.nodes.All()
if err != nil {
return err
}
var wg sync.WaitGroup
errCh := make(chan error, 1)
for _, node := range nodes {
wg.Add(1)
go func(node *clusterNode) {
defer wg.Done()
err := fn(node.Client)
if err != nil {
select {
case errCh <- err:
default:
}
}
}(node)
}
wg.Wait()
select {
case err := <-errCh:
return err
default:
return nil
}
}
// ForEachMaster concurrently calls the fn on each master node in the cluster.
// It returns the first error if any.
func (c *ClusterClient) ForEachMaster(fn func(client *Client) error) error {
state := c.state()
if state == nil {
return errNilClusterState
}
var wg sync.WaitGroup
visited := make(map[*clusterNode]struct{})
errCh := make(chan error, 1)
for _, nodes := range state.slots {
if len(nodes) == 0 {
continue
}
master := nodes[0]
if _, ok := visited[master]; ok {
continue
}
visited[master] = struct{}{}
wg.Add(1)
go func(node *clusterNode) {
defer wg.Done()
err := fn(node.Client)
if err != nil {
select {
case errCh <- err:
default:
}
}
}(master)
}
wg.Wait()
select {
case err := <-errCh:
return err
default:
return nil
}
}
// PoolStats returns accumulated connection pool stats.
func (c *ClusterClient) PoolStats() *PoolStats {
var acc PoolStats
nodes, err := c.nodes.All()
if err != nil {
return &acc
}
for _, node := range nodes {
s := node.Client.connPool.Stats()
acc.Requests += s.Requests
acc.Hits += s.Hits
acc.Timeouts += s.Timeouts
acc.TotalConns += s.TotalConns
acc.FreeConns += s.FreeConns
}
return &acc
}
func (c *ClusterClient) lazyReloadSlots() {
if !atomic.CompareAndSwapUint32(&c.reloading, 0, 1) {
return
}
go func() {
for i := 0; i < 1000; i++ {
state, err := c.reloadSlots()
if err == pool.ErrClosed {
break
}
if err == nil {
c._state.Store(state)
break
}
time.Sleep(time.Millisecond)
}
time.Sleep(3 * time.Second)
atomic.StoreUint32(&c.reloading, 0)
}()
}
func (c *ClusterClient) reloadSlots() (*clusterState, error) {
node, err := c.nodes.Random()
if err != nil {
return nil, err
}
slots, err := node.Client.ClusterSlots().Result()
if err != nil {
return nil, err
}
return newClusterState(c.nodes, slots, node.Client.opt.Addr)
}
// reaper closes idle connections to the cluster.
func (c *ClusterClient) reaper(idleCheckFrequency time.Duration) {
ticker := time.NewTicker(idleCheckFrequency)
defer ticker.Stop()
for range ticker.C {
nodes, err := c.nodes.All()
if err != nil {
break
}
var n int
for _, node := range nodes {
nn, err := node.Client.connPool.(*pool.ConnPool).ReapStaleConns()
if err != nil {
internal.Logf("ReapStaleConns failed: %s", err)
} else {
n += nn
}
}
s := c.PoolStats()
internal.Logf(
"reaper: removed %d stale conns (TotalConns=%d FreeConns=%d Requests=%d Hits=%d Timeouts=%d)",
n, s.TotalConns, s.FreeConns, s.Requests, s.Hits, s.Timeouts,
)
}
}
func (c *ClusterClient) Pipeline() Pipeliner {
pipe := Pipeline{
exec: c.pipelineExec,
}
pipe.setProcessor(pipe.Process)
return &pipe
}
func (c *ClusterClient) Pipelined(fn func(Pipeliner) error) ([]Cmder, error) {
return c.Pipeline().pipelined(fn)
}
func (c *ClusterClient) pipelineExec(cmds []Cmder) error {
cmdsMap, err := c.mapCmdsByNode(cmds)
if err != nil {
return err
}
for i := 0; i <= c.opt.MaxRedirects; i++ {
failedCmds := make(map[*clusterNode][]Cmder)
for node, cmds := range cmdsMap {
cn, _, err := node.Client.conn()
if err != nil {
setCmdsErr(cmds, err)
continue
}
err = c.pipelineProcessCmds(cn, cmds, failedCmds)
node.Client.putConn(cn, err)
}
if len(failedCmds) == 0 {
break
}
cmdsMap = failedCmds
}
var firstErr error
for _, cmd := range cmds {
if err := cmd.Err(); err != nil {
firstErr = err
break
}
}
return firstErr
}
func (c *ClusterClient) mapCmdsByNode(cmds []Cmder) (map[*clusterNode][]Cmder, error) {
state := c.state()
cmdsMap := make(map[*clusterNode][]Cmder)
for _, cmd := range cmds {
_, node, err := c.cmdSlotAndNode(state, cmd)
if err != nil {
return nil, err
}
cmdsMap[node] = append(cmdsMap[node], cmd)
}
return cmdsMap, nil
}
func (c *ClusterClient) pipelineProcessCmds(
cn *pool.Conn, cmds []Cmder, failedCmds map[*clusterNode][]Cmder,
) error {
cn.SetWriteTimeout(c.opt.WriteTimeout)
if err := writeCmd(cn, cmds...); err != nil {
setCmdsErr(cmds, err)
return err
}
// Set read timeout for all commands.
cn.SetReadTimeout(c.opt.ReadTimeout)
return c.pipelineReadCmds(cn, cmds, failedCmds)
}
func (c *ClusterClient) pipelineReadCmds(
cn *pool.Conn, cmds []Cmder, failedCmds map[*clusterNode][]Cmder,
) error {
var firstErr error
for _, cmd := range cmds {
err := cmd.readReply(cn)
if err == nil {
continue
}
if firstErr == nil {
firstErr = err
}
err = c.checkMovedErr(cmd, failedCmds)
if err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}
func (c *ClusterClient) checkMovedErr(cmd Cmder, failedCmds map[*clusterNode][]Cmder) error {
moved, ask, addr := internal.IsMovedError(cmd.Err())
if moved {
c.lazyReloadSlots()
node, err := c.nodes.Get(addr)
if err != nil {
return err
}
failedCmds[node] = append(failedCmds[node], cmd)
}
if ask {
node, err := c.nodes.Get(addr)
if err != nil {
return err
}
failedCmds[node] = append(failedCmds[node], NewCmd("ASKING"), cmd)
}
return nil
}
// TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
func (c *ClusterClient) TxPipeline() Pipeliner {
pipe := Pipeline{
exec: c.txPipelineExec,
}
pipe.setProcessor(pipe.Process)
return &pipe
}
func (c *ClusterClient) TxPipelined(fn func(Pipeliner) error) ([]Cmder, error) {
return c.TxPipeline().pipelined(fn)
}
func (c *ClusterClient) txPipelineExec(cmds []Cmder) error {
cmdsMap, err := c.mapCmdsBySlot(cmds)
if err != nil {
return err
}
state := c.state()
if state == nil {
return errNilClusterState
}
for slot, cmds := range cmdsMap {
node, err := state.slotMasterNode(slot)
if err != nil {
setCmdsErr(cmds, err)
continue
}
cmdsMap := map[*clusterNode][]Cmder{node: cmds}
for i := 0; i <= c.opt.MaxRedirects; i++ {
failedCmds := make(map[*clusterNode][]Cmder)
for node, cmds := range cmdsMap {
cn, _, err := node.Client.conn()
if err != nil {
setCmdsErr(cmds, err)
continue
}
err = c.txPipelineProcessCmds(node, cn, cmds, failedCmds)
node.Client.putConn(cn, err)
}
if len(failedCmds) == 0 {
break
}
cmdsMap = failedCmds
}
}
var firstErr error
for _, cmd := range cmds {
if err := cmd.Err(); err != nil {
firstErr = err
break
}
}
return firstErr
}
func (c *ClusterClient) mapCmdsBySlot(cmds []Cmder) (map[int][]Cmder, error) {
state := c.state()
cmdsMap := make(map[int][]Cmder)
for _, cmd := range cmds {
slot, _, err := c.cmdSlotAndNode(state, cmd)
if err != nil {
return nil, err
}
cmdsMap[slot] = append(cmdsMap[slot], cmd)
}
return cmdsMap, nil
}
func (c *ClusterClient) txPipelineProcessCmds(
node *clusterNode, cn *pool.Conn, cmds []Cmder, failedCmds map[*clusterNode][]Cmder,
) error {
cn.SetWriteTimeout(c.opt.WriteTimeout)
if err := txPipelineWriteMulti(cn, cmds); err != nil {
setCmdsErr(cmds, err)
failedCmds[node] = cmds
return err
}
// Set read timeout for all commands.
cn.SetReadTimeout(c.opt.ReadTimeout)
if err := c.txPipelineReadQueued(cn, cmds, failedCmds); err != nil {
return err
}
_, err := pipelineReadCmds(cn, cmds)
return err
}
func (c *ClusterClient) txPipelineReadQueued(
cn *pool.Conn, cmds []Cmder, failedCmds map[*clusterNode][]Cmder,
) error {
var firstErr error
// Parse queued replies.
var statusCmd StatusCmd
if err := statusCmd.readReply(cn); err != nil && firstErr == nil {
firstErr = err
}
for _, cmd := range cmds {
err := statusCmd.readReply(cn)
if err == nil {
continue
}
cmd.setErr(err)
if firstErr == nil {
firstErr = err
}
err = c.checkMovedErr(cmd, failedCmds)
if err != nil && firstErr == nil {
firstErr = err
}
}
// Parse number of replies.
line, err := cn.Rd.ReadLine()
if err != nil {
if err == Nil {
err = TxFailedErr
}
return err
}
switch line[0] {
case proto.ErrorReply:
return proto.ParseErrorReply(line)
case proto.ArrayReply:
// ok
default:
err := fmt.Errorf("redis: expected '*', but got line %q", line)
return err
}
return firstErr
}
func isLoopbackAddr(addr string) bool {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return false
}
ip := net.ParseIP(host)
if ip == nil {
return false
}
return ip.IsLoopback()
}
| newClusterNodes |
test_series_actors_data.py | # coding: utf-8
"""
TheTVDB API v2
API v3 targets v2 functionality with a few minor additions. The API is accessible via https://api.thetvdb.com and provides the following REST endpoints in JSON format. How to use this API documentation ---------------- You may browse the API routes without authentication, but if you wish to send requests to the API and see response data, then you must authenticate. 1. Obtain a JWT token by `POST`ing to the `/login` route in the `Authentication` section with your API key and credentials. 1. Paste the JWT token from the response into the \"JWT Token\" field at the top of the page and click the 'Add Token' button. You will now be able to use the remaining routes to send requests to the API and get a response. Language Selection ---------------- Language selection is done via the `Accept-Language` header. At the moment, you may only pass one language abbreviation in the header at a time. Valid language abbreviations can be found at the `/languages` route.. Authentication ---------------- Authentication to use the API is similar to the How-to section above. Users must `POST` to the `/login` route with their API key and credentials in the following format in order to obtain a JWT token. `{\"apikey\":\"APIKEY\",\"username\":\"USERNAME\",\"userkey\":\"USERKEY\"}` Note that the username and key are ONLY required for the `/user` routes. The user's key is labled `Account Identifier` in the account section of the main site. The token is then used in all subsequent requests by providing it in the `Authorization` header. The header will look like: `Authorization: Bearer <yourJWTtoken>`. Currently, the token expires after 24 hours. You can `GET` the `/refresh_token` route to extend that expiration date. Versioning ---------------- You may request a different version of the API by including an `Accept` header in your request with the following format: `Accept:application/vnd.thetvdb.v$VERSION`. This documentation automatically uses the version seen at the top and bottom of the page. # noqa: E501
OpenAPI spec version: 3.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import tvdb_api
from tvdb_api.models.series_actors_data import SeriesActorsData # noqa: E501
from tvdb_api.rest import ApiException
class TestSeriesActorsData(unittest.TestCase):
"""SeriesActorsData unit test stubs"""
def setUp(self):
|
def tearDown(self):
pass
def testSeriesActorsData(self):
"""Test SeriesActorsData"""
# FIXME: construct object with mandatory attributes with example values
# model = tvdb_api.models.series_actors_data.SeriesActorsData() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| pass |
codegen.py | """Generate langauge specific loaders for a particular SALAD schema."""
import sys
from io import TextIOWrapper
from typing import (
Any,
Dict,
List,
MutableMapping,
MutableSequence,
Optional,
TextIO,
Union,
)
from . import schema
from .codegen_base import CodeGenBase
from .exceptions import SchemaSaladException
from .java_codegen import JavaCodeGen
from .python_codegen import PythonCodeGen
from .ref_resolver import Loader
from .schema import shortname
from .utils import aslist
FIELD_SORT_ORDER = ["id", "class", "name"]
def | (
lang: str,
i: List[Dict[str, str]],
schema_metadata: Dict[str, Any],
loader: Loader,
target: Optional[str] = None,
examples: Optional[str] = None,
package: Optional[str] = None,
copyright: Optional[str] = None,
) -> None:
"""Generate classes with loaders for the given Schema Salad description."""
j = schema.extend_and_specialize(i, loader)
gen = None # type: Optional[CodeGenBase]
if lang == "python":
if target:
dest: Union[TextIOWrapper, TextIO] = open(
target, mode="w", encoding="utf-8"
)
else:
dest = sys.stdout
gen = PythonCodeGen(dest, copyright=copyright)
elif lang == "java":
gen = JavaCodeGen(
schema_metadata.get("$base", schema_metadata.get("id")),
target=target,
examples=examples,
package=package,
copyright=copyright,
)
else:
raise SchemaSaladException(f"Unsupported code generation language '{lang}'")
gen.prologue()
document_roots = []
for rec in j:
if rec["type"] in ("enum", "record"):
gen.type_loader(rec)
gen.add_vocab(shortname(rec["name"]), rec["name"])
for rec in j:
if rec["type"] == "enum":
for symbol in rec["symbols"]:
gen.add_vocab(shortname(symbol), symbol)
if rec["type"] == "record":
if rec.get("documentRoot"):
document_roots.append(rec["name"])
field_names = []
optional_fields = set()
for field in rec.get("fields", []):
field_name = shortname(field["name"])
field_names.append(field_name)
tp = field["type"]
if (
isinstance(tp, MutableSequence)
and tp[0] == "https://w3id.org/cwl/salad#null"
):
optional_fields.add(field_name)
idfield = ""
for field in rec.get("fields", []):
if field.get("jsonldPredicate") == "@id":
idfield = field.get("name")
gen.begin_class(
rec["name"],
aslist(rec.get("extends", [])),
rec.get("doc", ""),
rec.get("abstract", False),
field_names,
idfield,
optional_fields,
)
gen.add_vocab(shortname(rec["name"]), rec["name"])
sorted_fields = sorted(
rec.get("fields", []),
key=lambda i: FIELD_SORT_ORDER.index(i["name"].split("/")[-1])
if i["name"].split("/")[-1] in FIELD_SORT_ORDER
else 100,
)
for field in sorted_fields:
if field.get("jsonldPredicate") == "@id":
subscope = field.get("subscope")
fieldpred = field["name"]
optional = bool("https://w3id.org/cwl/salad#null" in field["type"])
uri_loader = gen.uri_loader(
gen.type_loader(field["type"]), True, False, None
)
gen.declare_id_field(
fieldpred, uri_loader, field.get("doc"), optional, subscope
)
break
for field in sorted_fields:
optional = bool("https://w3id.org/cwl/salad#null" in field["type"])
type_loader = gen.type_loader(field["type"])
jld = field.get("jsonldPredicate")
fieldpred = field["name"]
subscope = None
if isinstance(jld, MutableMapping):
ref_scope = jld.get("refScope")
if jld.get("typeDSL"):
type_loader = gen.typedsl_loader(type_loader, ref_scope)
elif jld.get("secondaryFilesDSL"):
type_loader = gen.secondaryfilesdsl_loader(type_loader)
elif jld.get("subscope"):
subscope = jld.get("subscope")
elif jld.get("_type") == "@id":
type_loader = gen.uri_loader(
type_loader, jld.get("identity", False), False, ref_scope
)
elif jld.get("_type") == "@vocab":
type_loader = gen.uri_loader(
type_loader, False, True, ref_scope
)
map_subject = jld.get("mapSubject")
if map_subject:
type_loader = gen.idmap_loader(
field["name"],
type_loader,
map_subject,
jld.get("mapPredicate"),
)
if "_id" in jld and jld["_id"][0] != "@":
fieldpred = jld["_id"]
if jld == "@id":
continue
gen.declare_field(fieldpred, type_loader, field.get("doc"), optional)
gen.end_class(rec["name"], field_names)
root_type = list(document_roots)
root_type.append({"type": "array", "items": document_roots})
gen.epilogue(gen.type_loader(root_type))
| codegen |
PRESUBMIT.py | # Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
import json
import os
import re
import subprocess
import sys
# Directories that will be scanned by cpplint by the presubmit script.
CPPLINT_DIRS = [
'webrtc/api',
'webrtc/audio',
'webrtc/call',
'webrtc/common_video',
'webrtc/examples',
'webrtc/modules/audio_mixer',
'webrtc/modules/bitrate_controller',
'webrtc/modules/congestion_controller',
'webrtc/modules/pacing',
'webrtc/modules/remote_bitrate_estimator',
'webrtc/modules/rtp_rtcp',
'webrtc/modules/video_coding',
'webrtc/modules/video_processing',
'webrtc/tools',
'webrtc/video',
]
# These filters will always be removed, even if the caller specifies a filter
# set, as they are problematic or broken in some way.
#
# Justifications for each filter:
# - build/c++11 : Rvalue ref checks are unreliable (false positives),
# include file and feature blacklists are
# google3-specific.
# - whitespace/operators: Same as above (doesn't seem sufficient to eliminate
# all move-related errors).
BLACKLIST_LINT_FILTERS = [
'-build/c++11',
'-whitespace/operators',
]
# List of directories of "supported" native APIs. That means changes to headers
# will be done in a compatible way following this scheme:
# 1. Non-breaking changes are made.
# 2. The old APIs as marked as deprecated (with comments).
# 3. Deprecation is announced to [email protected] and
# [email protected] (internal list).
# 4. (later) The deprecated APIs are removed.
NATIVE_API_DIRS = (
'webrtc',
'webrtc/api',
'webrtc/media',
'webrtc/modules/audio_device/include',
'webrtc/pc',
)
# These directories should not be used but are maintained only to avoid breaking
# some legacy downstream code.
LEGACY_API_DIRS = (
'webrtc/base',
'webrtc/common_audio/include',
'webrtc/modules/audio_coding/include',
'webrtc/modules/audio_conference_mixer/include',
'webrtc/modules/audio_processing/include',
'webrtc/modules/bitrate_controller/include',
'webrtc/modules/congestion_controller/include',
'webrtc/modules/include',
'webrtc/modules/remote_bitrate_estimator/include',
'webrtc/modules/rtp_rtcp/include',
'webrtc/modules/rtp_rtcp/source',
'webrtc/modules/utility/include',
'webrtc/modules/video_coding/codecs/h264/include',
'webrtc/modules/video_coding/codecs/i420/include',
'webrtc/modules/video_coding/codecs/vp8/include',
'webrtc/modules/video_coding/codecs/vp9/include',
'webrtc/modules/video_coding/include',
'webrtc/system_wrappers/include',
'webrtc/voice_engine/include',
)
API_DIRS = NATIVE_API_DIRS[:] + LEGACY_API_DIRS[:]
def _RunCommand(command, cwd):
"""Runs a command and returns the output from that command."""
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=cwd)
stdout = p.stdout.read()
stderr = p.stderr.read()
p.wait()
p.stdout.close()
p.stderr.close()
return p.returncode, stdout, stderr
def _VerifyNativeApiHeadersListIsValid(input_api, output_api):
"""Ensures the list of native API header directories is up to date."""
non_existing_paths = []
native_api_full_paths = [
input_api.os_path.join(input_api.PresubmitLocalPath(),
*path.split('/')) for path in API_DIRS]
for path in native_api_full_paths:
if not os.path.isdir(path):
non_existing_paths.append(path)
if non_existing_paths:
return [output_api.PresubmitError(
'Directories to native API headers have changed which has made the '
'list in PRESUBMIT.py outdated.\nPlease update it to the current '
'location of our native APIs.',
non_existing_paths)]
return []
api_change_msg = """
You seem to be changing native API header files. Please make sure that you:
1. Make compatible changes that don't break existing clients. Usually
this is done by keeping the existing method signatures unchanged.
2. Mark the old stuff as deprecated (see RTC_DEPRECATED macro).
3. Create a timeline and plan for when the deprecated stuff will be
removed. (The amount of time we give users to change their code
should be informed by how much work it is for them. If they just
need to replace one name with another or something equally
simple, 1-2 weeks might be good; if they need to do serious work,
up to 3 months may be called for.)
4. Update/inform existing downstream code owners to stop using the
deprecated stuff. (Send announcements to
[email protected] and [email protected].)
5. Remove the deprecated stuff, once the agreed-upon amount of time
has passed.
Related files:
"""
def _CheckNativeApiHeaderChanges(input_api, output_api):
"""Checks to remind proper changing of native APIs."""
files = []
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if f.LocalPath().endswith('.h'):
for path in API_DIRS:
if os.path.dirname(f.LocalPath()) == path:
files.append(f)
if files:
return [output_api.PresubmitNotifyResult(api_change_msg, files)]
return []
def _CheckNoIOStreamInHeaders(input_api, output_api):
"""Checks to make sure no .h files include <iostream>."""
files = []
pattern = input_api.re.compile(r'^#include\s*<iostream>',
input_api.re.MULTILINE)
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if not f.LocalPath().endswith('.h'):
continue
contents = input_api.ReadFile(f)
if pattern.search(contents):
files.append(f)
if len(files):
return [output_api.PresubmitError(
'Do not #include <iostream> in header files, since it inserts static ' +
'initialization into every file including the header. Instead, ' +
'#include <ostream>. See http://crbug.com/94794',
files)]
return []
def _CheckNoPragmaOnce(input_api, output_api):
"""Make sure that banned functions are not used."""
files = []
pattern = input_api.re.compile(r'^#pragma\s+once',
input_api.re.MULTILINE)
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if not f.LocalPath().endswith('.h'):
continue
contents = input_api.ReadFile(f)
if pattern.search(contents):
files.append(f)
if files:
return [output_api.PresubmitError(
'Do not use #pragma once in header files.\n'
'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
files)]
return []
def _CheckNoFRIEND_TEST(input_api, output_api):
"""Make sure that gtest's FRIEND_TEST() macro is not used, the
FRIEND_TEST_ALL_PREFIXES() macro from testsupport/gtest_prod_util.h should be
used instead since that allows for FLAKY_, FAILS_ and DISABLED_ prefixes."""
problems = []
file_filter = lambda f: f.LocalPath().endswith(('.cc', '.h'))
for f in input_api.AffectedFiles(file_filter=file_filter):
for line_num, line in f.ChangedContents():
if 'FRIEND_TEST(' in line:
problems.append(' %s:%d' % (f.LocalPath(), line_num))
if not problems:
return []
return [output_api.PresubmitPromptWarning('WebRTC\'s code should not use '
'gtest\'s FRIEND_TEST() macro. Include testsupport/gtest_prod_util.h and '
'use FRIEND_TEST_ALL_PREFIXES() instead.\n' + '\n'.join(problems))]
def _IsLintWhitelisted(whitelist_dirs, file_path):
""" Checks if a file is whitelisted for lint check."""
for path in whitelist_dirs:
if os.path.dirname(file_path).startswith(path):
return True
return False
def _CheckApprovedFilesLintClean(input_api, output_api,
source_file_filter=None):
"""Checks that all new or whitelisted .cc and .h files pass cpplint.py.
This check is based on _CheckChangeLintsClean in
depot_tools/presubmit_canned_checks.py but has less filters and only checks
added files."""
result = []
# Initialize cpplint.
import cpplint
# Access to a protected member _XX of a client class
# pylint: disable=W0212
cpplint._cpplint_state.ResetErrorCounts()
lint_filters = cpplint._Filters()
lint_filters.extend(BLACKLIST_LINT_FILTERS)
cpplint._SetFilters(','.join(lint_filters))
# Create a platform independent whitelist for the CPPLINT_DIRS.
whitelist_dirs = [input_api.os_path.join(*path.split('/'))
for path in CPPLINT_DIRS]
# Use the strictest verbosity level for cpplint.py (level 1) which is the
# default when running cpplint.py from command line.
# To make it possible to work with not-yet-converted code, we're only applying
# it to new (or moved/renamed) files and files listed in LINT_FOLDERS.
verbosity_level = 1
files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
# Note that moved/renamed files also count as added.
if f.Action() == 'A' or _IsLintWhitelisted(whitelist_dirs, f.LocalPath()):
files.append(f.AbsoluteLocalPath())
for file_name in files:
cpplint.ProcessFile(file_name, verbosity_level)
if cpplint._cpplint_state.error_count > 0:
if input_api.is_committing:
# TODO(kjellander): Change back to PresubmitError below when we're
# confident with the lint settings.
res_type = output_api.PresubmitPromptWarning
else:
res_type = output_api.PresubmitPromptWarning
result = [res_type('Changelist failed cpplint.py check.')]
return result
def _CheckNoSourcesAbove(input_api, gn_files, output_api):
# Disallow referencing source files with paths above the GN file location.
source_pattern = input_api.re.compile(r' +sources \+?= \[(.*?)\]',
re.MULTILINE | re.DOTALL)
file_pattern = input_api.re.compile(r'"((\.\./.*?)|(//.*?))"')
violating_gn_files = set()
violating_source_entries = []
for gn_file in gn_files:
contents = input_api.ReadFile(gn_file)
for source_block_match in source_pattern.finditer(contents):
# Find all source list entries starting with ../ in the source block
# (exclude overrides entries).
for file_list_match in file_pattern.finditer(source_block_match.group(1)):
source_file = file_list_match.group(1)
if 'overrides/' not in source_file:
violating_source_entries.append(source_file)
violating_gn_files.add(gn_file)
if violating_gn_files:
return [output_api.PresubmitError(
'Referencing source files above the directory of the GN file is not '
'allowed. Please introduce new GN targets in the proper location '
'instead.\n'
'Invalid source entries:\n'
'%s\n'
'Violating GN files:' % '\n'.join(violating_source_entries),
items=violating_gn_files)]
return []
def _CheckNoMixingCAndCCSources(input_api, gn_files, output_api):
# Disallow mixing .c and .cc source files in the same target.
source_pattern = input_api.re.compile(r' +sources \+?= \[(.*?)\]',
re.MULTILINE | re.DOTALL)
file_pattern = input_api.re.compile(r'"(.*)"')
violating_gn_files = dict()
for gn_file in gn_files:
contents = input_api.ReadFile(gn_file)
for source_block_match in source_pattern.finditer(contents):
c_files = []
cc_files = []
for file_list_match in file_pattern.finditer(source_block_match.group(1)):
source_file = file_list_match.group(1)
if source_file.endswith('.c'):
c_files.append(source_file)
if source_file.endswith('.cc'):
cc_files.append(source_file)
if c_files and cc_files:
violating_gn_files[gn_file.LocalPath()] = sorted(c_files + cc_files)
if violating_gn_files:
return [output_api.PresubmitError(
'GN targets cannot mix .cc and .c source files. Please create a '
'separate target for each collection of sources.\n'
'Mixed sources: \n'
'%s\n'
'Violating GN files:' % json.dumps(violating_gn_files, indent=2),
items=violating_gn_files.keys())]
return []
def _CheckNoPackageBoundaryViolations(input_api, gn_files, output_api):
cwd = input_api.PresubmitLocalPath()
script_path = os.path.join('tools-webrtc', 'check_package_boundaries.py')
webrtc_path = os.path.join('webrtc')
command = [sys.executable, script_path, webrtc_path]
command += [gn_file.LocalPath() for gn_file in gn_files]
returncode, _, stderr = _RunCommand(command, cwd)
if returncode:
return [output_api.PresubmitError(
'There are package boundary violations in the following GN files:\n\n'
'%s' % stderr)]
return []
def _CheckGnChanges(input_api, output_api):
source_file_filter = lambda x: input_api.FilterSourceFile(
x, white_list=(r'.+\.(gn|gni)$',))
gn_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
if f.LocalPath().startswith('webrtc'):
gn_files.append(f)
result = []
if gn_files:
result.extend(_CheckNoSourcesAbove(input_api, gn_files, output_api))
result.extend(_CheckNoMixingCAndCCSources(input_api, gn_files, output_api))
result.extend(_CheckNoPackageBoundaryViolations(
input_api, gn_files, output_api))
return result
def _CheckUnwantedDependencies(input_api, output_api):
"""Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning.
"""
# Copied from Chromium's src/PRESUBMIT.py.
# We need to wait until we have an input_api object and use this
# roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__.
original_sys_path = sys.path
try:
checkdeps_path = input_api.os_path.join(input_api.PresubmitLocalPath(),
'buildtools', 'checkdeps')
if not os.path.exists(checkdeps_path):
return [output_api.PresubmitError(
'Cannot find checkdeps at %s\nHave you run "gclient sync" to '
'download Chromium and setup the symlinks?' % checkdeps_path)]
sys.path.append(checkdeps_path)
import checkdeps
from cpp_checker import CppChecker
from rules import Rule
finally:
# Restore sys.path to what it was before. | added_includes = []
for f in input_api.AffectedFiles():
if not CppChecker.IsCppFile(f.LocalPath()):
continue
changed_lines = [line for _, line in f.ChangedContents()]
added_includes.append([f.LocalPath(), changed_lines])
deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
error_descriptions = []
warning_descriptions = []
for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
added_includes):
description_with_path = '%s\n %s' % (path, rule_description)
if rule_type == Rule.DISALLOW:
error_descriptions.append(description_with_path)
else:
warning_descriptions.append(description_with_path)
results = []
if error_descriptions:
results.append(output_api.PresubmitError(
'You added one or more #includes that violate checkdeps rules.',
error_descriptions))
if warning_descriptions:
results.append(output_api.PresubmitPromptOrNotify(
'You added one or more #includes of files that are temporarily\n'
'allowed but being removed. Can you avoid introducing the\n'
'#include? See relevant DEPS file(s) for details and contacts.',
warning_descriptions))
return results
def _CheckChangeHasBugField(input_api, output_api):
"""Requires that the changelist have a BUG= field.
This check is stricter than the one in depot_tools/presubmit_canned_checks.py
since it fails the presubmit if the BUG= field is missing or doesn't contain
a bug reference.
"""
if input_api.change.BUG:
return []
else:
return [output_api.PresubmitError(
'The BUG=[bug number] field is mandatory. Please create a bug and '
'reference it using either of:\n'
' * https://bugs.webrtc.org - reference it using BUG=webrtc:XXXX\n'
' * https://crbug.com - reference it using BUG=chromium:XXXXXX')]
def _CheckJSONParseErrors(input_api, output_api):
"""Check that JSON files do not contain syntax errors."""
def FilterFile(affected_file):
return input_api.os_path.splitext(affected_file.LocalPath())[1] == '.json'
def GetJSONParseError(input_api, filename):
try:
contents = input_api.ReadFile(filename)
input_api.json.loads(contents)
except ValueError as e:
return e
return None
results = []
for affected_file in input_api.AffectedFiles(
file_filter=FilterFile, include_deletes=False):
parse_error = GetJSONParseError(input_api,
affected_file.AbsoluteLocalPath())
if parse_error:
results.append(output_api.PresubmitError('%s could not be parsed: %s' %
(affected_file.LocalPath(), parse_error)))
return results
def _RunPythonTests(input_api, output_api):
def join(*args):
return input_api.os_path.join(input_api.PresubmitLocalPath(), *args)
test_directories = [
join('webrtc', 'tools', 'py_event_log_analyzer')
] + [
root for root, _, files in os.walk(join('tools-webrtc'))
if any(f.endswith('_test.py') for f in files)
]
tests = []
for directory in test_directories:
tests.extend(
input_api.canned_checks.GetUnitTestsInDirectory(
input_api,
output_api,
directory,
whitelist=[r'.+_test\.py$']))
return input_api.RunTests(tests, parallel=True)
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
# Filter out files that are in objc or ios dirs from being cpplint-ed since
# they do not follow C++ lint rules.
black_list = input_api.DEFAULT_BLACK_LIST + (
r".*\bobjc[\\\/].*",
r".*objc\.[hcm]+$",
r"webrtc\/build\/ios\/SDK\/.*",
)
source_file_filter = lambda x: input_api.FilterSourceFile(x, None, black_list)
results.extend(_CheckApprovedFilesLintClean(
input_api, output_api, source_file_filter))
results.extend(input_api.canned_checks.RunPylint(input_api, output_api,
black_list=(r'^base[\\\/].*\.py$',
r'^build[\\\/].*\.py$',
r'^buildtools[\\\/].*\.py$',
r'^ios[\\\/].*\.py$',
r'^out.*[\\\/].*\.py$',
r'^testing[\\\/].*\.py$',
r'^third_party[\\\/].*\.py$',
r'^tools[\\\/].*\.py$',
# TODO(phoglund): should arguably be checked.
r'^tools-webrtc[\\\/]mb[\\\/].*\.py$',
r'^tools-webrtc[\\\/]valgrind[\\\/].*\.py$',
r'^xcodebuild.*[\\\/].*\.py$',),
disabled_warnings=['F0401', # Failed to import x
'E0611', # No package y in x
'W0232', # Class has no __init__ method
],
pylintrc='pylintrc'))
# TODO(nisse): talk/ is no more, so make below checks simpler?
# WebRTC can't use the presubmit_canned_checks.PanProjectChecks function since
# we need to have different license checks in talk/ and webrtc/ directories.
# Instead, hand-picked checks are included below.
# .m and .mm files are ObjC files. For simplicity we will consider .h files in
# ObjC subdirectories ObjC headers.
objc_filter_list = (r'.+\.m$', r'.+\.mm$', r'.+objc\/.+\.h$')
# Skip long-lines check for DEPS and GN files.
build_file_filter_list = (r'.+\.gn$', r'.+\.gni$', 'DEPS')
eighty_char_sources = lambda x: input_api.FilterSourceFile(x,
black_list=build_file_filter_list + objc_filter_list)
hundred_char_sources = lambda x: input_api.FilterSourceFile(x,
white_list=objc_filter_list)
results.extend(input_api.canned_checks.CheckLongLines(
input_api, output_api, maxlen=80, source_file_filter=eighty_char_sources))
results.extend(input_api.canned_checks.CheckLongLines(
input_api, output_api, maxlen=100,
source_file_filter=hundred_char_sources))
results.extend(input_api.canned_checks.CheckChangeHasNoTabs(
input_api, output_api))
results.extend(input_api.canned_checks.CheckChangeHasNoStrayWhitespace(
input_api, output_api))
results.extend(input_api.canned_checks.CheckAuthorizedAuthor(
input_api, output_api))
results.extend(input_api.canned_checks.CheckChangeTodoHasOwner(
input_api, output_api))
results.extend(_CheckNativeApiHeaderChanges(input_api, output_api))
results.extend(_CheckNoIOStreamInHeaders(input_api, output_api))
results.extend(_CheckNoPragmaOnce(input_api, output_api))
results.extend(_CheckNoFRIEND_TEST(input_api, output_api))
results.extend(_CheckGnChanges(input_api, output_api))
results.extend(_CheckUnwantedDependencies(input_api, output_api))
results.extend(_CheckJSONParseErrors(input_api, output_api))
results.extend(_RunPythonTests(input_api, output_api))
return results
def CheckChangeOnUpload(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(
input_api.canned_checks.CheckGNFormatted(input_api, output_api))
return results
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_VerifyNativeApiHeadersListIsValid(input_api, output_api))
results.extend(input_api.canned_checks.CheckOwners(input_api, output_api))
results.extend(input_api.canned_checks.CheckChangeWasUploaded(
input_api, output_api))
results.extend(input_api.canned_checks.CheckChangeHasDescription(
input_api, output_api))
results.extend(_CheckChangeHasBugField(input_api, output_api))
results.extend(input_api.canned_checks.CheckChangeHasTestField(
input_api, output_api))
results.extend(input_api.canned_checks.CheckTreeIsOpen(
input_api, output_api,
json_url='http://webrtc-status.appspot.com/current?format=json'))
return results | sys.path = original_sys_path
|
SpinBox.py | # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode
from ..SignalProxy import SignalProxy
from .. import functions as fn
from math import log
from decimal import Decimal as D ## Use decimal to avoid accumulating floating-point errors
from decimal import *
import weakref
__all__ = ['SpinBox']
class SpinBox(QtGui.QAbstractSpinBox):
"""
**Bases:** QtGui.QAbstractSpinBox
QSpinBox widget on steroids. Allows selection of numerical value, with extra features:
- SI prefix notation (eg, automatically display "300 mV" instead of "0.003 V")
- Float values with linear and decimal stepping (1-9, 10-90, 100-900, etc.)
- Option for unbounded values
- Delayed signals (allows multiple rapid changes with only one change signal)
============================= ==============================================
**Signals:**
valueChanged(value) Same as QSpinBox; emitted every time the value
has changed.
sigValueChanged(self) Emitted when value has changed, but also combines
multiple rapid changes into one signal (eg,
when rolling the mouse wheel).
sigValueChanging(self, value) Emitted immediately for all value changes.
============================= ==============================================
"""
## There's a PyQt bug that leaks a reference to the
## QLineEdit returned from QAbstractSpinBox.lineEdit()
## This makes it possible to crash the entire program
## by making accesses to the LineEdit after the spinBox has been deleted.
## I have no idea how to get around this..
valueChanged = QtCore.Signal(object) # (value) for compatibility with QSpinBox
sigValueChanged = QtCore.Signal(object) # (self)
sigValueChanging = QtCore.Signal(object, object) # (self, value) sent immediately; no delay.
def __init__(self, parent=None, value=0.0, **kwargs):
"""
============== ========================================================================
**Arguments:**
parent Sets the parent widget for this SpinBox (optional). Default is None.
value (float/int) initial value. Default is 0.0.
bounds (min,max) Minimum and maximum values allowed in the SpinBox.
Either may be None to leave the value unbounded. By default, values are unbounded.
suffix (str) suffix (units) to display after the numerical value. By default, suffix is an empty str.
siPrefix (bool) If True, then an SI prefix is automatically prepended
to the units and the value is scaled accordingly. For example,
if value=0.003 and suffix='V', then the SpinBox will display
"300 mV" (but a call to SpinBox.value will still return 0.003). Default is False.
step (float) The size of a single step. This is used when clicking the up/
down arrows, when rolling the mouse wheel, or when pressing
keyboard arrows while the widget has keyboard focus. Note that
the interpretation of this value is different when specifying
the 'dec' argument. Default is 0.01.
dec (bool) If True, then the step value will be adjusted to match
the current size of the variable (for example, a value of 15
might step in increments of 1 whereas a value of 1500 would
step in increments of 100). In this case, the 'step' argument
is interpreted *relative* to the current value. The most common
'step' values when dec=True are 0.1, 0.2, 0.5, and 1.0. Default is False.
minStep (float) When dec=True, this specifies the minimum allowable step size.
int (bool) if True, the value is forced to integer type. Default is False
precision (int) Number of significant digits to display. Default is 3.
============== ========================================================================
"""
QtGui.QAbstractSpinBox.__init__(self, parent)
self.lastValEmitted = None
self.lastText = ''
self.textValid = True ## If false, we draw a red border
self.setMinimumWidth(0)
self.setMaximumHeight(20)
self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
self.opts = {
'bounds': [None, None],
## Log scaling options #### Log mode is no longer supported.
#'step': 0.1,
#'minStep': 0.001,
#'log': True,
#'dec': False,
## decimal scaling option - example
#'step': 0.1,
#'minStep': .001,
#'log': False,
#'dec': True,
## normal arithmetic step
'step': D('0.01'), ## if 'dec' is false, the spinBox steps by 'step' every time
## if 'dec' is True, the step size is relative to the value
## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True)
'log': False,
'dec': False, ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc.
## if true, minStep must be set in order to cross zero.
'int': False, ## Set True to force value to be integer
'suffix': '',
'siPrefix': False, ## Set to True to display numbers with SI prefix (ie, 100pA instead of 1e-10A)
'delay': 0.3, ## delay sending wheel update signals for 300ms
'delayUntilEditFinished': True, ## do not send signals until text editing has finished
'precision': 3,
## for compatibility with QDoubleSpinBox and QSpinBox
'decimals': None,
}
self.decOpts = ['step', 'minStep']
self.val = D(asUnicode(value)) ## Value is precise decimal. Ordinary math not allowed.
self.updateText()
self.skipValidate = False
self.setCorrectionMode(self.CorrectToPreviousValue)
self.setKeyboardTracking(False)
self.setOpts(**kwargs)
self.editingFinished.connect(self.editingFinishedEvent)
self.proxy = SignalProxy(self.sigValueChanging, slot=self.delayedChange, delay=self.opts['delay'])
def event(self, ev):
ret = QtGui.QAbstractSpinBox.event(self, ev)
if ev.type() == QtCore.QEvent.KeyPress and ev.key() == QtCore.Qt.Key_Return:
ret = True ## For some reason, spinbox pretends to ignore return key press
return ret
##lots of config options, just gonna stuff 'em all in here rather than do the get/set crap.
def setOpts(self, **opts):
"""
Changes the behavior of the SpinBox. Accepts most of the arguments
allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`.
"""
#print opts
for k in opts:
if k == 'bounds':
#print opts[k]
self.setMinimum(opts[k][0], update=False)
self.setMaximum(opts[k][1], update=False)
#for i in [0,1]:
#if opts[k][i] is None:
#self.opts[k][i] = None
#else:
#self.opts[k][i] = D(unicode(opts[k][i]))
elif k in ['step', 'minStep']:
self.opts[k] = D(asUnicode(opts[k]))
elif k == 'value':
pass ## don't set value until bounds have been set
else:
self.opts[k] = opts[k]
if 'value' in opts:
self.setValue(opts['value'])
## If bounds have changed, update value to match
if 'bounds' in opts and 'value' not in opts:
self.setValue()
## sanity checks:
if self.opts['int']:
if 'step' in opts:
step = opts['step']
## not necessary..
#if int(step) != step:
#raise Exception('Integer SpinBox must have integer step size.')
else:
self.opts['step'] = int(self.opts['step'])
if 'minStep' in opts:
step = opts['minStep']
if int(step) != step:
raise Exception('Integer SpinBox must have integer minStep size.')
else:
ms = int(self.opts.get('minStep', 1))
if ms < 1:
ms = 1
self.opts['minStep'] = ms
if 'delay' in opts:
self.proxy.setDelay(opts['delay'])
self.updateText()
def setMaximum(self, m, update=True):
"""Set the maximum allowed value (or None for no limit)"""
if m is not None:
m = D(asUnicode(m))
self.opts['bounds'][1] = m
if update:
self.setValue()
def setMinimum(self, m, update=True):
"""Set the minimum allowed value (or None for no limit)"""
if m is not None:
m = D(asUnicode(m))
self.opts['bounds'][0] = m
if update:
self.setValue()
def setPrefix(self, p):
self.setOpts(prefix=p)
def setRange(self, r0, r1):
self.setOpts(bounds = [r0,r1])
def setProperty(self, prop, val):
## for QSpinBox compatibility
if prop == 'value':
#if type(val) is QtCore.QVariant:
#val = val.toDouble()[0]
self.setValue(val)
else:
print("Warning: SpinBox.setProperty('%s', ..) not supported." % prop)
def setSuffix(self, suf):
self.setOpts(suffix=suf)
def setSingleStep(self, step):
self.setOpts(step=step)
def setPrecision(self, p):
"""Set the number of significant digits to display.
"""
self.setOpts(precision=p)
def setDecimals(self, decimals):
# Note: non-functional for now; provided as workaround for uic files that set this property.
self.setOpts(decimals=decimals)
def selectNumber(self):
"""
Select the numerical portion of the text to allow quick editing by the user.
"""
le = self.lineEdit()
text = asUnicode(le.text())
if self.opts['suffix'] == '':
le.setSelection(0, len(text))
else:
try:
index = text.index(' ')
except ValueError:
return
le.setSelection(0, index)
def value(self):
"""
Return the value of this SpinBox.
"""
if self.opts['int']:
return int(self.val)
else:
return float(self.val)
def setValue(self, value=None, update=True, delaySignal=False):
"""
Set the value of this spin.
If the value is out of bounds, it will be clipped to the nearest boundary.
If the spin is integer type, the value will be coerced to int.
Returns the actual value set.
If value is None, then the current value is used (this is for resetting
the value after bounds, etc. have changed)
"""
if value is None:
value = self.value()
bounds = self.opts['bounds']
if bounds[0] is not None and value < bounds[0]:
value = bounds[0]
if bounds[1] is not None and value > bounds[1]:
value = bounds[1]
if self.opts['int']:
value = int(value)
value = D(asUnicode(value))
if value == self.val:
return
prev = self.val
self.val = value
if update:
self.updateText(prev=prev)
self.sigValueChanging.emit(self, float(self.val)) ## change will be emitted in 300ms if there are no subsequent changes.
if not delaySignal:
self.emitChanged()
return value
def emitChanged(self):
self.lastValEmitted = self.val
self.valueChanged.emit(float(self.val))
self.sigValueChanged.emit(self)
def delayedChange(self):
try:
if self.val != self.lastValEmitted:
self.emitChanged()
except RuntimeError:
pass ## This can happen if we try to handle a delayed signal after someone else has already deleted the underlying C++ object.
def widgetGroupInterface(self):
return (self.valueChanged, SpinBox.value, SpinBox.setValue)
def sizeHint(self):
return QtCore.QSize(120, 0) | def stepEnabled(self):
return self.StepUpEnabled | self.StepDownEnabled
#def fixup(self, *args):
#print "fixup:", args
def stepBy(self, n):
n = D(int(n)) ## n must be integral number of steps.
s = [D(-1), D(1)][n >= 0] ## determine sign of step
val = self.val
for i in range(int(abs(n))):
if self.opts['log']:
raise Exception("Log mode no longer supported.")
# step = abs(val) * self.opts['step']
# if 'minStep' in self.opts:
# step = max(step, self.opts['minStep'])
# val += step * s
if self.opts['dec']:
if val == 0:
step = self.opts['minStep']
exp = None
else:
vs = [D(-1), D(1)][val >= 0]
#exp = D(int(abs(val*(D('1.01')**(s*vs))).log10()))
fudge = D('1.01')**(s*vs) ## fudge factor. at some places, the step size depends on the step sign.
exp = abs(val * fudge).log10().quantize(1, ROUND_FLOOR)
step = self.opts['step'] * D(10)**exp
if 'minStep' in self.opts:
step = max(step, self.opts['minStep'])
val += s * step
#print "Exp:", exp, "step", step, "val", val
else:
val += s*self.opts['step']
if 'minStep' in self.opts and abs(val) < self.opts['minStep']:
val = D(0)
self.setValue(val, delaySignal=True) ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only.
def valueInRange(self, value):
bounds = self.opts['bounds']
if bounds[0] is not None and value < bounds[0]:
return False
if bounds[1] is not None and value > bounds[1]:
return False
if self.opts.get('int', False):
if int(value) != value:
return False
return True
def updateText(self, prev=None):
#print "Update text."
self.skipValidate = True
if self.opts['siPrefix']:
if self.val == 0 and prev is not None:
(s, p) = fn.siScale(prev)
txt = "0.0 %s%s" % (p, self.opts['suffix'])
else:
txt = fn.siFormat(float(self.val), suffix=self.opts['suffix'], precision=self.opts['precision'])
else:
txt = '%g%s' % (self.val , self.opts['suffix'])
self.lineEdit().setText(txt)
self.lastText = txt
self.skipValidate = False
def validate(self, strn, pos):
if self.skipValidate:
#print "skip validate"
#self.textValid = False
ret = QtGui.QValidator.Acceptable
else:
try:
## first make sure we didn't mess with the suffix
suff = self.opts.get('suffix', '')
if len(suff) > 0 and asUnicode(strn)[-len(suff):] != suff:
#print '"%s" != "%s"' % (unicode(strn)[-len(suff):], suff)
ret = QtGui.QValidator.Invalid
## next see if we actually have an interpretable value
else:
val = self.interpret()
if val is False:
#print "can't interpret"
#self.setStyleSheet('SpinBox {border: 2px solid #C55;}')
#self.textValid = False
ret = QtGui.QValidator.Intermediate
else:
if self.valueInRange(val):
if not self.opts['delayUntilEditFinished']:
self.setValue(val, update=False)
#print " OK:", self.val
#self.setStyleSheet('')
#self.textValid = True
ret = QtGui.QValidator.Acceptable
else:
ret = QtGui.QValidator.Intermediate
except:
#print " BAD"
#import sys
#sys.excepthook(*sys.exc_info())
#self.textValid = False
#self.setStyleSheet('SpinBox {border: 2px solid #C55;}')
ret = QtGui.QValidator.Intermediate
## draw / clear border
if ret == QtGui.QValidator.Intermediate:
self.textValid = False
elif ret == QtGui.QValidator.Acceptable:
self.textValid = True
## note: if text is invalid, we don't change the textValid flag
## since the text will be forced to its previous state anyway
self.update()
## support 2 different pyqt APIs. Bleh.
if hasattr(QtCore, 'QString'):
return (ret, pos)
else:
return (ret, strn, pos)
def paintEvent(self, ev):
QtGui.QAbstractSpinBox.paintEvent(self, ev)
## draw red border if text is invalid
if not self.textValid:
p = QtGui.QPainter(self)
p.setRenderHint(p.Antialiasing)
p.setPen(fn.mkPen((200,50,50), width=2))
p.drawRoundedRect(self.rect().adjusted(2, 2, -2, -2), 4, 4)
p.end()
def interpret(self):
"""Return value of text. Return False if text is invalid, raise exception if text is intermediate"""
strn = self.lineEdit().text()
suf = self.opts['suffix']
if len(suf) > 0:
if strn[-len(suf):] != suf:
return False
#raise Exception("Units are invalid.")
strn = strn[:-len(suf)]
try:
val = fn.siEval(strn)
except:
#sys.excepthook(*sys.exc_info())
#print "invalid"
return False
#print val
return val
#def interpretText(self, strn=None):
#print "Interpret:", strn
#if strn is None:
#strn = self.lineEdit().text()
#self.setValue(siEval(strn), update=False)
##QtGui.QAbstractSpinBox.interpretText(self)
def editingFinishedEvent(self):
"""Edit has finished; set value."""
#print "Edit finished."
if asUnicode(self.lineEdit().text()) == self.lastText:
#print "no text change."
return
try:
val = self.interpret()
except:
return
if val is False:
#print "value invalid:", str(self.lineEdit().text())
return
if val == self.val:
#print "no value change:", val, self.val
return
self.setValue(val, delaySignal=False) ## allow text update so that values are reformatted pretty-like
#def textChanged(self):
#print "Text changed."
### Drop-in replacement for SpinBox; just for crash-testing
#class SpinBox(QtGui.QDoubleSpinBox):
#valueChanged = QtCore.Signal(object) # (value) for compatibility with QSpinBox
#sigValueChanged = QtCore.Signal(object) # (self)
#sigValueChanging = QtCore.Signal(object) # (value)
#def __init__(self, parent=None, *args, **kargs):
#QtGui.QSpinBox.__init__(self, parent)
#def __getattr__(self, attr):
#return lambda *args, **kargs: None
#def widgetGroupInterface(self):
#return (self.valueChanged, SpinBox.value, SpinBox.setValue) | |
util.ts | export const identity = <T>(v: T): T => v; |
||
main.rs | use std::io::Read;
struct InterpreterState {
pc: u32,
call_stack: Vec<u32>,
stack: Vec<i32>,
}
fn main() -> std::io::Result<()> {
let args: Vec<_> = std::env::args().collect();
let bytecode = match args.len() {
1 => {
let mut buf = Vec::new();
std::io::stdin().read_to_end(&mut buf)?;
buf
}
2 => std::fs::read(&args[1])?,
_ => {
eprintln!("usage: {} <filename>?", args[0]);
std::process::exit(1);
}
};
let mut state = InterpreterState {
pc: 0,
call_stack: vec![],
stack: vec![],
};
let res = loop {
let inst_start = (state.pc * 5) as usize;
let opcode = bytecode[inst_start];
let immediate = i32::from_le_bytes([
bytecode[inst_start + 1],
bytecode[inst_start + 2],
bytecode[inst_start + 3],
bytecode[inst_start + 4],
]);
match opcode {
1 => state.stack.push(immediate),
2 => state.stack.push(*state.stack.last().unwrap()),
3 => {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
state.stack.push(left + right)
}
4 => {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
state.stack.push(left - right)
}
5 => {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
state.stack.push(left * right)
}
6 => {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
state.stack.push(left / right)
}
7 => |
8 => state.pc = (state.pc as i32 + immediate - 1) as u32,
9 => {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
if left == right {
state.pc = (state.pc as i32 + immediate - 1) as u32
}
}
10 => {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
if left != right {
state.pc = (state.pc as i32 + immediate - 1) as u32
}
}
11 => {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
if left < right {
state.pc = (state.pc as i32 + immediate - 1) as u32
}
}
12 => {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
if left > right {
state.pc = (state.pc as i32 + immediate - 1) as u32
}
}
13 => {
let immediate = state.stack.len() - (immediate as usize) - 1;
let tmp = state.stack[immediate as usize];
state.stack[immediate as usize] = state.stack[(immediate + 1) as usize];
state.stack[(immediate + 1) as usize] = tmp;
}
14 => {
state.call_stack.push(state.pc);
state.pc = (state.pc as i32 + immediate - 1) as u32
}
15 => {
state.pc = state.call_stack.pop().unwrap();
}
16 => {
state.stack.pop().unwrap();
}
17 => {
break state.stack.pop().unwrap();
}
_ => {
eprintln!("unrecognized opcode ({})", opcode);
std::process::exit(-1);
}
}
state.pc += 1;
};
println!("{}", res);
Ok(())
}
| {
let right = state.stack.pop().unwrap();
let left = state.stack.pop().unwrap();
state.stack.push(left % right)
} |
customers.service.ts | import { Injectable } from '@nestjs/common';
| @Injectable()
export class CustomersService {} |
|
settings.py | import os
import environ
environ.Env.read_env(os.path.join(os.path.dirname(__file__), '..', '..', 'test.env'))
from ..settings import *
INSTALLED_APPS.append('forsta_brand')
SOCIAL_AUTH_SAML_SP_PRIVATE_KEY = """\
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCkR4S26dW8j+yO
fxLFjdeUQbzL+QerKXkmQUiF8U9kvxAudt/aqvHFJ+gIo7/N5QuG/C1ptmT9NhB8
jLS6qyRiQzS0MHtPjmXO3m+ukR/VHxuoowxbqBYCjnytUg2BUX91hWTKqzKXKV31
Yfds7uGE9oQ3E3wGCCTOs9/1fnRVAmzq4gMCLAGH3b0Wjg3/Nijl4MaXwYqLElcb
zbo30RkdY2xdH2ZeTGEKotHx60ZCJF3ypYy2LNYBXMqIudMPA5v0VO5lhKGjJI0Y
fgQq06vrABlM866UCn6qxMvIoFjav0D+GRdEsSa2PDibjukA2fJFvC71XS9cz/Il
K6FyXnS/AgMBAAECggEACWZmO6kpp758hLLUuiUhnsQcL3eybqLS4dN+eNuT9WnR
XTdEG9kIOIXOCyCDix5+CF1Jo/Dh2nNLgjTy6nN8g3rg+yaDB8xYGvwzW8PGFIXR
KVcbD+uQRtksXSaCy1GEf48Ac3BUVr3xOGdApyUMFnWcnyIoSJgSsxkryXpQ4cRI
QcuJY3iz19I2aobseUjik6HKM7qhJIt1H1UAQqVp0KieMrBVqJd0BjmLcf/YlZRH
UPw8sgW6R1BNsZWLJHd2ZzpVkPiX6Op/kHtsY6QvJmTQcG2enuqJr1l9Oc0PGS+r
+zrmiCSVMAT5eea9WJbbER/9jxtcLpIVNwM6SPfXEQKBgQDY14UbvvrYbDMRoWpZ
UJHwKgBluXCZQYA1Rol+mu4njzUn3JO/gLm4+fqCQazQ+p9fBAM75b9hwD24XPTq
jqgcBLlhPLJEzDCDLvvAYpLIJM8KHlgk1uH31lYY32raHWt/2sYtcOsFQE2IQWlC
bS6hpgFbCBl6ToIup9N36QDOfQKBgQDB8hAXQN1gO1avgMo1SEkG3SpkCqH721jy
ieRHGxDJi9SBt2VDIglmAUI09YPG9y3TkJfTDJwgwuzCCJh8OtIWfC/Fu0+j3tgn
Mytevj9Vd40GodZy5rjNJvR2VrBzQQd9OCc9LYlrSLqRTJ2UDdpOTd/IHCtQ+067
589nX3EI6wKBgAjfuQjLpgRZWTWtf2asT2yeq2l+T0dWUOLdQh82Q+zGhYxeEIXT
xMX3JPNTsLjUqNUAmwlGe7CKZ3w2Aaffsq2C2/tIuprqKEoWECNtZUhfiUGGwGCx
konL8bYO3paSgaW31EhjyJpsaT/cPWyEf1YKLyAEktZYhCdYouTTWj8ZAoGBAJ+q
KQcLtnQfxbiMPWvqC3ykHN7pRfty0+IwFQdYx9Q00ojLs4i1/6jDRn8U1By7pzVx
5xuvWOU7s+/1ZZt4TTaHnEibcPAGaEq1PHIuCzPQTQB1wXcsbF0wQbcenPr1QTYc
QWmDEIuK/1TZDy0wzlUClUVHs31itqnJKB0BHKxrAoGADuM2aR0DTMu95qyObKhM
tuP1OmHX/9AYD/Pqs3iA2cfbqB28XmqXBIW73d+NTrQtWWH9jaghyqYIH9Y1Gfv4
sgGX3Be+bUNvcOjMGe43S+p/0aUNP4lw2W99PXZBV0rCXEf/ToyyqHLkb/lAXiv8
vzMKXId6qCc6Xd5ccVGFpvw=
-----END PRIVATE KEY-----
"""
SOCIAL_AUTH_SAML_SP_PUBLIC_CERT = """\
-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJALZeoXvHPXTjMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
BAYTAkdCMQ8wDQYDVQQHDAZPeGZvcmQxETAPBgNVBAoMCEFjbWUgT3JnMRIwEAYD
VQQDDAlsb2NhbGhvc3QwHhcNMTcwNDE2MTUwNTAzWhcNMjcwNDE2MTUwNTAzWjBF
MQswCQYDVQQGEwJHQjEPMA0GA1UEBwwGT3hmb3JkMREwDwYDVQQKDAhBY21lIE9y
ZzESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEApEeEtunVvI/sjn8SxY3XlEG8y/kHqyl5JkFIhfFPZL8QLnbf2qrxxSfo
CKO/zeULhvwtabZk/TYQfIy0uqskYkM0tDB7T45lzt5vrpEf1R8bqKMMW6gWAo58
rVINgVF/dYVkyqsylyld9WH3bO7hhPaENxN8BggkzrPf9X50VQJs6uIDAiwBh929
Fo4N/zYo5eDGl8GKixJXG826N9EZHWNsXR9mXkxhCqLR8etGQiRd8qWMtizWAVzK
iLnTDwOb9FTuZYShoySNGH4EKtOr6wAZTPOulAp+qsTLyKBY2r9A/hkXRLEmtjw4
m47pANnyRbwu9V0vXM/yJSuhcl50vwIDAQABo1AwTjAdBgNVHQ4EFgQU+x0bDoRy
JapiI34OxCoIxv3Lt+0wHwYDVR0jBBgwFoAU+x0bDoRyJapiI34OxCoIxv3Lt+0w
DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEADc+DT1jprMWBmuyatGhd
ZMAMc1oJGz/ZAZUkguNXaAufUf0hY8POlv7g8Mi13IY+au5Gv8UWGBd98dTXR0vr
QAe3v9qVzSsUhW5N0mhenI9Int3y8J+6d3dXKkrZ4Ihk/KqCqzXdoy3bs7bjDvvE
kHtVVoCgKJLZRqRye2xL7isvPG+kIP3alNRXz7gglq6Frn+rw8to3raa8vRPFQS7
HFWfKkrflAfLvoU9s9CePth4W7zFNF8IF/jOFvw45gzWUCx5UyhuMV3P5JLpQv1T
6IKyICbfpvICiyBx61o6KvvTsbcuPOKFGh/Lkku48cJKp4BaClKB8MMZKQXtoU5y
Gw==
-----END CERTIFICATE-----
"""
SOCIAL_AUTH_SAML_SP_ENTITY_ID = 'http://localhost/'
AUTHENTICATION_BACKENDS += (
'forsta_auth.tests.social_backends.DummyBackend',
)
|
ONBOARDING = {
'REGISTRATION_OPEN': True,
'REGISTRATION_OPEN_SOCIAL': True,
'REGISTRATION_OPEN_SAML': True,
}
MEDIA_URL = '/media/'
STATIC_URL = '/static/' | # PASSWORD_HASHERS.remove('forsta_auth.kerberos.hashers.KerberosHasher') |
broadcaster.test.ts | import { Broadcaster, EventPayload, Listener } from '../src/index'
let broadcaster: Broadcaster, listener: Listener, payload: EventPayload
beforeEach(() => {
payload = {
channel: 'test_channel',
topic: 'test_topic',
payload: {
propOne: 'one'
}
}
listener = jest.fn()
broadcaster = new Broadcaster('test')
})
describe('Broadcaster', () => {
describe('Initialize', () => {
test('with paramters', () => {
const name = 'test'
broadcaster = new Broadcaster(name)
expect(broadcaster.name).toBe(name)
expect(broadcaster.getEventEmitter().getMaxListeners()).toBe(0)
})
test('if the name is not provided, throw error', () => {
expect(() => {
broadcaster = new Broadcaster((undefined as unknown) as string)
}).toThrow('')
})
})
describe('Add listeners', () => {
test('addListener method', () => {
broadcaster.addListener(listener)
broadcaster.emit(payload)
expect(listener).toBeCalledWith(payload)
})
test('on method', () => {
broadcaster.on(listener)
broadcaster.emit(payload)
expect(listener).toBeCalledWith(payload)
})
test('once method', () => {
broadcaster.once(listener)
broadcaster.emit(payload)
broadcaster.emit(payload)
expect(listener).toBeCalledTimes(1)
})
test('prependListener method', () => {
const firstListener = jest.fn(() => {
throw new Error()
})
// add first listener (should throw if called first)
broadcaster.addListener(firstListener)
broadcaster.prependListener(() => {
// switch firstListener mock not to throw
// @ts-ignore
firstListener.mockImplementation(() => true)
})
expect(() => {
broadcaster.emit(payload)
}).not.toThrow()
expect(firstListener).toBeCalled()
})
describe('PrependOnceListener', () => {
test('whenever added listener should be called first', () => {
const firstListener = jest.fn(() => {
throw new Error()
})
// add first listener (should throw if called first)
broadcaster.addListener(firstListener)
broadcaster.prependOnceListener(() => {
// switch firstListener mock not to throw
// @ts-ignore
firstListener.mockImplementation((): boolean => true)
})
expect(() => {
broadcaster.emit(payload)
}).not.toThrow()
expect(firstListener).toBeCalled()
})
test('listener is called only once', () => {
const listenerTwo = jest.fn()
broadcaster.addListener(jest.fn())
broadcaster.prependOnceListener(listenerTwo)
broadcaster.emit(payload)
broadcaster.emit(payload)
expect(listenerTwo).toBeCalledTimes(1)
})
})
describe('Remove listeners', () => {
test('removeListener method', () => {
broadcaster.addListener(listener)
broadcaster.removeListener(listener)
broadcaster.emit(payload)
expect(listener).not.toBeCalled()
})
test('remove listener via off method', () => {
broadcaster.addListener(listener)
broadcaster.off(listener)
broadcaster.emit(payload)
expect(listener).not.toBeCalled()
})
test('remove listener via removeAllListeners method', () => {
const listenerTwo = jest.fn()
broadcaster.addListener(listener)
broadcaster.addListener(listenerTwo)
broadcaster.removeAllListeners()
broadcaster.emit(payload)
expect(listener).not.toBeCalled()
expect(listenerTwo).not.toBeCalled()
})
test('unsubscribe listener via returned function ', () => {
const subOne = broadcaster.addListener(listener)
subOne()
broadcaster.emit(payload)
expect(listener).not.toBeCalled()
})
})
})
describe('Get and set number of listeners', () => {
test('initialize with the default number (0) unlimited', () => { |
test('initialize with custom number', () => {
const max = 4
const broadcaster = new Broadcaster('_', max)
expect(broadcaster.getEventEmitter().getMaxListeners()).toBe(max)
})
test('set maximum number of listeners listeners', () => {
const max = 11
broadcaster.setMaxListeners(max)
expect(broadcaster.getEventEmitter().getMaxListeners()).toBe(max)
})
test('get maximum number listeners', () => {
const max = broadcaster.getMaxListeners()
expect(broadcaster.getEventEmitter().getMaxListeners()).toBe(max)
})
})
describe('Query listeners', () => {
test('get all listeners', () => {
const listeners = [jest.fn(), jest.fn(), jest.fn()]
broadcaster.addListener(listeners[0])
broadcaster.once(listeners[1])
broadcaster.addListener(listeners[2])
expect(broadcaster.listeners()).toEqual(expect.arrayContaining(listeners))
})
test('call raw listeners method', () => {
const listeners = [jest.fn(), jest.fn(), jest.fn()]
broadcaster.addListener(listeners[0])
broadcaster.addListener(listeners[1])
broadcaster.once(listeners[2])
listeners.splice(2)
expect(broadcaster.rawListeners()).toEqual(
expect.arrayContaining(listeners)
)
})
test('get listener count', () => {
broadcaster.addListener(jest.fn())
broadcaster.once(jest.fn())
broadcaster.prependListener(jest.fn())
broadcaster.prependOnceListener(jest.fn())
expect(broadcaster.listenerCount()).toBe(4)
})
})
describe('Destroy', () => {
test('release references', () => {
const internalEmitter = jest.spyOn(
broadcaster.emitter,
'removeAllListeners'
)
broadcaster.destroy()
expect(internalEmitter).toBeCalled()
})
})
}) | const broadcaster = new Broadcaster('test')
expect(broadcaster.getEventEmitter().getMaxListeners()).toBe(0)
}) |
integer.js | export function isEven(n) {
return n % 2 === 0;
}
export function | (n) {
return !isEven(n);
}
| isOdd |
server.ts | import express from 'express';
import cors from 'cors';
import routes from './routes';
const app = express();
app.use(cors()); |
app.listen(3000); | app.use(express.json());
app.use(routes); |
table.ts | /**
* @license | *
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, Input, NgModule} from '@angular/core';
import {BrowserModule, DomSanitizer, SafeStyle} from '@angular/platform-browser';
import {emptyTable, TableCell} from '../util';
let trustedEmptyColor: SafeStyle;
let trustedGreyColor: SafeStyle;
@Component({
selector: 'largetable',
template: `<table><tbody>
<tr *ngFor="let row of data; trackBy: trackByIndex">
<td *ngFor="let cell of row; trackBy: trackByIndex" [style.backgroundColor]="getColor(cell.row)">
{{cell.value}}
</td>
</tr>
</tbody></table>`,
})
export class TableComponent {
@Input() data: TableCell[][] = emptyTable;
trackByIndex(index: number, item: any) {
return index;
}
getColor(row: number) {
return row % 2 ? trustedEmptyColor : trustedGreyColor;
}
}
@NgModule({imports: [BrowserModule], bootstrap: [TableComponent], declarations: [TableComponent]})
export class AppModule {
constructor(sanitizer: DomSanitizer) {
trustedEmptyColor = sanitizer.bypassSecurityTrustStyle('white');
trustedGreyColor = sanitizer.bypassSecurityTrustStyle('grey');
}
} | * Copyright Google LLC All Rights Reserved. |
0008_auto_20180116_0137.py | # Generated by Django 2.0.1 on 2018-01-15 19:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('forum', '0007_auto_20180113_1812'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.DeleteModel(
name='User',
),
migrations.AddField(
model_name='userprofile',
name='user',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
] |
|
product.controller.ts | import {
Body,
Controller,
Delete,
Get,
Inject,
Param,
Post,
Put,
} from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { Product } from '@prisma/client';
import { ProductDto } from './dto';
import { ProductService } from './product.service';
@Controller('products')
export class | {
constructor(
private productService: ProductService,
@Inject('PRODUCT_SERVICE') private readonly client: ClientProxy,
) {}
@Post()
async createProduct(@Body() dto: ProductDto): Promise<Product> {
const product = await this.productService.createProduct(dto);
this.client.emit('product_created', product);
return product;
}
@Get()
async all(): Promise<Product[]> {
this.client.emit('hello', { message: 'Hello from RabbitMQ!' });
return this.productService.allProducts();
}
@Get(':id')
async getProductById(@Param('id') id: string): Promise<Product> {
return this.productService.getProductById(id);
}
@Put(':id')
async updateProduct(
@Param('id') id: string,
@Body() data: any,
): Promise<Product> {
const updatedProduct = await this.productService.updateProduct(id, data);
this.client.emit('product_updated', updatedProduct);
return updatedProduct;
}
@Delete(':id')
async deleteProduct(@Param('id') id: string): Promise<void> {
await this.productService.deleteProduct(id);
this.client.emit('product_deleted', id);
}
}
| ProductController |
InterpolateSequenceToInterpolate_test.py | # Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import unittest
from openvino.tools.mo.middle.InterpolateSequenceToInterpolate import InterpolateSequenceToInterpolate
from openvino.tools.mo.front.common.partial_infer.utils import int64_array
from openvino.tools.mo.utils.ir_engine.compare_graphs import compare_graphs
from unit_tests.utils.graph import build_graph
graph_node_attrs_for_2d_case_1_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'size_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([660])
},
'size_1_data': {'value': int64_array([660]), 'shape': [1], 'kind': 'data'},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([3.0])
},
'scale_1_data': {'value': np.array([3.0]), 'shape': [1], 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2])
},
'axes_1_data': {'value': int64_array([2]), 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'scales',
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 660, 350]), 'kind': 'data'},
'size_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([700])
},
'size_2_data': {'value': int64_array([700]), 'shape': [1], 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([2.0])
},
'scale_2_data': {'value': np.array([2.0]), 'shape': [1], 'kind': 'data'},
'axes_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([3])
},
'axes_2_data': {'value': int64_array([3]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'scales',
'version': 'opset4'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 4, 660, 700]), 'kind': 'data'},
'size_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([1320])
},
'size_3_data': {'value': int64_array([1320]), 'shape': [1], 'kind': 'data'},
'scale_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([2.0])
},
'scale_3_data': {'value': np.array([2.0]), 'shape': [1], 'kind': 'data'},
'axes_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2])
},
'axes_3_data': {'value': int64_array([2]), 'shape': [1], 'kind': 'data'},
'interpolate_3': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'scales',
'version': 'opset4'
},
'interpolate_3_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_2d_case_1_opset4_case = [
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('size_1', 'size_1_data'),
('scale_1', 'scale_1_data'),
('axes_1', 'axes_1_data'),
('size_1_data', 'interpolate_1', {'in': 1}),
('scale_1_data', 'interpolate_1', {'in': 2}),
('axes_1_data', 'interpolate_1', {'in': 3}),
('interpolate_1', 'interpolate_1_data'),
('interpolate_1_data', 'interpolate_2', {'in': 0}),
('size_2', 'size_2_data'),
('scale_2', 'scale_2_data'),
('axes_2', 'axes_2_data'),
('size_2_data', 'interpolate_2', {'in': 1}),
('scale_2_data', 'interpolate_2', {'in': 2}),
('axes_2_data', 'interpolate_2', {'in': 3}),
('interpolate_2', 'interpolate_2_data'),
('interpolate_2_data', 'interpolate_3', {'in': 0}),
('size_3', 'size_3_data'),
('scale_3', 'scale_3_data'),
('axes_3', 'axes_3_data'),
('size_3_data', 'interpolate_3', {'in': 1}),
('scale_3_data', 'interpolate_3', {'in': 2}),
('axes_3_data', 'interpolate_3', {'in': 3}),
('interpolate_3', 'interpolate_3_data'),
('interpolate_3_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
ref_graph_node_attrs_for_2d_case_1_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'size_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([660, 700])
},
'size_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([3.0, 2.0])
},
'scale_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2, 3])
},
'axes_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'scales',
'antialias': 0,
'pads_begin': int64_array([0]),
'pads_end': int64_array([0]),
'coordinate_transformation_mode': 'half_pixel',
'nearest_mode': 'round_prefer_floor',
'cube_coeff': -0.75,
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 660, 700]), 'kind': 'data'},
'size_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([1320])
},
'size_3_data': {'value': None, 'shape': [1], 'kind': 'data'},
'scale_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([2.0])
},
'scale_3_data': {'value': None, 'shape': [1], 'kind': 'data'},
'axes_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2])
},
'axes_3_data': {'value': int64_array([2]), 'shape': [1], 'kind': 'data'},
'interpolate_3': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'scales',
'version': 'opset4'
},
'interpolate_3_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
ref_edges_for_2d_case_1_opset4_case = [
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('size_1', 'size_1_data'),
('scale_1', 'scale_1_data'),
('axes_1', 'axes_1_data'),
('size_1_data', 'interpolate_1', {'in': 1}),
('scale_1_data', 'interpolate_1', {'in': 2}),
('axes_1_data', 'interpolate_1', {'in': 3}),
('interpolate_1', 'interpolate_1_data'),
('interpolate_1_data', 'interpolate_3', {'in': 0}),
('size_3', 'size_3_data'),
('scale_3', 'scale_3_data'),
('axes_3', 'axes_3_data'),
('size_3_data', 'interpolate_3', {'in': 1}),
('scale_3_data', 'interpolate_3', {'in': 2}),
('axes_3_data', 'interpolate_3', {'in': 3}),
('interpolate_3', 'interpolate_3_data'),
('interpolate_3_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
graph_node_attrs_for_2d_case_1 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([660])
},
'scale_1_data': {'value': int64_array([660]), 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 660, 350]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([700])
},
'scale_2_data': {'value': int64_array([700]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([3]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 4, 660, 700]), 'kind': 'data'},
'scale_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([1320])
},
'scale_3_data': {'value': int64_array([1320]), 'shape': [1], 'kind': 'data'},
'interpolate_3': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_3_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_2d_case_1 = [
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('scale_1', 'scale_1_data'),
('scale_1_data', 'interpolate_1', {'in': 1}),
('interpolate_1', 'interpolate_1_data'),
('interpolate_1_data', 'interpolate_2', {'in': 0}),
('scale_2', 'scale_2_data'),
('scale_2_data', 'interpolate_2', {'in': 1}),
('interpolate_2', 'interpolate_2_data'),
('interpolate_2_data', 'interpolate_3', {'in': 0}),
('scale_3', 'scale_3_data'),
('scale_3_data', 'interpolate_3', {'in': 1}),
('interpolate_3', 'interpolate_3_data'),
('interpolate_3_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
graph_node_attrs_for_2d_case_2 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([660])
},
'scale_1_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 660, 350]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 660, 350]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_2d_case_2 = [
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('scale_1', 'scale_1_data'),
('scale_1_data', 'interpolate_1', {'in': 1}),
('interpolate_1', 'interpolate_1_data'),
('interpolate_1_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
graph_node_attrs_for_2d_case_3 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([660])
},
'scale_1_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 660, 350]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([700])
},
'scale_2_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([3]),
'mode': 'linear',
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 4, 660, 700]), 'kind': 'data'},
'scale_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([1320])
},
'scale_3_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_3': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'cubic',
'version': 'opset1'
},
'interpolate_3_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_2d_case_3 = edges_for_2d_case_1
new_graph_node_attrs_for_2d_case_4_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'size_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2200])
},
'size_1_data': {'value': int64_array([2200]), 'shape': [1], 'kind': 'data'},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([10.0])
},
'scale_1_data': {'value': np.array([10.0]), 'shape': [1], 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2])
},
'axes_1_data': {'value': int64_array([2]), 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'linear',
'coordinate_transformation_mode': 'asymmetric',
'nearest_mode': 'simple',
'cube_coeff': -0.4,
'antialias': 1,
'shape_calculation_mode': 'scales',
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 2200, 350]), 'kind': 'data'},
'size_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([700])
},
'size_2_data': {'value': int64_array([700]), 'shape': [1], 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([2.0])
},
'scale_2_data': {'value': np.array([2.0]), 'shape': [1], 'kind': 'data'},
'axes_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([3])
},
'axes_2_data': {'value': int64_array([3]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'linear',
'coordinate_transformation_mode': 'asymmetric',
'nearest_mode': 'simple',
'cube_coeff': -0.4,
'antialias': 1,
'shape_calculation_mode': 'scales',
'version': 'opset4'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
new_edges_for_2d_case_4_opset4_case = [
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('size_1', 'size_1_data'),
('size_1_data', 'interpolate_1', {'in': 1}),
('scale_1', 'scale_1_data'),
('scale_1_data', 'interpolate_1', {'in': 2}),
('axes_1', 'axes_1_data'),
('axes_1_data', 'interpolate_1', {'in': 3}),
('interpolate_1', 'interpolate_1_data'),
('interpolate_1_data', 'interpolate_2', {'in': 0}),
('size_2', 'size_2_data'),
('size_2_data', 'interpolate_2', {'in': 1}),
('scale_2', 'scale_2_data'),
('scale_2_data', 'interpolate_2', {'in': 2}),
('axes_2', 'axes_2_data'),
('axes_2_data', 'interpolate_2', {'in': 3}),
('interpolate_2', 'interpolate_2_data'),
('interpolate_2_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
new_ref_graph_node_attrs_for_2d_case_4_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'size_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2200, 700])
},
'size_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([10.0, 2.0])
},
'scale_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2, 3])
},
'axes_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'linear',
'coordinate_transformation_mode': 'asymmetric',
'nearest_mode': 'simple',
'cube_coeff': -0.4,
'antialias': 1,
'shape_calculation_mode': 'scales',
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
new_ref_edges_for_2d_case_4_opset4_case = [
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('size_1', 'size_1_data'),
('size_1_data', 'interpolate_1', {'in': 1}),
('scale_1', 'scale_1_data'),
('scale_1_data', 'interpolate_1', {'in': 2}),
('axes_1', 'axes_1_data'),
('axes_1_data', 'interpolate_1', {'in': 3}),
('interpolate_1', 'interpolate_1_data'),
('interpolate_1_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
graph_node_attrs_for_2d_case_4_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2200])
},
'scale_1_data': {'value': None, 'shape': [1], 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2])
},
'axes_1_data': {'value': int64_array([2]), 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'linear',
'coordinate_transformation_mode': 'asymmetric',
'nearest_mode': 'simple',
'cube_coeff': -0.4,
'antialias': 1,
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 2200, 350]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([700])
},
'scale_2_data': {'value': None, 'shape': [1], 'kind': 'data'},
'axes_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([3])
},
'axes_2_data': {'value': int64_array([3]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'linear',
'coordinate_transformation_mode': 'asymmetric',
'nearest_mode': 'simple',
'cube_coeff': -0.4,
'antialias': 1,
'version': 'opset4'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_2d_case_4_opset4_case = [
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('scale_1', 'scale_1_data'),
('scale_1_data', 'interpolate_1', {'in': 1}),
('axes_1', 'axes_1_data'),
('axes_1_data', 'interpolate_1', {'in': 2}),
('interpolate_1', 'interpolate_1_data'),
('interpolate_1_data', 'interpolate_2', {'in': 0}),
('scale_2', 'scale_2_data'),
('scale_2_data', 'interpolate_2', {'in': 1}),
('axes_2', 'axes_2_data'),
('axes_2_data', 'interpolate_2', {'in': 2}),
('interpolate_2', 'interpolate_2_data'),
('interpolate_2_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
graph_node_attrs_for_2d_case_4 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2200])
},
'scale_1_data': {'value': int64_array([2200]), 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'linear',
'align_corners': 0,
'antialias': 1,
'pads_begin': 5,
'pads_end': 3,
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 2200, 350]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([700])
},
'scale_2_data': {'value': int64_array([700]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([3]),
'mode': 'linear',
'align_corners': 0,
'antialias': 1,
'pads_begin': 5,
'pads_end': 3,
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_2d_case_4 = [
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('scale_1', 'scale_1_data'),
('scale_1_data', 'interpolate_1', {'in': 1}),
('interpolate_1', 'interpolate_1_data'),
('interpolate_1_data', 'interpolate_2', {'in': 0}),
('scale_2', 'scale_2_data'),
('scale_2_data', 'interpolate_2', {'in': 1}),
('interpolate_2', 'interpolate_2_data'),
('interpolate_2_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
graph_node_attrs_for_2d_case_6 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([220, 350])
},
'scale_1_data': {'value': None, 'shape': [2], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2, 3]),
'mode': 'linear',
'align_corners': 0,
'antialias': 1,
'pads_begin': 5,
'pads_end': 3,
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 220, 350]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([220])
},
'scale_2_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'linear',
'align_corners': 0,
'antialias': 1,
'pads_begin': 5,
'pads_end': 3,
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 4, 220, 350]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 220, 350]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_2d_case_6 = edges_for_2d_case_4
new_ref_graph_node_attrs_for_3d_case_1_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 5, 1024, 256, 800]),
'kind': 'data',
'data_type': None
},
'size_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4096, 1280, 2400])
},
'size_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([4.0, 5.0, 3.0])
},
'scale_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2, 3, 4])
},
'axes_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'sizes',
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 2400]), 'kind': 'data'},
'size_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([512])
},
'size_3_data': {'value': None, 'shape': [1], 'kind': 'data'},
'scale_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([512.0 / 2400.0])
},
'scale_3_data': {'value': None, 'shape': [1], 'kind': 'data'},
'axes_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4])
},
'axes_3_data': {'value': int64_array([4]), 'shape': [1], 'kind': 'data'},
'interpolate_3': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'sizes',
'version': 'opset4'
},
'interpolate_3_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 512]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 512]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
new_ref_edges_for_3d_case_1_opset4_case = ref_edges_for_2d_case_1_opset4_case
new_graph_node_attrs_for_3d_case_1_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 5, 1024, 256, 800]),
'kind': 'data',
'data_type': None
},
'size_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4096, 2400])
},
'size_1_data': {'value': int64_array([4096, 2400]), 'shape': [2], 'kind': 'data'},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([4.0, 3.0])
},
'scale_1_data': {'value': np.array([4.0, 3.0]), 'shape': [2], 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2, 4])
},
'axes_1_data': {'value': int64_array([2, 4]), 'shape': [2], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'sizes',
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 5, 4096, 256, 2400]), 'kind': 'data'},
'size_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([1280])
},
'size_2_data': {'value': int64_array([1280]), 'shape': [1], 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([5.0])
},
'scale_2_data': {'value': np.array([5.0]), 'shape': [1], 'kind': 'data'},
'axes_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([3])
},
'axes_2_data': {'value': int64_array([3]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'sizes',
'version': 'opset4'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 2400]), 'kind': 'data'},
'size_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([512])
},
'size_3_data': {'value': int64_array([512]), 'shape': [1], 'kind': 'data'},
'scale_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([512.0 / 2400.0])
},
'scale_3_data': {'value': np.array([512.0 / 2400.0]), 'shape': [1], 'kind': 'data'},
'axes_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4])
},
'axes_3_data': {'value': int64_array([4]), 'shape': [1], 'kind': 'data'},
'interpolate_3': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'nearest',
'shape_calculation_mode': 'sizes',
'version': 'opset4'
},
'interpolate_3_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 512]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 512]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
new_edges_for_3d_case_1_opset4_case = edges_for_2d_case_1_opset4_case
graph_node_attrs_for_3d_case_1 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 5, 1024, 256, 800]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4096, 2400])
},
'scale_1_data': {'value': int64_array([4096, 2400]), 'shape': [2], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2, 4]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 5, 4096, 256, 2400]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([1280])
},
'scale_2_data': {'value': int64_array([1280]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([3]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 2400]), 'kind': 'data'},
'scale_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([512])
},
'scale_3_data': {'value': int64_array([512]), 'shape': [1], 'kind': 'data'},
'interpolate_3': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([4]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_3_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 512]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 512]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_3d_case_1 = edges_for_2d_case_1
graph_node_attrs_for_3d_case_2 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 5, 1024, 256, 800]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4096, 1280])
},
'scale_1_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2, 3]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 800]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 800]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_3d_case_2 = edges_for_2d_case_2
graph_node_attrs_for_3d_case_3 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([16, 44, 512, 87, 790]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([256])
},
'scale_1_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([16, 44, 256, 87, 790]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2370])
},
'scale_2_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([4]),
'mode': 'linear',
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([16, 44, 256, 87, 2370]), 'kind': 'data'},
'scale_3': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([435])
},
'scale_3_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_3': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([3]),
'mode': 'cubic',
'version': 'opset1'
},
'interpolate_3_data': {'value': None, 'shape': int64_array([16, 44, 256, 435, 2370]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([16, 44, 256, 435, 2370]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_3d_case_3 = edges_for_2d_case_3
new_ref_graph_node_attrs_for_3d_case_4_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([10, 64, 511, 416, 10240]),
'kind': 'data',
'data_type': None
},
'size_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4599, 912, 133120])
},
'size_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const',
'value': np.array([4599.0 / 511.0, 912.0 / 416.0, 133120.0 / 10240.0])
},
'scale_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2, 3, 4])
},
'axes_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'linear',
'antialias': 1,
'shape_calculation_mode': 'sizes',
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([10, 64, 4599, 912, 133120]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([10, 64, 4599, 912, 133120]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
new_ref_edges_for_3d_case_4_opset4_case = new_ref_edges_for_2d_case_4_opset4_case
new_graph_node_attrs_for_3d_case_4_opset4_case = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([10, 64, 511, 416, 10240]),
'kind': 'data',
'data_type': None
},
'size_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4599, 133120])
},
'size_1_data': {'value': int64_array([4599, 133120]), 'shape': [2], 'kind': 'data'},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([4599.0 / 511.0, 133120.0 / 10240.0])
},
'scale_1_data': {'value': np.array([4599.0 / 511.0, 133120.0 / 10240.0]), 'shape': [2], 'kind': 'data'},
'axes_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2, 4])
},
'axes_1_data': {'value': int64_array([2, 4]), 'shape': [2], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'linear',
'antialias': 1,
'shape_calculation_mode': 'sizes',
'version': 'opset4'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([10, 64, 4599, 416, 133120]), 'kind': 'data'},
'size_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([912])
},
'size_2_data': {'value': int64_array([912]), 'shape': [1], 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': np.array([912.0 / 416.0])
},
'scale_2_data': {'value': np.array([912.0 / 416.0]), 'shape': [1], 'kind': 'data'},
'axes_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([3])
},
'axes_2_data': {'value': int64_array([3]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'mode': 'linear',
'antialias': 1,
'shape_calculation_mode': 'sizes',
'version': 'opset4'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([10, 64, 4599, 912, 133120]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([10, 64, 4599, 912, 133120]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
new_edges_for_3d_case_4_opset4_case = new_edges_for_2d_case_4_opset4_case
graph_node_attrs_for_3d_case_4 = {
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([10, 64, 511, 416, 10240]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4599, 133120])
},
'scale_1_data': {'value': int64_array([4599, 133120]), 'shape': [2], 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2, 4]),
'mode': 'linear',
'align_corners': 0,
'antialias': 1,
'pads_begin': 5,
'pads_end': 3,
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([10, 64, 4599, 416, 133120]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([912])
},
'scale_2_data': {'value': int64_array([912]), 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([3]),
'mode': 'linear',
'align_corners': 0,
'antialias': 1,
'pads_begin': 5,
'pads_end': 3,
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([10, 64, 4599, 912, 133120]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([10, 64, 4599, 912, 133120]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
}
edges_for_3d_case_4 = edges_for_2d_case_4
class InterpolateSequenceToInterpolateTest(unittest.TestCase):
def test_2d_interpolate_sequence_1(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_1,
edges=edges_for_2d_case_1
)
ref_graph = build_graph(
nodes_attrs={
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([660, 700])
},
'scale_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2, 3]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 4, 660, 700]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([1320])
},
'scale_2_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 1320, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
},
edges=[
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('scale_1', 'scale_1_data'),
('scale_1_data', 'interpolate_1', {'in': 1}),
('interpolate_1', 'interpolate_1_data'),
('scale_2', 'scale_2_data'),
('interpolate_2', 'interpolate_2_data'),
('interpolate_1_data', 'interpolate_2', {'in': 0}),
('scale_2_data', 'interpolate_2', {'in': 1}),
('interpolate_2_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_2d_interpolate_sequence_1_opset4_case(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_1_opset4_case,
edges=edges_for_2d_case_1_opset4_case
)
ref_graph = build_graph(
nodes_attrs=ref_graph_node_attrs_for_2d_case_1_opset4_case,
edges=ref_edges_for_2d_case_1_opset4_case
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_2d_interpolate_sequence_2(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_2,
edges=edges_for_2d_case_2
)
ref_graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_2,
edges=edges_for_2d_case_2
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_2d_interpolate_sequence_3(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_3,
edges=edges_for_2d_case_3
)
ref_graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_3,
edges=edges_for_2d_case_3
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_2d_interpolate_sequence_4(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_4,
edges=edges_for_2d_case_4
)
ref_graph = build_graph(
nodes_attrs={
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 4, 220, 350]),
'kind': 'data',
'data_type': None
},
'scale': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([2200, 700])
},
'scale_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2, 3]),
'mode': 'linear',
'align_corners': 0,
'antialias': 1,
'pads_begin': 5,
'pads_end': 3,
'version': 'opset1'
},
'interpolate_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 4, 2200, 700]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
},
edges=[
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate', {'in': 0}),
('scale', 'scale_data'),
('scale_data', 'interpolate', {'in': 1}),
('interpolate', 'interpolate_data'),
('interpolate_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_2d_interpolate_sequence_4_opset4_case(self):
graph = build_graph(
nodes_attrs=new_graph_node_attrs_for_2d_case_4_opset4_case,
edges=new_edges_for_2d_case_4_opset4_case
)
ref_graph = build_graph(
nodes_attrs=new_ref_graph_node_attrs_for_2d_case_4_opset4_case,
edges=new_ref_edges_for_2d_case_4_opset4_case
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_2d_interpolate_sequence_5(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_4,
edges=edges_for_2d_case_4,
update_attributes={
'interpolate_1': {
'align_corners': 1, 'antialias': 1, 'pads_begin': 3, 'pads_end': 0
}
}
)
ref_graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_4,
edges=edges_for_2d_case_4,
update_attributes={
'interpolate_1': {
'align_corners': 1, 'antialias': 1, 'pads_begin': 3, 'pads_end': 0
}
}
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_2d_interpolate_sequence_5_opset4_case(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_4_opset4_case,
edges=edges_for_2d_case_4_opset4_case,
update_attributes={
'interpolate_1': {
'antialias': 0, 'cube_coeff': -0.1
}
}
)
ref_graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_4_opset4_case,
edges=edges_for_2d_case_4_opset4_case,
update_attributes={
'interpolate_1': {
'antialias': 0, 'cube_coeff': -0.1
}
}
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_2d_interpolate_sequence_6(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_6,
edges=edges_for_2d_case_6,
)
ref_graph = build_graph(
nodes_attrs=graph_node_attrs_for_2d_case_6,
edges=edges_for_2d_case_6
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_3d_interpolate_sequence_1(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_3d_case_1,
edges=edges_for_3d_case_1
)
ref_graph = build_graph(
nodes_attrs={
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([1, 5, 1024, 256, 800]),
'kind': 'data',
'data_type': None
},
'scale_1': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4096, 1280, 2400])
},
'scale_1_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate_1': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2, 3, 4]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_1_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 2400]), 'kind': 'data'},
'scale_2': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([512])
},
'scale_2_data': {'value': None, 'shape': [1], 'kind': 'data'},
'interpolate_2': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([4]),
'mode': 'nearest',
'version': 'opset1'
},
'interpolate_2_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 512]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([1, 5, 4096, 1280, 512]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
},
edges=[
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate_1', {'in': 0}),
('scale_1', 'scale_1_data'),
('scale_1_data', 'interpolate_1', {'in': 1}),
('interpolate_1', 'interpolate_1_data'),
('scale_2', 'scale_2_data'),
('interpolate_2', 'interpolate_2_data'),
('interpolate_1_data', 'interpolate_2', {'in': 0}),
('scale_2_data', 'interpolate_2', {'in': 1}),
('interpolate_2_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_3d_interpolate_sequence_1_opset4_case(self):
|
def test_3d_interpolate_sequence_2(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_3d_case_2,
edges=edges_for_3d_case_2
)
ref_graph = build_graph(
nodes_attrs=graph_node_attrs_for_3d_case_2,
edges=edges_for_3d_case_2
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_3d_interpolate_sequence_3(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_3d_case_3,
edges=edges_for_3d_case_3
)
ref_graph = build_graph(
nodes_attrs=graph_node_attrs_for_3d_case_3,
edges=edges_for_3d_case_3
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_3d_interpolate_sequence_4(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_3d_case_4,
edges=edges_for_3d_case_4
)
ref_graph = build_graph(
nodes_attrs={
'placeholder': {'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},
'placeholder_data': {
'value': None,
'shape': int64_array([10, 64, 511, 416, 10240]),
'kind': 'data',
'data_type': None
},
'scale': {
'kind': 'op', 'op': 'Const', 'type': 'Const', 'value': int64_array([4599, 912, 133120])
},
'scale_data': {'value': None, 'shape': None, 'kind': 'data'},
'interpolate': {
'type': 'Interpolate',
'kind': 'op',
'op': 'Interpolate',
'axes': int64_array([2, 3, 4]),
'mode': 'linear',
'align_corners': 0,
'antialias': 1,
'pads_begin': 5,
'pads_end': 3,
'version': 'opset1'
},
'interpolate_data': {'value': None, 'shape': int64_array([10, 64, 4599, 912, 133120]), 'kind': 'data'},
'abs': {'type': 'Abs', 'kind': 'op', 'op': 'Abs'},
'abs_data': {'value': None, 'shape': int64_array([10, 64, 4599, 912, 133120]), 'kind': 'data'},
'output': {'kind': 'op', 'op': 'Result'},
},
edges=[
('placeholder', 'placeholder_data'),
('placeholder_data', 'interpolate', {'in': 0}),
('scale', 'scale_data'),
('scale_data', 'interpolate', {'in': 1}),
('interpolate', 'interpolate_data'),
('interpolate_data', 'abs'),
('abs', 'abs_data'),
('abs_data', 'output'),
]
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_3d_interpolate_sequence_4_opset4_case(self):
graph = build_graph(
nodes_attrs=new_graph_node_attrs_for_3d_case_4_opset4_case,
edges=new_edges_for_3d_case_4_opset4_case
)
ref_graph = build_graph(
nodes_attrs=new_ref_graph_node_attrs_for_3d_case_4_opset4_case,
edges=new_ref_edges_for_3d_case_4_opset4_case
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
def test_3d_interpolate_sequence_5(self):
graph = build_graph(
nodes_attrs=graph_node_attrs_for_3d_case_4,
edges=edges_for_3d_case_4,
update_attributes={
'interpolate_1': {
'align_corners': 1, 'antialias': 1, 'pads_begin': 3, 'pads_end': 7
}
}
)
ref_graph = build_graph(
nodes_attrs=graph_node_attrs_for_3d_case_4,
edges=edges_for_3d_case_4,
update_attributes={
'interpolate_1': {
'align_corners': 1, 'antialias': 1, 'pads_begin': 3, 'pads_end': 7
}
}
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp)
| graph = build_graph(
nodes_attrs=new_graph_node_attrs_for_3d_case_1_opset4_case,
edges=new_edges_for_3d_case_1_opset4_case
)
ref_graph = build_graph(
nodes_attrs=new_ref_graph_node_attrs_for_3d_case_1_opset4_case,
edges=new_ref_edges_for_3d_case_1_opset4_case
)
InterpolateSequenceToInterpolate().find_and_replace_pattern(graph)
(flag, resp) = compare_graphs(graph, ref_graph, 'output')
self.assertTrue(flag, resp) |
Behav_Consistency.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Letter-color Consistency test
O.Colizoli 2020
Each letter of the alphabet in random order x 2
Color wheel opens at a randomized color on each trial (but does not turn)
Python 2..7
"""
# data saved in ~/LogFiles/sub-XXX
# Import necessary modules
import random
import numpy as np
import pandas as pd
import os, time # for paths and data
from IPython import embed as shell
try:
import Tkinter as tk # py27
from tkColorChooser import askcolor
except:
import tkinter as tk
from tkinter.colorchooser import askcolor
# Get subject number via tkinter (command line doesn't work in PsychoPy)
subject_ID = []
session = []
## INPUT WINDOW
class GetInput():
def __init__(self):
self.root2 = tk.Tk()
self.root2.title("Subject and Session")
# always put in same location
w = 400 # width for the Tk root
h = 200 # height for the Tk root
# get screen width and height
ws = self.root2.winfo_screenwidth() # width of the screen
hs = self.root2.winfo_screenheight() # height of the screen
# calculate x and y coordinates for the Tk root window
x = (ws/6) - (w/6)
y = (hs/6) - (h/6)
self.root2.geometry('%dx%d+%d+%d' % (w, h, x, y))
# Subject
self.e = tk.Entry(self.root2)
self.e.insert(0, 'Subject Number')
self.e.pack()
self.e.focus_set()
# Session
self.e2 = tk.Entry(self.root2)
self.e2.insert(0, 'Session')
self.e2.pack()
self.e2.focus_set()
txt='If each letter of the alphabet\
\nwere to have a unique color,\
\nwhat color would it have?\
\n\nThere are no right or wrong answers.'
# instructions
self.instr = tk.Label(self.root2, bg='white', text=txt, font=("Helvetica", 14))
self.instr.pack()
b = tk.Button(self.root2,text='OK',command=self.get_input)
b.pack(side='bottom')
self.root2.mainloop()
def get_input(self):
subj_str = self.e.get()
sess_str = self.e2.get()
subject_ID.append(subj_str)
session.append(sess_str)
self.root2.destroy()
## ASK INPUT
app = GetInput() # subject and session
subject_ID = int(subject_ID[0])
session = int(session[0])
## Create LogFile folder cwd/LogFiles
cwd = os.getcwd()
logfile_dir = os.path.join(cwd,'LogFiles','sub-{}'.format(subject_ID),'sess-{}'.format(session),'behav')
if not os.path.isdir(logfile_dir):
os.makedirs(logfile_dir)
timestr = time.strftime("%Y%m%d-%H%M%S")
output_alphabet = os.path.join(logfile_dir,'sub-{}_sess-{}_task-consistency_events_{}.tsv'.format(subject_ID,session,timestr))
### CONSISTENCY TASK ###
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#alphabet = ['a','b','c']
REPS = 2 # number of times to repeat whole alphabet
RGBS = [] # save output
L = '2' # place holder
class Test():
def __init__(self):
self.counter = 1
self.root = tk.Tk()
self.root.title("Subject {} Session {}".format(subject_ID, session))
# always put in same location
# get screen width and height
ws = self.root.winfo_screenwidth() # width of the screen
hs = self.root.winfo_screenheight() # height of the screen
# open in full screen
self.root.geometry('%dx%d+%d+%d' % (ws, hs, 0, 0))
self.open1 = tk.Button(self.root, text='Pick a color:', command=self.pick_a_color, font=('Helvetica', '36'),padx=5, pady=5)
self.open1.pack(fill=tk.X, expand=False)
self.letter = tk.Label(self.root, bg='white', text=L, font=("Helvetica", 90))
self.letter.pack()
self.root.mainloop()
def quit(self):
|
def pick_a_color(self,):
# GET COLOR CHOOSER NOT OPEN ON TOP OF ROOT
self.RGB,self.HEX = askcolor((random.randint(0,255), random.randint(0,255), random.randint(0,255)), parent=None, title='Pick a color: {}'.format(L) )
self.letter.configure(fg = self.HEX)
if self.counter:
exit_button = tk.Button(self.root, text='FINISHED', command=self.quit, font=('Helvetica', '28'))
exit_button.pack()
self.counter = 0
self.root.mainloop()
# MAIN LOOP
abc = 1 # round
for R in np.arange(REPS):
random.shuffle(alphabet)
# Open a new GUI per letter
for L in alphabet:
app = Test()
# save colors on each trial to prevent losing data
DFS = pd.DataFrame(RGBS)
print(RGBS)
try:
DFS.columns = ["letter","rgb","hex","choice"]
DFS['subject'] = np.repeat(subject_ID,len(DFS))
DFS['r'] = [c[0] for c in DFS['rgb']]
DFS['g'] = [c[1] for c in DFS['rgb']]
DFS['b'] = [c[2] for c in DFS['rgb']]
except:
# clicked window away
pass
DFS.to_csv(output_alphabet, sep='\t') # save all alphabet/preferences for both groups (also in case it goes wrong)
abc+=1
####################################
## SAVE OUTPUT & determine conditions
print(RGBS)
print('consistency test - success!')
##### OUTPUT FIGURE WITH COLORS #####
# Sort and show letters x 2 side by side
del tk # py27
del askcolor
import matplotlib.pyplot as plt # doesn't work together with tkinter
import seaborn as sns
fig = plt.figure(figsize=(10,5))
# Sort so the same letters go side by side for each choice
try:
DFS.sort_values(by=['choice', 'letter'],inplace=True)
except:
DFS = DFS.sort(['choice', 'letter'])
DFS.reset_index(inplace=True)
for i,A in enumerate(alphabet):
ax = fig.add_subplot(6,5,i+1)
ax.text(0.5, 0.5, DFS['letter'][i], color=DFS['hex'][i],fontsize=18)
ax.text(0.25, 0.5, DFS['letter'][i+len(alphabet)], color=DFS['hex'][i+len(alphabet)],fontsize=18)
ax.set_axis_off()
sns.despine(offset=10, trim=True)
plt.tight_layout()
fig.savefig(os.path.join(cwd,'LogFiles','sub-{}'.format(subject_ID),'sess-{}'.format(session),'behav','sub-{}_sess-{}_colors.pdf'.format(subject_ID,session)))
print('success: sub-{}_sess-{}_colors.pdf'.format(subject_ID,session))
| RGBS.append( [L ,self.RGB, self.HEX, abc] )
self.root.destroy() |
dimension_value_item_request_builder.go | package item
import (
i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f "github.com/microsoft/kiota-abstractions-go"
ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459 "github.com/microsoftgraph/msgraph-beta-sdk-go/models/odataerrors"
)
// DimensionValueItemRequestBuilder provides operations to manage the dimensionValues property of the microsoft.graph.dimension entity.
type DimensionValueItemRequestBuilder struct {
// Path parameters for the request
pathParameters map[string]string
// The request adapter to use to execute the requests.
requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter
// Url template to use to build the URL for the current request builder
urlTemplate string
}
// DimensionValueItemRequestBuilderDeleteRequestConfiguration configuration for the request such as headers, query parameters, and middleware options.
type DimensionValueItemRequestBuilderDeleteRequestConfiguration struct {
// Request headers
Headers map[string]string
// Request options
Options []i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestOption
}
// DimensionValueItemRequestBuilderGetQueryParameters get dimensionValues from financials
type DimensionValueItemRequestBuilderGetQueryParameters struct {
// Expand related entities
Expand []string `uriparametername:"%24expand"`
// Select properties to be returned
Select []string `uriparametername:"%24select"`
}
// DimensionValueItemRequestBuilderGetRequestConfiguration configuration for the request such as headers, query parameters, and middleware options.
type DimensionValueItemRequestBuilderGetRequestConfiguration struct {
// Request headers
Headers map[string]string
// Request options
Options []i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestOption
// Request query parameters
QueryParameters *DimensionValueItemRequestBuilderGetQueryParameters
}
// DimensionValueItemRequestBuilderPatchRequestConfiguration configuration for the request such as headers, query parameters, and middleware options.
type DimensionValueItemRequestBuilderPatchRequestConfiguration struct {
// Request headers
Headers map[string]string
// Request options
Options []i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestOption
}
// NewDimensionValueItemRequestBuilderInternal instantiates a new DimensionValueItemRequestBuilder and sets the default values.
func NewDimensionValueItemRequestBuilderInternal(pathParameters map[string]string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*DimensionValueItemRequestBuilder) {
m := &DimensionValueItemRequestBuilder{
}
m.urlTemplate = "{+baseurl}/financials/companies/{company%2Did}/dimensions/{dimension%2Did}/dimensionValues/{dimensionValue%2Did}{?%24select,%24expand}";
urlTplParams := make(map[string]string)
for idx, item := range pathParameters {
urlTplParams[idx] = item
}
m.pathParameters = urlTplParams;
m.requestAdapter = requestAdapter;
return m
}
// NewDimensionValueItemRequestBuilder instantiates a new DimensionValueItemRequestBuilder and sets the default values.
func NewDimensionValueItemRequestBuilder(rawUrl string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*DimensionValueItemRequestBuilder) {
urlParams := make(map[string]string)
urlParams["request-raw-url"] = rawUrl
return NewDimensionValueItemRequestBuilderInternal(urlParams, requestAdapter)
}
// CreateDeleteRequestInformation delete navigation property dimensionValues for financials
func (m *DimensionValueItemRequestBuilder) CreateDeleteRequestInformation()(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {
return m.CreateDeleteRequestInformationWithRequestConfiguration(nil);
}
// CreateDeleteRequestInformationWithRequestConfiguration delete navigation property dimensionValues for financials
func (m *DimensionValueItemRequestBuilder) CreateDeleteRequestInformationWithRequestConfiguration(requestConfiguration *DimensionValueItemRequestBuilderDeleteRequestConfiguration)(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {
requestInfo := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.DELETE
if requestConfiguration != nil {
requestInfo.AddRequestHeaders(requestConfiguration.Headers)
requestInfo.AddRequestOptions(requestConfiguration.Options)
}
return requestInfo, nil
}
// CreateGetRequestInformation get dimensionValues from financials
func (m *DimensionValueItemRequestBuilder) CreateGetRequestInformation()(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {
return m.CreateGetRequestInformationWithRequestConfiguration(nil);
}
// CreateGetRequestInformationWithRequestConfiguration get dimensionValues from financials
func (m *DimensionValueItemRequestBuilder) CreateGetRequestInformationWithRequestConfiguration(requestConfiguration *DimensionValueItemRequestBuilderGetRequestConfiguration)(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {
requestInfo := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.GET
if requestConfiguration != nil {
if requestConfiguration.QueryParameters != nil {
requestInfo.AddQueryParameters(*(requestConfiguration.QueryParameters))
}
requestInfo.AddRequestHeaders(requestConfiguration.Headers)
requestInfo.AddRequestOptions(requestConfiguration.Options)
}
return requestInfo, nil
}
// CreatePatchRequestInformation update the navigation property dimensionValues in financials
func (m *DimensionValueItemRequestBuilder) CreatePatchRequestInformation(body ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.DimensionValueable)(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {
return m.CreatePatchRequestInformationWithRequestConfiguration(body, nil);
}
// CreatePatchRequestInformationWithRequestConfiguration update the navigation property dimensionValues in financials
func (m *DimensionValueItemRequestBuilder) CreatePatchRequestInformationWithRequestConfiguration(body ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.DimensionValueable, requestConfiguration *DimensionValueItemRequestBuilderPatchRequestConfiguration)(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {
requestInfo := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.PATCH
requestInfo.SetContentFromParsable(m.requestAdapter, "application/json", body)
if requestConfiguration != nil {
requestInfo.AddRequestHeaders(requestConfiguration.Headers)
requestInfo.AddRequestOptions(requestConfiguration.Options)
}
return requestInfo, nil
}
// Delete delete navigation property dimensionValues for financials
func (m *DimensionValueItemRequestBuilder) Delete()(error) {
return m.DeleteWithRequestConfigurationAndResponseHandler(nil, nil);
}
// DeleteWithRequestConfigurationAndResponseHandler delete navigation property dimensionValues for financials
func (m *DimensionValueItemRequestBuilder) DeleteWithRequestConfigurationAndResponseHandler(requestConfiguration *DimensionValueItemRequestBuilderDeleteRequestConfiguration, responseHandler i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ResponseHandler)(error) {
requestInfo, err := m.CreateDeleteRequestInformationWithRequestConfiguration(requestConfiguration);
if err != nil {
return err
}
errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {
"4XX": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,
"5XX": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,
}
err = m.requestAdapter.SendNoContentAsync(requestInfo, responseHandler, errorMapping)
if err != nil {
return err
}
return nil
}
// Get get dimensionValues from financials
func (m *DimensionValueItemRequestBuilder) Get()(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.DimensionValueable, error) {
return m.GetWithRequestConfigurationAndResponseHandler(nil, nil);
}
// GetWithRequestConfigurationAndResponseHandler get dimensionValues from financials
func (m *DimensionValueItemRequestBuilder) GetWithRequestConfigurationAndResponseHandler(requestConfiguration *DimensionValueItemRequestBuilderGetRequestConfiguration, responseHandler i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ResponseHandler)(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.DimensionValueable, error) {
requestInfo, err := m.CreateGetRequestInformationWithRequestConfiguration(requestConfiguration);
if err != nil {
return nil, err
}
errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {
"4XX": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,
"5XX": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,
}
res, err := m.requestAdapter.SendAsync(requestInfo, ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.CreateDimensionValueFromDiscriminatorValue, responseHandler, errorMapping)
if err != nil {
return nil, err
}
return res.(ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.DimensionValueable), nil
}
// Patch update the navigation property dimensionValues in financials
func (m *DimensionValueItemRequestBuilder) Patch(body ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.DimensionValueable)(error) {
return m.PatchWithRequestConfigurationAndResponseHandler(body, nil, nil);
}
// PatchWithRequestConfigurationAndResponseHandler update the navigation property dimensionValues in financials
func (m *DimensionValueItemRequestBuilder) PatchWithRequestConfigurationAndResponseHandler(body ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.DimensionValueable, requestConfiguration *DimensionValueItemRequestBuilderPatchRequestConfiguration, responseHandler i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ResponseHandler)(error) {
requestInfo, err := m.CreatePatchRequestInformationWithRequestConfiguration(body, requestConfiguration);
if err != nil {
return err
}
errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {
"4XX": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,
"5XX": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,
}
err = m.requestAdapter.SendNoContentAsync(requestInfo, responseHandler, errorMapping) | }
return nil
} | if err != nil {
return err |
main.go | package main
import (
"flag"
"fmt"
gt "github.com/pubref/grpc_greetertimer/proto"
"golang.org/x/net/context"
"google.golang.org/grpc"
"io"
"log"
)
func connect(timerHost *string, timerAddress *int) (gt.GreeterTimerClient, *grpc.ClientConn, error) {
address := fmt.Sprintf("%s:%d", *timerHost, *timerAddress)
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
return nil, nil, err
}
client := gt.NewGreeterTimerClient(conn)
return client, conn, nil
}
func submit(client gt.GreeterTimerClient, request *gt.TimerRequest) error {
stream, err := client.TimeGreetings(context.Background(), request)
if err != nil {
log.Fatalf("could not submit request: %v", err)
}
for {
batchResponse, err := stream.Recv()
if err == io.EOF {
log.Printf("EOF: %s", batchResponse)
return nil
}
if err != nil {
log.Fatalf("bad batch recv: %v", err)
return err
}
reportBatchResult(batchResponse)
}
}
func reportBatchResult(b *gt.BatchResponse) {
time := float32(b.BatchTimeMillis)
count := float32(b.BatchCount)
rate := count / time
q := (time / count) * 1000
fmt := "%d hellos (%d errs, %d remaining): %.1f hellos/ms or ~%.0f\u00B5s per hello"
log.Printf(fmt, b.BatchCount, b.ErrCount, b.Remaining, rate, q)
}
func main() {
timerHost := flag.String("timer_host", "localhost",
"hostname where greeterTimer service is running")
timerPort := flag.Int("timer_port", 50053,
"port where greeterTimer service is running")
helloHost := flag.String("hello_host", "localhost",
"hostname where hello service is running")
helloPort := flag.Int("hello_port", 50051,
"port where hello service is running")
totalSize := flag.Int("total_size", 10000,
"total number of messages size")
batchSize := flag.Int("batch_size", 1000,
"stream batch size")
flag.Parse()
timerRequest := >.TimerRequest{
Host: *helloHost,
Port: int32(*helloPort),
TotalSize: int32(*totalSize),
BatchSize: int32(*batchSize),
}
client, conn, err := connect(timerHost, timerPort)
defer conn.Close()
if err != nil |
submit(client, timerRequest)
}
| {
log.Fatalf("did not connect: %v", err)
} |
encode.go | // Copyright 2011 The Snappy-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package snappy
import (
"encoding/binary"
"io"
)
// We limit how far copy back-references can go, the same as the C++ code.
const maxOffset = 1 << 15
// read-only bytes
var magicChunkBytes = []byte(magicChunk)
// emitLiteral writes a literal chunk and returns the number of bytes written.
func emitLiteral(dst, lit []byte) int {
i, n := 0, uint(len(lit)-1)
switch {
case n < 60:
dst[0] = uint8(n)<<2 | tagLiteral
i = 1
case n < 1<<8:
dst[0] = 60<<2 | tagLiteral
dst[1] = uint8(n)
i = 2
case n < 1<<16:
dst[0] = 61<<2 | tagLiteral
dst[1] = uint8(n)
dst[2] = uint8(n >> 8)
i = 3
case n < 1<<24:
dst[0] = 62<<2 | tagLiteral
dst[1] = uint8(n)
dst[2] = uint8(n >> 8)
dst[3] = uint8(n >> 16)
i = 4
case int64(n) < 1<<32:
dst[0] = 63<<2 | tagLiteral
dst[1] = uint8(n)
dst[2] = uint8(n >> 8)
dst[3] = uint8(n >> 16)
dst[4] = uint8(n >> 24)
i = 5
default:
panic("snappy: source buffer is too long")
}
if copy(dst[i:], lit) != len(lit) {
panic("snappy: destination buffer is too short")
}
return i + len(lit)
}
// emitCopy writes a copy chunk and returns the number of bytes written.
func emitCopy(dst []byte, offset, length int) int {
i := 0
for length > 0 {
x := length - 4
if 0 <= x && x < 1<<3 && offset < 1<<11 |
x = length
if x > 1<<6 {
x = 1 << 6
}
dst[i+0] = uint8(x-1)<<2 | tagCopy2
dst[i+1] = uint8(offset)
dst[i+2] = uint8(offset >> 8)
i += 3
length -= x
}
return i
}
// Encode returns the encoded form of src. The returned slice may be a sub-
// slice of dst if dst was large enough to hold the entire encoded block.
// Otherwise, a newly allocated slice will be returned.
// It is valid to pass a nil dst.
func Encode(dst, src []byte) []byte {
if n := MaxEncodedLen(len(src)); len(dst) < n {
dst = make([]byte, n)
}
d := encode(dst, src)
return dst[:d]
}
func encode(dst, src []byte) (d int) {
// The block starts with the varint-encoded length of the decompressed bytes.
l := len(src)
d = binary.PutUvarint(dst, uint64(l))
// Return early if src is short.
if l <= 4 {
if l != 0 {
d += emitLiteral(dst[d:], src)
}
return
}
// Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
const maxTableSize = 1 << 14
shift, tableSize := uint(32-8), 1<<8
for tableSize < maxTableSize && tableSize < l {
shift--
tableSize *= 2
}
var table [maxTableSize]int
// Iterate over the source bytes.
var (
s int // The iterator position.
t int // The last position with the same hash as s.
lit int // The start position of any pending literal bytes.
)
for s+3 < l {
// Update the hash table.
b0, b1, b2, b3 := src[s], src[s+1], src[s+2], src[s+3]
h := uint32(b0) | uint32(b1)<<8 | uint32(b2)<<16 | uint32(b3)<<24
p := &table[(h*0x1e35a7bd)>>shift]
// We need to to store values in [-1, inf) in table. To save
// some initialization time, (re)use the table's zero value
// and shift the values against this zero: add 1 on writes,
// subtract 1 on reads.
t, *p = *p-1, s+1
// If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal byte.
if t < 0 || s-t >= maxOffset || b0 != src[t] || b1 != src[t+1] || b2 != src[t+2] || b3 != src[t+3] {
s++
continue
}
// Otherwise, we have a match. First, emit any pending literal bytes.
if lit != s {
d += emitLiteral(dst[d:], src[lit:s])
}
// Extend the match to be as long as possible.
s0 := s
s, t = s+4, t+4
for s < l && src[s] == src[t] {
s++
t++
}
// Emit the copied bytes.
d += emitCopy(dst[d:], s-t, s-s0)
lit = s
}
// Emit any final pending literal bytes and return.
if lit != l {
d += emitLiteral(dst[d:], src[lit:])
}
return
}
// MaxEncodedLen returns the maximum length of a snappy block, given its
// uncompressed length.
func MaxEncodedLen(srcLen int) int {
// Compressed data can be defined as:
// compressed := item* literal*
// item := literal* copy
//
// The trailing literal sequence has a space blowup of at most 62/60
// since a literal of length 60 needs one tag byte + one extra byte
// for length information.
//
// Item blowup is trickier to measure. Suppose the "copy" op copies
// 4 bytes of data. Because of a special check in the encoding code,
// we produce a 4-byte copy only if the offset is < 65536. Therefore
// the copy op takes 3 bytes to encode, and this type of item leads
// to at most the 62/60 blowup for representing literals.
//
// Suppose the "copy" op copies 5 bytes of data. If the offset is big
// enough, it will take 5 bytes to encode the copy op. Therefore the
// worst case here is a one-byte literal followed by a five-byte copy.
// That is, 6 bytes of input turn into 7 bytes of "compressed" data.
//
// This last factor dominates the blowup, so the final estimate is:
return 32 + srcLen + srcLen/6
}
// NewWriter returns a new Writer that compresses to w, using the framing
// format described at
// https://github.com/google/snappy/blob/master/framing_format.txt
func NewWriter(w io.Writer) *Writer {
return &Writer{
w: w,
enc: pool.Get().([]byte)[:maxEncodedUncompressedChunkLenPlusChecksumPlusHeaderSize],
buf: pool.Get().([]byte)[:maxUncompressedChunkLen],
}
}
func WriteOnce(writer io.Writer, p []byte) (n int, err error) {
if _, err = writer.Write(magicChunkBytes); err != nil {
return
}
w := &Writer{
w: writer,
enc: pool.Get().([]byte)[:maxEncodedUncompressedChunkLenPlusChecksumPlusHeaderSize],
}
defer pool.Put(w.enc)
var uncompressed []byte
for len(p) > 0 {
if len(p) > maxUncompressedChunkLen {
uncompressed, p = p[:maxUncompressedChunkLen], p[maxUncompressedChunkLen:]
} else {
uncompressed, p = p, nil
}
if err = w.writeChunk(uncompressed); err != nil {
return
}
n += len(uncompressed)
}
return
}
// Writer is an io.Writer than can write Snappy-compressed bytes.
type Writer struct {
w io.Writer
err error
enc []byte
buf []byte
bufCursor int
wroteHeader bool
}
// Reset discards the writer's state and switches the Snappy writer to write to
// w. This permits reusing a Writer rather than allocating a new one.
func (w *Writer) Reset(writer io.Writer) {
w.w = writer
w.err = nil
w.bufCursor = 0
w.wroteHeader = false
}
// Write satisfies the io.Writer interface.
func (w *Writer) Write(p []byte) (n int, err error) {
if w.err != nil {
return 0, w.err
}
if !w.wroteHeader {
if _, err = w.w.Write(magicChunkBytes); err != nil {
w.err = err
return
}
w.wroteHeader = true
}
var uncompressed []byte
var noBuffer bool
if len(p) > maxUncompressedChunkLen {
noBuffer = true
}
for len(p) > 0 {
if len(p) > maxUncompressedChunkLen {
uncompressed, p = p[:maxUncompressedChunkLen], p[maxUncompressedChunkLen:]
} else {
uncompressed, p = p, nil
}
// Writes with length under minUncompressedChunkLen will be copied to the buffer, over this length will be written directly as one chunk without buffering
// This means many small writes will be collected and written together as one single large chunk, while any large writes will be written immediately
// This behavior should enhance both speed and compression for small writes without sacrificing speed on large writes
l := len(uncompressed)
if noBuffer || l > minUncompressedChunkLen {
if w.bufCursor > 0 {
if err = w.writeChunk(w.buf[0:w.bufCursor]); err != nil { // flush
return
}
w.bufCursor = 0
}
if err = w.writeChunk(uncompressed); err != nil {
return
}
} else {
if l + w.bufCursor > maxUncompressedChunkLen {
if err = w.writeChunk(w.buf[0:w.bufCursor]); err != nil { // flush
return
}
w.bufCursor = 0
}
copy(w.buf[w.bufCursor:], uncompressed)
w.bufCursor += l
}
n += l
}
return
}
func (w *Writer) writeChunk(uncompressed []byte) error {
checksum := crc(uncompressed)
// Compress the buffer, discarding the result if the improvement
// isn't at least 12.5%.
chunkBody := w.enc
chunkLen := encode(chunkBody[checksumPlusChunkHeaderSize:], uncompressed)
if chunkLen >= len(uncompressed) - len(uncompressed)/8 {
// Write the uncompressed data
chunkLen = 4 + len(uncompressed)
chunkBody[0] = chunkTypeUncompressedData
chunkBody[1] = uint8(chunkLen)
chunkBody[2] = uint8(chunkLen >> 8)
chunkBody[3] = uint8(chunkLen >> 16)
chunkBody[4] = uint8(checksum >> 0)
chunkBody[5] = uint8(checksum >> 8)
chunkBody[6] = uint8(checksum >> 16)
chunkBody[7] = uint8(checksum >> 24)
if _, err := w.w.Write(chunkBody[:8]); err != nil {
w.err = err
return err
}
if _, err := w.w.Write(uncompressed); err != nil {
w.err = err
return err
}
} else {
// Write the compressed data
chunkBody = chunkBody[:chunkLen + checksumPlusChunkHeaderSize]
chunkLen += 4
chunkBody[0] = chunkTypeCompressedData
chunkBody[1] = uint8(chunkLen)
chunkBody[2] = uint8(chunkLen >> 8)
chunkBody[3] = uint8(chunkLen >> 16)
chunkBody[4] = uint8(checksum >> 0)
chunkBody[5] = uint8(checksum >> 8)
chunkBody[6] = uint8(checksum >> 16)
chunkBody[7] = uint8(checksum >> 24)
if _, err := w.w.Write(chunkBody); err != nil {
w.err = err
return err
}
}
return nil
}
func (w *Writer) Flush() error {
if w.err != nil {
return w.err
}
if w.bufCursor > 0 {
w.err = w.writeChunk(w.buf[0:w.bufCursor])
w.bufCursor = 0
return w.err
}
return nil
}
func (w *Writer) Close() error {
if w.err == ErrClosed {
return nil
}
if w.bufCursor > 0 {
if err := w.writeChunk(w.buf[0:w.bufCursor]); err != nil {
w.err = err
return err
}
}
pool.Put(w.enc)
pool.Put(w.buf)
w.err = ErrClosed
return nil
}
| {
dst[i+0] = uint8(offset>>8)&0x07<<5 | uint8(x)<<2 | tagCopy1
dst[i+1] = uint8(offset)
i += 2
break
} |
procedure.rs | use crate::ast::expression::ExpressionType;
use crate::ast::semantic::SymbolId;
#[derive(Debug, Clone, PartialEq)]
pub struct Procedure {
pub id: SymbolId,
pub name: String,
pub params_types: Vec<ExpressionType>,
pub return_type: ExpressionType,
}
| name: name.to_owned(),
params_types: Vec::new(),
return_type: ExpressionType::Unit,
}
}
} | impl Procedure {
pub fn new(name: &str, id: SymbolId) -> Self {
Self {
id, |
soho-wizard-page.component.ts | import {
HostBinding,
Input,
Component,
ChangeDetectionStrategy,
ElementRef,
AfterViewInit,
Output,
EventEmitter
} from '@angular/core';
/**
* Angular wrapper for the soho wizard page.
*/
@Component({
selector: 'div[soho-wizard-page]', // eslint-disable-line
template: `<ng-content></ng-content>`,
styles: [
`:host {
flex: 1;
display: flex;
flex-direction: column;
overflow-y: auto;
}`
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class | implements AfterViewInit {
jQueryElement!: JQuery;
@HostBinding('class.wizard-page') isWizardPage = true;
/**
* Is this wizard page hidden? Return true by default to avoid
* displaying all the pages for a moment. The wizard will
* ensure only a single page is displayed.
*
*
*/
@HostBinding('class.hidden') hidden = true; // tslint: ignore-line
/** This id of the associated tick. */
@Input()
tickId!: string; // tslint: ignore-line
/**
* Event fired when the page is activated.
*/
@Output() activated = new EventEmitter<SohoWizardEvent>();
/**
* Constructor.
*
* @param el owning DOM element
*
*/
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
this.jQueryElement = $(this.el.nativeElement);
}
/**
* Fire the activated event, using the given SohoWizardEvent.
*
* I'd have rather done this with an event, but we end up
* with a circular dependency.
*
* @param e - the soho wizard event.
*
*/
fireActivated(e: SohoWizardEvent) {
this.activated.next(e);
}
}
| SohoWizardPageComponent |
vme_test.go | package vme
import (
"bytes"
"github.com/coschain/contentos-go/common"
"reflect" | "testing"
)
func requireEncodeError(t *testing.T, value interface{}) {
_, err := Encode(value)
if err == nil {
t.Fatalf("encoding should fail, but succeeded. value = %v", value)
}
}
func requireEncodeOK(t *testing.T, value interface{}) []byte {
data, err := Encode(value)
if err != nil {
t.Fatalf("encoding should succeed, but got error = %v, value = %v", err, value)
}
return data
}
func requireEncodeResult(t *testing.T, value interface{}, leBytes...byte) {
enc := requireEncodeOK(t, value)
r := leBytes
if !common.IsLittleEndianPlatform() {
n := len(leBytes)
r = make([]byte, n)
n--
for i := range r {
r[i] = leBytes[n - i]
}
}
if bytes.Compare(r, enc) != 0 {
t.Fatalf("encoding result error. got %v, expecting %v", enc, r)
}
}
func requireDecodeOK(t *testing.T, typ reflect.Type, leBytes...byte) interface{} {
enc := leBytes
if !common.IsLittleEndianPlatform() {
n := len(leBytes)
enc = make([]byte, n)
n--
for i := range enc {
enc[i] = leBytes[n - i]
}
}
d, err := DecodeWithType(enc, typ)
if err != nil {
t.Fatalf("decoding to %s failed. encoded bytes = %v", typ.String(), enc)
}
return d
}
func requireDecodeResult(t *testing.T, value interface{}, leBytes...byte) {
d := requireDecodeOK(t, reflect.TypeOf(value), leBytes...)
if d != value {
t.Fatalf("decoding result error. got %v, expecting %v", d, value)
}
}
func TestEncode(t *testing.T) {
requireEncodeResult(t, true, 1)
requireEncodeResult(t, false, 0)
requireEncodeResult(t, int8(10), 10)
requireEncodeResult(t, int8(-2), 0xfe)
requireEncodeResult(t, int16(100), 100, 0)
requireEncodeResult(t, int32(-10), 0xf6, 0xff, 0xff, 0xff)
requireEncodeResult(t, int64(12345678), 0x4e, 0x61, 0xbc, 0, 0, 0, 0, 0)
requireEncodeResult(t, uint8(10), 10)
requireEncodeResult(t, int16(4321), 0xe1, 0x10)
requireEncodeResult(t, uint32(645322), 0xca, 0xd8, 0x09, 0)
requireEncodeResult(t, uint64(987654321), 0xb1, 0x68, 0xde, 0x3a, 0, 0, 0, 0)
requireEncodeResult(t, float32(3.14159), 0xd0, 0x0f, 0x49, 0x40)
requireEncodeResult(t, float64(3.14159265359), 0xea, 0x2e, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40)
requireEncodeResult(t, "hello", []byte("\x05hello")...)
requireEncodeResult(t, "", 0)
requireEncodeResult(t, []byte("hello"), []byte("\x05hello")...)
requireEncodeResult(t, []byte{}, 0)
requireEncodeResult(t, StructValue("alice", int16(100), float32(3.14159)), []byte("\x03\x05alice\x64\x00\xd0\x0f\x49\x40")...)
requireEncodeResult(t,
StructValue("bob",
StructValue("alice", int16(100), float32(3.14159)),
),
[]byte("\x02\x03bob\x03\x05alice\x64\x00\xd0\x0f\x49\x40")...)
requireEncodeResult(t, []int32{3,4,5,6}, 4, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0)
requireEncodeResult(t, []string{"nice", "to", "meet", "you"}, []byte("\x04\x04nice\x02to\x04meet\x03you")...)
requireEncodeError(t, map[int]int{1:2, 3:4})
requireEncodeError(t, nil)
requireEncodeError(t, []interface{}{3})
}
func TestDecode(t *testing.T) {
requireDecodeResult(t, true, 1)
requireDecodeResult(t, false, 0)
requireDecodeResult(t, int8(10), 10)
requireDecodeResult(t, int8(-2), 0xfe)
requireDecodeResult(t, int16(100), 100, 0)
requireDecodeResult(t, int32(-10), 0xf6, 0xff, 0xff, 0xff)
requireDecodeResult(t, int64(12345678), 0x4e, 0x61, 0xbc, 0, 0, 0, 0, 0)
requireDecodeResult(t, uint8(10), 10)
requireDecodeResult(t, int16(4321), 0xe1, 0x10)
requireDecodeResult(t, uint32(645322), 0xca, 0xd8, 0x09, 0)
requireDecodeResult(t, uint64(987654321), 0xb1, 0x68, 0xde, 0x3a, 0, 0, 0, 0)
requireDecodeResult(t, float32(3.14159), 0xd0, 0x0f, 0x49, 0x40)
requireDecodeResult(t, float64(3.14159265359), 0xea, 0x2e, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40)
requireDecodeResult(t, "hello", []byte("\x05hello")...)
requireDecodeResult(t, "", 0)
var d interface{}
d = requireDecodeOK(t, BytesType(), 0)
if bytes.Compare(d.([]byte), []byte{}) != 0 {
t.Fatalf("decoding result error. got %v, expecting %v", d, []byte("hello"))
}
d = requireDecodeOK(t, BytesType(), []byte("\x05hello")...)
if bytes.Compare(d.([]byte), []byte("hello")) != 0 {
t.Fatalf("decoding result error. got %v, expecting %v", d, []byte("hello"))
}
sv := StructValue("bob",
StructValue("alice", int16(100), float32(3.14159)),
)
d = requireDecodeOK(t, reflect.TypeOf(sv), []byte("\x02\x03bob\x03\x05alice\x64\x00\xd0\x0f\x49\x40")...)
if reflect.ValueOf(d).Field(0).String() != "bob" ||
reflect.ValueOf(d).Field(1).Field(0).String() != "alice" ||
reflect.ValueOf(d).Field(1).Field(1).Int() != 100 ||
reflect.ValueOf(d).Field(1).Field(2).Float() != float64(float32(3.14159)) {
t.Fatal("decoding result error on structures")
}
v1 := int32(0)
Decode([]byte{10, 0, 0, 0}, &v1)
if v1 != 10 {
t.Fatal("decoding result error on ints")
}
v2 := "world"
Decode([]byte("\x05hello"), &v2)
if v2 != "hello" {
t.Fatal("decoding result error on strings")
}
t3 := StructOf(StringType(), StructOf(StringType(), Int16Type(), Float32Type()))
p3 := reflect.New(t3).Interface()
Decode([]byte("\x02\x03bob\x03\x05alice\x64\x00\xd0\x0f\x49\x40"), p3)
if reflect.ValueOf(p3).Elem().Field(0).String() != "bob" {
t.Fatal("decoding result error on structures")
}
ss, _ := DecodeWithType([]byte("\x04\x04nice\x02to\x04meet\x03you"), reflect.SliceOf(reflect.TypeOf("")))
s4 := ss.([]string)
if len(s4) != 4 || s4[0] != "nice" || s4[1] != "to" || s4[2] != "meet" || s4[3] != "you" {
t.Fatal("decoding []string error")
}
} | |
errorsource.go | package errors
import (
"encoding/json"
"fmt"
)
type (
errorSource struct {
*errorType
source error
}
)
| return e.source.Error()
}
// NewAsSource returns a new error which is the source.
func NewAsSource(msg string) error {
return newSource(nil, new(nil, msg, 1), 1)
}
// NewAsSourcef returns a new error which is the source.
func NewAsSourcef(format string, a ...interface{}) error {
return newSource(nil, new(nil, fmt.Sprintf(format, a...), 1), 1)
}
// AsSource returns a new source error.
func AsSource(err error) error {
if err == nil {
return nil
}
return newSource(nil, err, 1)
}
// WrapBySourceError returns a new error.
// If the error is passed to errors.SourceOf function,
// returns the source.
func WrapBySourceError(inner error, source error) error {
if inner == nil {
return nil
}
return newSource(inner, source, 1)
}
// WrapBySourceMsg returns a new error.
func WrapBySourceMsg(inner error, msg string) error {
if inner == nil {
return nil
}
return newSource(inner, new(nil, msg, 1), 1)
}
// WrapBySourceMsgf returns a new error.
func WrapBySourceMsgf(inner error, format string, a ...interface{}) error {
if inner == nil {
return nil
}
return newSource(inner, new(nil, fmt.Sprintf(format, a...), 1), 1)
}
// SourceOf returns the source error of the err.
func SourceOf(err error) error {
if e, ok := err.(*errorSource); ok {
return e.source
}
if e, ok := err.(*collection); ok {
return e.source()
}
if e, ok := err.(*errorType); ok {
if e.inner != nil {
return SourceOf(e.inner)
}
return e
}
return err
}
// ExplicitSourceOf returns an error if the error is
// explicitly specified Source by WrapBySourceXxx.
func ExplicitSourceOf(err error) error {
if e, ok := err.(*errorSource); ok {
return e.source
}
if e, ok := err.(*collection); ok {
return e.explicitSource()
}
if e, ok := err.(*errorType); ok {
if e.inner != nil {
return ExplicitSourceOf(e.inner)
}
return nil
}
return nil
}
// MarshalJSON implements json.Marshaler interface.
func (e *errorSource) MarshalJSON() ([]byte, error) {
obj := struct {
Inner *errMarshal `json:"inner"`
Callers *callerInfo `json:"callers"`
Message string `json:"message"`
IsSource bool `json:"isSource"`
}{
Inner: &errMarshal{
err: e.inner,
callerCount: e.callerCount,
},
Callers: e.info,
Message: e.source.Error(),
IsSource: true,
}
return json.Marshal(&obj)
}
func newSource(inner error, source error, skip int) error {
return &errorSource{
errorType: new(inner, "", skip+1).(*errorType),
source: source,
}
} | // Error implements error interface.
func (e *errorSource) Error() string { |
types.rs | use std::cell::RefCell;
use std::hash::{Hash, Hasher};
use std::os::raw::{c_int, c_void};
use std::sync::{Arc, Mutex};
use std::{fmt, mem, ptr};
#[cfg(feature = "async")]
use futures_core::future::LocalBoxFuture;
use crate::error::Result;
use crate::ffi;
use crate::hook::Debug;
use crate::lua::Lua;
use crate::util::{assert_stack, StackGuard};
use crate::value::MultiValue;
/// Type of Lua integer numbers.
pub type Integer = ffi::lua_Integer;
/// Type of Lua floating point numbers.
pub type Number = ffi::lua_Number;
/// A "light" userdata value. Equivalent to an unmanaged raw pointer.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct LightUserData(pub *mut c_void);
pub(crate) type Callback<'lua, 'a> =
Box<dyn Fn(&'lua Lua, MultiValue<'lua>) -> Result<MultiValue<'lua>> + 'a>;
pub(crate) struct CallbackUpvalue<'lua> {
pub(crate) lua: Lua,
pub(crate) func: Callback<'lua, 'static>,
}
#[cfg(feature = "async")]
pub(crate) type AsyncCallback<'lua, 'a> =
Box<dyn Fn(&'lua Lua, MultiValue<'lua>) -> LocalBoxFuture<'lua, Result<MultiValue<'lua>>> + 'a>;
#[cfg(feature = "async")]
pub(crate) struct AsyncCallbackUpvalue<'lua> {
pub(crate) lua: Lua,
pub(crate) func: AsyncCallback<'lua, 'static>,
}
#[cfg(feature = "async")]
pub(crate) struct AsyncPollUpvalue<'lua> {
pub(crate) lua: Lua,
pub(crate) fut: LocalBoxFuture<'lua, Result<MultiValue<'lua>>>,
}
#[cfg(feature = "send")]
pub(crate) type HookCallback = Arc<RefCell<dyn FnMut(&Lua, Debug) -> Result<()> + Send>>;
#[cfg(not(feature = "send"))]
pub(crate) type HookCallback = Arc<RefCell<dyn FnMut(&Lua, Debug) -> Result<()>>>;
#[cfg(feature = "send")]
pub trait MaybeSend: Send {}
#[cfg(feature = "send")]
impl<T: Send> MaybeSend for T {}
#[cfg(not(feature = "send"))]
pub trait MaybeSend {}
#[cfg(not(feature = "send"))]
impl<T> MaybeSend for T {}
pub(crate) struct DestructedUserdataMT;
/// An auto generated key into the Lua registry.
///
/// This is a handle to a value stored inside the Lua registry. It is not automatically
/// garbage collected on Drop, but it can be removed with [`Lua::remove_registry_value`],
/// and instances not manually removed can be garbage collected with [`Lua::expire_registry_values`].
///
/// Be warned, If you place this into Lua via a [`UserData`] type or a rust callback, it is *very
/// easy* to accidentally cause reference cycles that the Lua garbage collector cannot resolve.
/// Instead of placing a [`RegistryKey`] into a [`UserData`] type, prefer instead to use
/// [`AnyUserData::set_user_value`] / [`AnyUserData::get_user_value`].
///
/// [`UserData`]: crate::UserData
/// [`RegistryKey`]: crate::RegistryKey
/// [`Lua::remove_registry_value`]: crate::Lua::remove_registry_value
/// [`Lua::expire_registry_values`]: crate::Lua::expire_registry_values
/// [`AnyUserData::set_user_value`]: crate::AnyUserData::set_user_value
/// [`AnyUserData::get_user_value`]: crate::AnyUserData::get_user_value
pub struct RegistryKey {
pub(crate) registry_id: c_int,
pub(crate) unref_list: Arc<Mutex<Option<Vec<c_int>>>>,
}
impl fmt::Debug for RegistryKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "RegistryKey({})", self.registry_id)
}
}
impl Hash for RegistryKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.registry_id.hash(state)
}
}
impl PartialEq for RegistryKey {
fn eq(&self, other: &RegistryKey) -> bool {
self.registry_id == other.registry_id && Arc::ptr_eq(&self.unref_list, &other.unref_list)
}
}
impl Eq for RegistryKey {}
impl Drop for RegistryKey {
fn drop(&mut self) {
let mut unref_list = mlua_expect!(self.unref_list.lock(), "unref list poisoned"); | }
impl RegistryKey {
// Destroys the RegistryKey without adding to the drop list
pub(crate) fn take(self) -> c_int {
let registry_id = self.registry_id;
unsafe {
ptr::read(&self.unref_list);
mem::forget(self);
}
registry_id
}
}
pub(crate) struct LuaRef<'lua> {
pub(crate) lua: &'lua Lua,
pub(crate) index: c_int,
}
impl<'lua> fmt::Debug for LuaRef<'lua> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Ref({})", self.index)
}
}
impl<'lua> Clone for LuaRef<'lua> {
fn clone(&self) -> Self {
self.lua.clone_ref(self)
}
}
impl<'lua> Drop for LuaRef<'lua> {
fn drop(&mut self) {
self.lua.drop_ref(self)
}
}
impl<'lua> PartialEq for LuaRef<'lua> {
fn eq(&self, other: &Self) -> bool {
let lua = self.lua;
unsafe {
let _sg = StackGuard::new(lua.state);
assert_stack(lua.state, 2);
lua.push_ref(self);
lua.push_ref(other);
ffi::lua_rawequal(lua.state, -1, -2) == 1
}
}
} | if let Some(list) = unref_list.as_mut() {
list.push(self.registry_id);
}
} |
timer.js | /*
* This file contains the logic of the Timer application. It may seem complex,
* but it strictly follows the MVC pattern, which dictates to separate model
* (the Project and Projects classes) from the code manipulating the HTML. The
* use of MVC was probably not necessary in such a small application, but I
* consider it an exercise in using this pattern in a new environment
* (client-side JavaScript application).
*/
/* ===== Project ===== */
/*
* The Project class represents a project and tracks the time the user has spent
* working on it.
*
* The project can be in two states - stopped and running. The "running" state
* means that the user is working on the project. The start time of the current
* work iteration is recorded in the "_currentIterationStartTime" attribute.
* When the work is finished, the project is switched into the "stopped" state
* and the difference between the current time and "_currentIterationStartTime"
* (i.e. the length of the last work iteration) is added to the value of
* "_timeSpentInPreviousIterations" attribute. This attribute tracks the total
* amount of time spent on the project (not counting the current work iteration
* if the project is in the "running" state).
*
* The chosen scheme allows to compute the total time spent on the project at
* any time, touching the attributes only at the times when the work on the
* project is started or stopped. This property is important when detecting
* whether other instance of the application touched any projects.
*
* All times are stored in classic Unix format: milliseconds since the beginning
* of time (we all know when it was :-) Time in this format is easy to obtain
* (by calling "Date.getTime()") and handle (using simple arithmetic).
*/
/* Creates a new Project object. */
function Project(name) {
this._name = name;
this._state = Project.State.STOPPED;
this._timeSpentInPreviousIterations = 0;
this._currentIterationStartTime = 0;
this._onChange = null;
}
/* Possible project states. */
Project.State = {
STOPPED: "stopped",
RUNNING: "running"
}
Project.prototype = {
/* Returns the project name. */
getName: function() {
return this._name;
},
/* Returns the project state. */
getState: function() {
return this._state;
},
/* Is the project stopped? */
isStopped: function() {
return this._state == Project.State.STOPPED;
},
/* Is the project running? */
isRunning: function() {
return this._state == Project.State.RUNNING;
},
/*
* Sets the "onChange" event handler. The "onChange" event is fired when the
* project is started, stopped, or reset.
*/
setOnChange: function(onChange) {
this._onChange = onChange;
},
/*
* Returns the time spent on the project in the current work iteration. Works
* correctly only when the project is running.
*/
_getCurrentIterationTime: function() {
return (new Date).getTime() - this._currentIterationStartTime;
},
/*
* Returns the total time spent on the project. This includes time spent in
* the current work iteration if the project is running.
*/
getTimeSpent: function() {
var result = this._timeSpentInPreviousIterations;
if (this._state == Project.State.RUNNING) {
result += this._getCurrentIterationTime();
}
return result;
},
/* Calls the "onChange" event handler if set. */
_callOnChange: function() {
if (typeof this._onChange == "function") {
this._onChange();
}
},
/* Starts a new project work iteration. */
start: function() {
if (this._state == Project.State.RUNNING) { return };
this._state = Project.State.RUNNING;
this._currentIterationStartTime = (new Date).getTime();
this._callOnChange();
},
/* Stops the current project work iteration. */
stop: function() {
if (this._state == Project.State.STOPPED) { return };
this._state = Project.State.STOPPED;
this._timeSpentInPreviousIterations += this._getCurrentIterationTime();
this._currentIterationStartTime = 0;
this._callOnChange();
},
/* Stops the current project work iteration and resets the time data. */
reset: function() {
this.stop();
this._timeSpentInPreviousIterations = 0;
this._callOnChange();
},
/* Serializes the project into a string. */
serialize: function() {
/*
* Originally, I wanted to use "toSource" and "eval" for serialization and
* deserialization, but "toSource" is not supported by WebKit, so I resorted
* to ugly hackery...
*/
return [
encodeURIComponent(this._name),
this._state,
this._timeSpentInPreviousIterations,
this._currentIterationStartTime
].join("&");
},
/* Deserializes the project from a string. */
deserialize: function(serialized) {
var parts = serialized.split("&");
this._name = decodeURIComponent(parts[0]);
this._state = parts[1];
this._timeSpentInPreviousIterations = parseInt(parts[2]);
this._currentIterationStartTime = parseInt(parts[3]);
}
}
/* ===== Projects ===== */
/* The Projects class represents a list of projects. */
/* Creates a new Projects object. */
function Projects() {
this._projects = [];
this._onAdd = null;
this._onRemove = null;
}
Projects.prototype = {
/*
* Sets the "onAdd" event handler. The "onAdd" event is fired when a project
* is added to the list.
*/
setOnAdd: function(onAdd) {
this._onAdd = onAdd;
},
/*
* Sets the "onRemove" event handler. The "onRemove" event is fired when a
* project is removed from the list.
*/
setOnRemove: function(onRemove) {
this._onRemove = onRemove;
},
/* Returns the length of the project list. */
length: function() {
return this._projects.length
},
/*
* Returns index-th project in the list, or "undefined" if the index is out of
* bounds.
*/
get: function(index) {
return this._projects[index];
},
/*
* Calls the callback function for each project in the list. The function is
* called with three parameters - the project, its index and the project list
* object. This is modeled after "Array.forEach" in JavaScript 1.6.
*/
forEach: function(callback) {
for (var i = 0; i < this._projects.length; i++) {
callback(this._projects[i], i, this);
}
},
/* Calls the "onAdd" event handler if set. */
_callOnAdd: function(project) {
if (typeof this._onAdd == "function") {
this._onAdd(project);
}
},
/* Adds a new project to the end of the list. */
add: function(project) {
this._projects.push(project);
this._callOnAdd(project);
},
/* Calls the "onRemove" event handler if set. */
_callOnRemove: function(index) {
if (typeof this._onRemove == "function") {
this._onRemove(index);
}
},
/*
* Removes index-th project from the list. Does not do anything if the index
* is out of bounds.
*/
remove: function(index) {
this._callOnRemove(index);
this._projects.splice(index, 1);
},
/* Serializes the list of projects into a string. */
serialize: function() {
var serializedProjects = [];
this.forEach(function(project) {
serializedProjects.push(project.serialize());
});
return serializedProjects.join("|");
},
/* Deserializes the list of projects from a string. */
deserialize: function(serialized) {
/*
* Repeatedly use "remove" so the "onRemove" event is triggered. Do the same
* with the "add" method below.
*/
while (this._projects.length > 0) {
this.remove(0);
}
var serializedProjects = serialized.split("|");
for (var i = 0; i < serializedProjects.length; i++) {
var project = new Project("");
project.deserialize(serializedProjects[i]);
this.add(project);
}
}
}
/* ===== Extensions ===== */
/*
* Pads this string with another string on the left until the resulting string
* has specified length. If the padding string has more than one character, the
* resulting string may be longer than desired (the padding string is not
* truncated and it is only prepended as a whole). Bad API, I know, but it's
* good enough for me.
*/
String.prototype.pad = function(length, padding) {
var result = this;
while (result.length < length) {
result = padding + result;
}
return result;
}
/* ===== Project List + DOM Storage ===== */
/* The list of projects. */
var projects = new Projects();
/* The last value of the serialized project list string. */
var lastSerializedProjectsString;
/*
* The key under which the serialized project list string is stored in the DOM
* Storage.
*/
var PROJECTS_DOM_STORAGE_KEY = "timerProjects";
/*
* Returns DOM Storage used by the application, or "null" if the browser does
* not support DOM Storage.
*/
function getStorage() {
/*
* HTML 5 says that the persistent storage is available in the
* "window.localStorage" attribute, however Firefox implements older version
* of the proposal, which uses "window.globalStorage" indexed by the domain
* name. We deal with this situation here as gracefully as possible (i.e.
* without concrete browser detection and with forward compatibility).
*
* For more information, see:
*
* http://www.whatwg.org/specs/web-apps/current-work/#storage
* https://developer.mozilla.org/En/DOM/Storage
*/
if (window.localStorage !== undefined) {
return window.localStorage;
} else if (window.globalStorage !== undefined) {
return window.globalStorage[location.hostname];
} else {
return null;
}
}
/*
* Saves the project list into a DOM Storage. Also updates the value of the
* "lastSerializedProjectsString" variable.
*/
function saveProjects() {
var serializedProjectsString = projects.serialize();
getStorage()[PROJECTS_DOM_STORAGE_KEY] = serializedProjectsString;
lastSerializedProjectsString = serializedProjectsString;
}
/*
* Loads the serialized project list string from the DOM Storage. Returns
* "undefined" if the storage does not contain the string (this happens when
* running the application for the first time).
*/
function loadSerializedProjectsString() {
var storedValue = getStorage()[PROJECTS_DOM_STORAGE_KEY];
/*
* The spec says "null" should be returned when the key is not found, but some
* browsers return "undefined" instead. Maybe it was in some earlier version
* of the spec (I didn't bother to check).
*/
if (storedValue !== null && storedValue !== undefined) {
/*
* The values retrieved from "globalStorage" use one more level of
* indirection.
*/
return (window.localStorage === undefined) ? storedValue.value : storedValue;
} else {
return undefined;
}
}
/*
* Loads the project list from the DOM Storage. Also updates the value of the
* "lastSerializedProjectsString" variable.
*/
function loadProjects() {
var serializedProjectsString = loadSerializedProjectsString();
if (serializedProjectsString !== undefined) {
projects.deserialize(serializedProjectsString);
lastSerializedProjectsString = serializedProjectsString;
}
}
/*
* Was the project list changed outside of the application? Detects the change
* by comparing the current serialized project list string in the DOM Storage
* with a kept old value.
*/
function | () {
return loadSerializedProjectsString() != lastSerializedProjectsString;
}
/* ===== View ===== */
/* Some time constants. */
var MILISECONDS_IN_SECOND = 1000;
var MILISECONDS_IN_MINUTE = 60 * MILISECONDS_IN_SECOND;
var MINUTES_IN_HOUR = 60;
/* Formats the time in the H:MM format. */
function formatTime(time) {
var timeInMinutes = time / MILISECONDS_IN_MINUTE;
var hours = Math.floor(timeInMinutes / MINUTES_IN_HOUR);
var minutes = Math.floor(timeInMinutes - hours * MINUTES_IN_HOUR);
return hours + ":" + String(minutes).pad(2, "0");
}
/*
* Computes the URL of the image in the start/stop link according to the project
* state.
*/
function computeStartStopLinkImageUrl(state) {
switch (state) {
case Project.State.STOPPED:
return "img/start.png";
case Project.State.RUNNING:
return "img/stop.png";
default:
throw "Invalid project state."
}
}
/*
* Builds the HTML element of the row in the project table corresponding to the
* specified project and index.
*/
function buildProjectRow(project, index) {
var result = $("<tr />");
var startStopLink = $(
"<a href='#' class='start-stop-link' title='Start/stop'>"
+ "<img src='" + computeStartStopLinkImageUrl(project.getState()) + "' width='16' height='16' alt='Start/stop' />"
+ "</a>"
);
startStopLink.click(function() {
switch (project.getState()) {
case Project.State.STOPPED:
project.start();
break;
case Project.State.RUNNING:
project.stop();
break;
default:
throw "Invalid project state."
}
saveProjects();
return false;
});
var resetLink = $(
"<a href='#' title='Reset'>"
+ "<img src='img/reset.png' width='16' height='16' alt='Reset' />"
+ "</a>"
);
resetLink.click(function() {
project.reset();
saveProjects();
return false;
});
var deleteLink = $(
"<a href='#' title='Delete'>"
+ "<img src='img/delete.png' width='16' height='16' alt='Delete' />"
+ "</a>"
);
deleteLink.click(function() {
if (confirm("Do you really want to delete delete project \"" + project.getName() + "\"?")) {
projects.remove(index);
saveProjects();
}
return false;
});
result
.addClass("state-" + project.getState())
.append($("<td class='project-name' />").text(project.getName()))
.append($("<td class='project-time' />").text(formatTime(project.getTimeSpent())))
.append($("<td class='project-actions' />")
.append(startStopLink)
.append(resetLink)
.append(" ")
.append(deleteLink)
);
return result;
}
/* Finds row with the specified index in the project table. */
function findRowWithIndex(index) {
return $("#project-table").find("tr").slice(1).eq(index);
}
/*
* Updates the row in the project table corresponding to a project according to
* its state.
*/
function updateProjectRow(row, project) {
if (project.isStopped()) {
row.removeClass("state-running");
row.addClass("state-stopped");
} else if (project.isRunning()) {
row.removeClass("state-stopped");
row.addClass("state-running");
}
row.find(".project-time").text(formatTime(project.getTimeSpent()))
row.find(".start-stop-link img").attr(
"src",
computeStartStopLinkImageUrl(project.getState())
);
}
/* ===== Initialization ===== */
/* Initializes event handlers on the project list. */
function initializeProjectsEventHandlers() {
projects.setOnAdd(function(project) {
var row = buildProjectRow(project, projects.length() - 1);
$("#project-table").append(row);
project.setOnChange(function() {
updateProjectRow(row, project);
});
});
projects.setOnRemove(function(index) {
findRowWithIndex(index).remove();
});
}
/* Initializes GUI event handlers. */
function initializeGuiEventHandlers() {
$("#add-project-button").removeAttr("disabled");
$("#add-project-button").click(function() {
var projectName = prompt("Enter project name:", "");
if (projectName === null) { return; }
var project = new Project(projectName);
projects.add(project);
saveProjects();
});
}
/*
* Initializes a timer used to update project times and detect changes in the
* data stored in the DOM Storage.
*/
function initializeTimer() {
setInterval(function() {
projects.forEach(function(project, index) {
updateProjectRow(findRowWithIndex(index), project);
});
if (projectsHaveChangedOutsideApplication()) {
loadProjects();
}
}, 10 * MILISECONDS_IN_SECOND);
}
/* Initializes the application. */
$(document).ready(function(){
try {
if (!getStorage()) {
alert("Timer requires a browser with DOM Storage support, such as Firefox 3+ or Safari 4+.");
return;
}
} catch (e) {
alert("Timer does not work with file: URLs in Firefox.");
return;
}
initializeProjectsEventHandlers();
loadProjects();
initializeGuiEventHandlers();
initializeTimer();
});
| projectsHaveChangedOutsideApplication |
align_strings.py | import compute_distance_and_align.compute_levenshtein_distance as compute_dist | Calculates minimum edit distance between str1 and str2
and saves backpointers to retrieve the allignments
:param srt seq1: from this s®tring
:param srt seq2: into this string
:returns: edit distance, a tuple of (seq1, changes)
:rtype: a tuple of (seq1, changes)
changes is a string where:
"-": deletion from either seq1 or seq2
a lowercase letter: no editing needed
an uppercase letter: substitution or adding of this letter to seq2
'''
distance = 0
alignment = ""
if len(seq1) == 0 and len(seq2) == 0:
return distance, (alignment, alignment)
elif len(seq1) == 0:
distance = len(seq2)
alignment = seq2.upper()
elif len(seq2) == 0:
distance = len(seq1)
for letter in seq1:
alignment += '-'
elif seq1 == seq2:
distance = 0
alignment = seq1
else:
shortest_dist, table, row, column = compute_dist.compute_levenshtein_distance(seq1, seq2)
while True:
if (row == 0 and column == 0):
break
# Make sure that i or j haven't reached 0'th row or 0'th column
if row != 0 and column != 0 and seq2[row - 1] == seq1[column - 1]:
alignment += seq2[row - 1]
row = row - 1
column = column - 1
elif table[row][column] == (table[row - 1][column - 1] + 1):
alignment += seq2[row - 1].upper()
row = row - 1
column = column - 1
elif table[row][column] == (table[row - 1][column] + 1):
alignment += seq2[row - 1].upper()
row = row - 1
elif table[row][column] == (table[row][column - 1] + 1):
alignment += '-'
column = column - 1
distance = table[row][column]
alignment = alignment[::-1]
return distance, (seq1, alignment)
if __name__ == "__main__":
seq1 = 'abcdef'
seq2 = 'azced'
distance, alignment = align_strings('abcdef', 'azced')
print("\nFrom string: ", seq1, "\nto string:", seq2,
"\nMinimum edit distance:", distance,
"\nChanges:", alignment) |
def align_strings(seq1, seq2):
''' |
user.ts | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../../types";
import * as utilities from "../../utilities";
/**
* Represents a user who has access to one or more shares on the Data Box Edge/Gateway device.
*/
export class User extends pulumi.CustomResource {
/**
* Get an existing User resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
* | * @param id The _unique_ provider ID of the resource to lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): User {
return new User(name, undefined as any, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure-native:databoxedge/v20200901preview:User';
/**
* Returns true if the given object is an instance of User. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is User {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === User.__pulumiType;
}
/**
* The password details.
*/
public readonly encryptedPassword!: pulumi.Output<outputs.databoxedge.v20200901preview.AsymmetricEncryptedSecretResponse | undefined>;
/**
* The object name.
*/
public readonly name!: pulumi.Output<string>;
/**
* List of shares that the user has rights on. This field should not be specified during user creation.
*/
public /*out*/ readonly shareAccessRights!: pulumi.Output<outputs.databoxedge.v20200901preview.ShareAccessRightResponse[]>;
/**
* User in DataBoxEdge Resource
*/
public /*out*/ readonly systemData!: pulumi.Output<outputs.databoxedge.v20200901preview.SystemDataResponse>;
/**
* The hierarchical type of the object.
*/
public /*out*/ readonly type!: pulumi.Output<string>;
/**
* Type of the user.
*/
public readonly userType!: pulumi.Output<string | undefined>;
/**
* Create a User resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: UserArgs, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (!opts.id) {
if ((!args || args.deviceName === undefined) && !opts.urn) {
throw new Error("Missing required property 'deviceName'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
inputs["deviceName"] = args ? args.deviceName : undefined;
inputs["encryptedPassword"] = args ? args.encryptedPassword : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["userType"] = args ? args.userType : undefined;
inputs["shareAccessRights"] = undefined /*out*/;
inputs["systemData"] = undefined /*out*/;
inputs["type"] = undefined /*out*/;
} else {
inputs["encryptedPassword"] = undefined /*out*/;
inputs["name"] = undefined /*out*/;
inputs["shareAccessRights"] = undefined /*out*/;
inputs["systemData"] = undefined /*out*/;
inputs["type"] = undefined /*out*/;
inputs["userType"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
const aliasOpts = { aliases: [{ type: "azure-nextgen:databoxedge/v20200901preview:User" }, { type: "azure-native:databoxedge:User" }, { type: "azure-nextgen:databoxedge:User" }, { type: "azure-native:databoxedge/v20190301:User" }, { type: "azure-nextgen:databoxedge/v20190301:User" }, { type: "azure-native:databoxedge/v20190701:User" }, { type: "azure-nextgen:databoxedge/v20190701:User" }, { type: "azure-native:databoxedge/v20190801:User" }, { type: "azure-nextgen:databoxedge/v20190801:User" }, { type: "azure-native:databoxedge/v20200501preview:User" }, { type: "azure-nextgen:databoxedge/v20200501preview:User" }, { type: "azure-native:databoxedge/v20200901:User" }, { type: "azure-nextgen:databoxedge/v20200901:User" }, { type: "azure-native:databoxedge/v20201201:User" }, { type: "azure-nextgen:databoxedge/v20201201:User" }, { type: "azure-native:databoxedge/v20210201:User" }, { type: "azure-nextgen:databoxedge/v20210201:User" }, { type: "azure-native:databoxedge/v20210201preview:User" }, { type: "azure-nextgen:databoxedge/v20210201preview:User" }] };
opts = pulumi.mergeOptions(opts, aliasOpts);
super(User.__pulumiType, name, inputs, opts);
}
}
/**
* The set of arguments for constructing a User resource.
*/
export interface UserArgs {
/**
* The device name.
*/
deviceName: pulumi.Input<string>;
/**
* The password details.
*/
encryptedPassword?: pulumi.Input<inputs.databoxedge.v20200901preview.AsymmetricEncryptedSecretArgs>;
/**
* The user name.
*/
name?: pulumi.Input<string>;
/**
* The resource group name.
*/
resourceGroupName: pulumi.Input<string>;
/**
* Type of the user.
*/
userType?: pulumi.Input<string | enums.databoxedge.v20200901preview.UserType>;
} | * @param name The _unique_ name of the resulting resource. |
texture.rs | use eyre::Result;
use image::GenericImageView;
pub(crate) struct Texture {
// pub texture: wgpu::Texture,
pub view: wgpu::TextureView,
pub sampler: wgpu::Sampler,
}
impl Texture {
pub fn | (device: &wgpu::Device, queue: &wgpu::Queue, bytes: &[u8]) -> Result<Self> {
let img = image::load_from_memory(bytes)?;
Self::from_image(device, queue, img, None)
}
pub fn from_image(
device: &wgpu::Device,
queue: &wgpu::Queue,
img: image::DynamicImage,
label: Option<&str>,
) -> Result<Self> {
let dimensions = img.dimensions();
let rgba = img.into_rgba();
let size = wgpu::Extent3d {
width: dimensions.0,
height: dimensions.1,
depth: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
label,
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST,
});
queue.write_texture(
wgpu::TextureCopyView {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
},
&rgba,
wgpu::TextureDataLayout {
offset: 0,
bytes_per_row: 4 * dimensions.0,
rows_per_image: dimensions.1,
},
size,
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
Ok(Self {
// texture,
view,
sampler,
})
}
}
| from_bytes |
patch_always_local_delegate.go | package apiserver
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
)
// alwaysLocalDelegatePrefixes specify a list of API paths that we want to delegate to Kubernetes API server
// instead of handling with OpenShift API server.
var alwaysLocalDelegatePathPrefixes = sets.NewString()
// AddAlwaysLocalDelegateForPrefix will cause the given URL prefix always be served by local API server (kube apiserver).
// This allows to move some resources from aggregated API server into CRD.
func AddAlwaysLocalDelegateForPrefix(prefix string) {
if alwaysLocalDelegatePathPrefixes.Has(prefix) {
return
}
alwaysLocalDelegatePathPrefixes.Insert(prefix)
}
var overlappingGroupVersion = map[schema.GroupVersion]bool{}
// AddOverlappingGroupVersion will stop the CRD registration controller from trying to manage an APIService.
func AddOverlappingGroupVersion(groupVersion schema.GroupVersion) |
var alwaysLocalDelegateGroupResource = map[schema.GroupResource]bool{}
func AddAlwaysLocalDelegateGroupResource(groupResource schema.GroupResource) {
alwaysLocalDelegateGroupResource[groupResource] = true
}
func APIServiceAlreadyExists(groupVersion schema.GroupVersion) bool {
if overlappingGroupVersion[groupVersion] {
return true
}
testPrefix := fmt.Sprintf("/apis/%s/%s/", groupVersion.Group, groupVersion.Version)
for _, prefix := range alwaysLocalDelegatePathPrefixes.List() {
if strings.HasPrefix(prefix, testPrefix) {
return true
}
}
return false
}
| {
overlappingGroupVersion[groupVersion] = true
} |
import_data.py | #- * - encoding : utf - 8 - * -
"""
:copyright: 2017-2018 H2O.ai, Inc.
:license: Apache License Version 2.0 (see LICENSE for details)
"""
def | (data_path,
use_pandas=False,
intercept=True,
valid_fraction=0.2,
classification=True):
"""Import Data for H2O GPU Edition
This function will read in data and prepare it for H2O4GPU's GLM solver.
Note, the data is assumed to be all numeric,i.e.,
categoricals are one hot encoded, etc.
:param data_path : str
A path to a dataset (The dataset needs to be all numeric)
:param use_pandas : bool
Indicate if Pandas should be used to parse
:param intercept : bool
Indicate if intercept term is needed
:param valid_fraction : float
Percentage of dataset reserved for a validation set
:param classification : bool
Classification problem?
:returns
If valid_fraction > 0 it will return the following:
train_x: numpy array of train input variables
train_y: numpy array of y variable
valid_x: numpy array of valid input variables
valid_y: numpy array of valid y variable
family : string that would either be "logistic" if classification is set
to True, otherwise "elasticnet"
If valid_fraction == 0 it will return the following:
train_x: numpy array of train input variables
train_y: numpy array of y variable
family : string that would either be "logistic" if classification is set
to True, otherwise "elasticnet"
"""
#Can import data using pandas or feather.
use_pandas = use_pandas
data_file = data_path # If importing using pandas
if use_pandas:
print("Reading Data with Pandas")
import pandas as pd
data = pd.read_csv(data_file)
else:
print("Reading Data with Feather")
import feather
data = feather.read_dataframe(data_file)
print(data.shape)
import numpy as np
data_x = np.array(
data.iloc[:, :data.shape[1] - 1],
dtype='float32',
order='C',
copy=False)
data_y = np.array(
data.iloc[:, data.shape[1] - 1], dtype='float32', order='C', copy=False)
#Setup train / validation set split
#(assuming form of mxn where m = row count and n = col count)
morig = data_x.shape[0]
norig = data_x.shape[1]
print("Original m=%d n=%d" % (morig, norig))
import sys
sys.stdout.flush()
#Do train / valid split
if valid_fraction > 0:
valid_fraction = valid_fraction
HO = int(valid_fraction * morig)
H = morig - HO
print("Size of Train rows=%d & valid rows=%d" % (H, HO))
sys.stdout.flush()
train_x = data_x[0:H, :]
train_y = data_y[0:H]
valid_x = data_x[H:morig, :]
valid_y = data_y[H:morig]
print("Size of Train cols=%d valid cols=%d" % (train_x.shape[1],
valid_x.shape[1]))
else:
train_x = data_x
train_y = data_y
#Using intercept
if intercept:
train_x = np.hstack(
[train_x,
np.ones((train_x.shape[0], 1), dtype=train_x.dtype)])
if valid_fraction > 0:
valid_x = np.hstack(
[valid_x,
np.ones((valid_x.shape[0], 1), dtype=valid_x.dtype)])
print("Size of Train cols=%d & valid cols=%d after adding "
"intercept column" % (train_x.shape[1], valid_x.shape[1]))
else:
print("Size of Train cols=%d after adding intercept column" %
(train_x.shape[1]))
if classification:
family = "logistic"
else:
family = "elasticnet"
if valid_fraction > 0:
return train_x, train_y, valid_x, valid_y, family
return train_x, train_y, family
| import_data |
user.go | package model
import (
"GopherBlog/constant"
"GopherBlog/utils"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// User 用户模型
type User struct {
// gorm.Model是一个包含ID、CreateAt、UpdateAt、DeleteAt字段的结构体,可以内嵌到自定义模型中
// 这样自己的模型就带有ID(主键)、CreateAt、UpdateAt、DeleteAt等的字段
// 自增ID作为主键,默认从1开始自增
gorm.Model
// 1.gorm标签后面的每个子标签名与设置的值格式为 -》 gorm:"tag1:v1;tag2:v2"
// 2.validate标签格式: validate:"tag1,tag2=v2,tag3=v3"
// 3.json标签定义的是结构体转换为json数据时对应的字段名称
// 4.设置结构体时注意字段对应的gorm标签类型,例如什么时候设主键,什么时候需要设置primaryKey,什么时候设not null
Username string `gorm:"type:varchar(20);not null" json:"username" validate:"required,min=4,max=12" label:"用户名"`
Password string `gorm:"type:varchar(20);not null" json:"password" validate:"required,min=6,max=20" label:"密码"`
Role int `gorm:"type:int;default:2" json:"role" validate:"required,gte=2" label:"角色码"`
}
// 用于更新用户信息
type UserEdition struct {
Username string `gorm:"type:varchar(20);not null" json:"username" validate:"min=4,max=12" label:"用户名"`
Role int `gorm:"type:int;default:2" json:"role" label:"角色码"`
}
// IsUserExistsByName 检查用户是否存在
func IsUserExistsByName(name string) bool {
var user User
// 1.字段名用数据库字段名称或者模型中的字段名都可以
//
// 2.Take、First、Find这些函数会根据传入参数选择查询对应的表,例如Take(&user)表示选择user表,并且将查询结果存放到user中
// 因为Take和First只查询单条数据,所以user中会存储查询到的值,也可以用 result := .....Take(&user)来获取查询到的结果数量,
// 但是Find会查询多条数据,需要传入users(user类型的切片)作为参数来存储多个值,result.RowsAffected表示查询到的数据条数
//
// 3.Take相当于:limit 1, First相当于:order by id limit 1, 所以一般Take效率比较高
db.Select("id").Where("username = ?", name).Take(&user)
if user.ID > 0 {
return true
}
return false
}
// CreateUser 创建新用户, 实现BeforeSave和BeforeUpdate接口,对密码进行创建和更新时都会自动进行加密
func CreateUser(data *User) int {
err := db.Create(data).Error
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.CreateUserError), err)
return constant.CreateUserError
}
return constant.SuccessCode
}
// BeforeSave 保存密码到数据库中时,自动对密码进行加密
func (u *User) BeforeSave(_ *gorm.DB) (err error) {
u.Password, err = EncryptPassword(u.Password)
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.SavePasswordError))
return
}
utils.Logger.Info("password: ", u.Password)
return
}
// BeforeUpdate 更新密码在保存到数据库之前自动对密码进行加密
func (u *User) BeforeUpdate(_ *gorm.DB) (err error) {
u.Password, err = EncryptPassword(u.Password)
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.UpdatePasswordError), err)
return
}
return
}
// EncryptPassword 对密码进行bcrypt加密
func EncryptPassword(password string) (string, error) {
const cost = 10
hashPwd, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.EncryptPasswordError), err)
return "", err
}
return string(hashPwd), nil
}
// GetUserInfoById 通过用户ID获取用户数据
func GetUserInfoById(id int) (User, int) {
var user User
// 如果没找到会返回record not found错误
err := db.Where("id = ?", id).Take(&user).Error
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.UserNotExistsError), err)
return user, constant.UserNotExistsError
}
return user, constant.SuccessCode
}
// GetUserList 获取用户列表
// 可能存储非常多的数据,total需要用长整型
func GetUserList(pageSize, pageNum int, username string) (users []map[string]interface{}, total int64, code int) {
if username != "" {
err = db.Model(&User{}) | ername, role").Where(
"username like ?", "%"+username+"%",
).Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users).Error
} else {
err = db.Model(&User{}).Select("id, username, role").Limit(pageSize).Offset(
(pageNum - 1) * pageSize,
).Find(&users).Error
}
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.GetUserListError), err)
return nil, total, constant.GetUserListError
}
total = int64(len(users))
return users, total, constant.SuccessCode
}
// CheckAccount 检查账户密码是否正确
func CheckAccount(username, password string) (user User, code int) {
err = db.Where("username = ?", username).Take(&user).Error
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.DatabaseAccessError), err)
return user, constant.DatabaseAccessError
}
if user.ID == 0 {
utils.Logger.Error(constant.ConvertForLog(constant.UsernameNotExistsError))
return user, constant.UsernameNotExistsError
}
// 判断密码是否是已加密密码对应的明文
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.UserPasswordError), err)
return user, constant.UserPasswordError
}
//if user.Role != 1 {
// utils.Logger.Error(constant.ConvertForLog(constant.UserRoleError), err)
// return user, constant.UserRoleError
//}
return user, constant.SuccessCode
}
// ChangeUserPassword 修改用户密码
// TODO:跟一般的逻辑比是否过于简单
func ChangeUserPassword(id int, data *User) int {
// Select可以选择需要修改的字段, 下面的语句等效于:update user set=xxx where id=yyy
// xxx表示Where中的id,yyy表示data中的ID值
err := db.Select("password").Where("id = ?", id).Updates(&data).Error
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.ChangeUserPasswordError), err)
return constant.ChangeUserPasswordError
}
return constant.SuccessCode
}
// EditUserInfo 编辑用户信息
func EditUserInfo(id int, data *UserEdition) int {
// 判断用户名是否已存在
var user User
err := db.Where("username = ?", data.Username).Take(&user).Error
if err == nil {
utils.Logger.Error(constant.ConvertForLog(constant.UsernameAlreadyExistsError), err)
return constant.UsernameAlreadyExistsError
}
// TODO:传入data和传入&data的区别??
var maps = make(map[string]interface{})
maps["username"] = data.Username
maps["role"] = data.Role
// 假设data中的ID为111, 下面语句相当于update user set username=xxx and role=yyy where id='111'
err = db.Model(&User{}).Where("id = ?", id).Updates(maps).Error
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.EditUserInfoError), err)
return constant.EditUserInfoError
}
return constant.SuccessCode
}
// DeleteUser 删除用户
func DeleteUser(id int) int {
// 如果模型中定义了gorm.DeleteAt字段,则会具有“软删除”功能, 即并不是真正的删除,而是将DeleteAt字段更新为删除语句执行的时间
// 可以通过db.UnScoped().Where()查询软删除的数据,要永久删除可以使用db.UnScoped().Delete()
err := db.Where("id = ?", id).Delete(&User{}).Error
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.DeleteUserError), err)
return constant.DeleteUserError
}
return constant.SuccessCode
}
// IsUserExistById 通过id判断用户是否存在
func IsUserExistsById(id int) bool {
var user User
err := db.Where("id = ?", id).Take(&user).Error
if err != nil {
utils.Logger.Error(constant.ConvertForLog(constant.UserNotExistsError), err)
return false
}
return true
}
| .Select("id, us |
credential_validators.py | # -*- coding: utf-8 -*-
from flask import request, current_app
from domain.models import Image, Document
from validation.base_validators import ParameterizedValidator
import repo
class CanCreateFacilityValidator(ParameterizedValidator):
def validate(self, f, *args, **kwargs):
|
class CanEditFacilityValidator(ParameterizedValidator):
def validate(self, f, *args, **kwargs):
if kwargs.get("facility_id", None): # the normal case: a faility
facility_id = kwargs["facility_id"]
elif kwargs.get("image_id", None): # an image related to a facility
image = current_app.db_session.query(Image).get(kwargs["image_id"])
facility_id = image.facility_id
elif kwargs.get("document_id", None): # a document related to a facility
document = current_app.db_session.query(Document).get(kwargs["document_id"])
facility_id = document.facility_id
elif request.form.get('facilityId', None): # POST image/document with facility id in form
facility_id = request.form.get('facilityId')
#this should cover all cases where this decorator is used
user_id = repo.get_user_id_for_user(cookies=request.cookies)
valid = user_id and repo.can_user_edit_facility(user_id, facility_id,
cookies=request.cookies)
if not valid:
self.fail("You do not have privileges to edit facility %s." % facility_id,
f, 403, None, *args, **kwargs)
| user_id = repo.get_user_id_for_user(cookies=request.cookies)
valid = user_id and repo.can_user_create_facility(user_id, cookies=request.cookies)
if not valid:
self.fail("You do not have privileges to create a facility.",
f, 403, None, *args, **kwargs) |
geojson.rs | use anyhow::Result;
use geojson::Feature;
use abstutil::{Tags, Timer};
use geom::{Distance, GPSBounds, PolyLine};
use crate::geometry::{InputRoad, Results};
use crate::{osm, OriginalRoad, RawMap};
impl RawMap {
pub fn save_osm2polygon_input(&self, output_path: String, i: osm::NodeID) -> Result<()> {
let mut features = Vec::new();
for id in self.roads_per_intersection(i) {
let (untrimmed_center_pts, total_width) = self.untrimmed_road_geometry(id)?;
let mut properties = serde_json::Map::new();
properties.insert("osm_way_id".to_string(), id.osm_way_id.0.into());
properties.insert("src_i".to_string(), id.i1.0.into());
properties.insert("dst_i".to_string(), id.i2.0.into());
properties.insert(
"half_width".to_string(),
(total_width / 2.0).inner_meters().into(),
);
let mut osm_tags = serde_json::Map::new();
for (k, v) in self.roads[&id].osm_tags.inner() {
osm_tags.insert(k.to_string(), v.to_string().into());
}
properties.insert("osm_tags".to_string(), osm_tags.into());
// TODO Both for ror reading and writing, we should find a way to pair a serde struct
// with a geo type
features.push(Feature {
geometry: Some(untrimmed_center_pts.to_geojson(Some(&self.gps_bounds))),
properties: Some(properties),
bbox: None,
id: None,
foreign_members: None,
});
}
// Include extra metadata as GeoJSON foreign members. They'll just show up as a top-level
// key/values on the FeatureCollection
let mut extra_props = serde_json::Map::new();
extra_props.insert("intersection_id".to_string(), i.0.into());
extra_props.insert("min_lon".to_string(), self.gps_bounds.min_lon.into());
extra_props.insert("min_lat".to_string(), self.gps_bounds.min_lat.into());
extra_props.insert("max_lon".to_string(), self.gps_bounds.max_lon.into());
extra_props.insert("max_lat".to_string(), self.gps_bounds.max_lat.into());
let fc = geojson::FeatureCollection {
features,
bbox: None,
foreign_members: Some(extra_props),
};
let gj = geojson::GeoJson::from(fc);
abstio::write_json(output_path, &gj);
Ok(())
}
}
/// Returns the (intersection_id, input roads, and GPS bounds) previously written by
/// `save_osm2polygon_input`.
pub fn read_osm2polygon_input(path: String) -> Result<(osm::NodeID, Vec<InputRoad>, GPSBounds)> {
let geojson: geojson::GeoJson = abstio::maybe_read_json(path, &mut Timer::throwaway())?;
if let geojson::GeoJson::FeatureCollection(collection) = geojson {
let extra_props = collection.foreign_members.as_ref().unwrap();
let gps_bounds = GPSBounds {
min_lon: extra_props.get("min_lon").and_then(|x| x.as_f64()).unwrap(),
min_lat: extra_props.get("min_lat").and_then(|x| x.as_f64()).unwrap(),
max_lon: extra_props.get("max_lon").and_then(|x| x.as_f64()).unwrap(),
max_lat: extra_props.get("max_lat").and_then(|x| x.as_f64()).unwrap(),
};
let intersection_id = osm::NodeID(
extra_props
.get("intersection_id")
.and_then(|x| x.as_i64())
.unwrap(),
);
let mut roads = Vec::new();
for feature in collection.features {
let center_pts = PolyLine::from_geojson(&feature, Some(&gps_bounds))?;
let osm_way_id = feature
.property("osm_way_id")
.and_then(|x| x.as_i64())
.unwrap();
let src_i = feature.property("src_i").and_then(|x| x.as_i64()).unwrap();
let dst_i = feature.property("dst_i").and_then(|x| x.as_i64()).unwrap();
let id = OriginalRoad::new(osm_way_id, (src_i, dst_i));
let half_width = Distance::meters(
feature
.property("half_width")
.and_then(|x| x.as_f64())
.unwrap(),
);
let mut osm_tags = Tags::empty();
for (k, v) in feature
.property("osm_tags")
.and_then(|x| x.as_object())
.unwrap()
{
osm_tags.insert(k, v.as_str().unwrap());
}
roads.push(InputRoad {
id,
center_pts,
half_width,
osm_tags,
});
}
return Ok((intersection_id, roads, gps_bounds));
}
bail!("No FeatureCollection")
}
impl Results {
pub fn save_to_geojson(
&self,
output_path: String,
gps_bounds: &GPSBounds,
debug_output: bool,
) -> Result<()> {
let mut features = Vec::new();
{
let mut properties = serde_json::Map::new();
properties.insert("intersection_id".to_string(), self.intersection_id.0.into());
features.push(Feature {
geometry: Some(self.intersection_polygon.to_geojson(Some(gps_bounds))),
properties: Some(properties),
bbox: None,
id: None,
foreign_members: None,
});
}
for (id, (pl, half_width)) in &self.trimmed_center_pts {
// Add both a line-string and polygon per road
let mut properties = serde_json::Map::new();
properties.insert("osm_way_id".to_string(), id.osm_way_id.0.into());
properties.insert("src_i".to_string(), id.i1.0.into());
properties.insert("dst_i".to_string(), id.i2.0.into());
features.push(Feature {
geometry: Some(pl.to_geojson(Some(gps_bounds))),
properties: Some(properties.clone()),
bbox: None,
id: None,
foreign_members: None,
});
features.push(Feature {
geometry: Some(
pl.make_polygons(2.0 * *half_width)
.to_geojson(Some(gps_bounds)),
),
properties: Some(properties),
bbox: None, |
if debug_output {
for (label, polygon) in &self.debug {
let mut properties = serde_json::Map::new();
properties.insert("debug".to_string(), label.clone().into());
features.push(Feature {
geometry: Some(polygon.to_geojson(Some(gps_bounds))),
properties: Some(properties),
bbox: None,
id: None,
foreign_members: None,
});
}
}
let fc = geojson::FeatureCollection {
features,
bbox: None,
foreign_members: None,
};
abstio::write_json(output_path, &geojson::GeoJson::from(fc));
Ok(())
}
} | id: None,
foreign_members: None,
});
} |
drrn.py | import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from os.path import join as pjoin
from memory import ReplayMemory, Transition, State
from model import DRRN
from util import *
import logger
import sentencepiece as spm
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class DRRN_Agent:
def __init__(self, args):
self.gamma = args.gamma
self.batch_size = args.batch_size
self.sp = spm.SentencePieceProcessor()
self.sp.Load(args.spm_path)
self.network = DRRN(len(self.sp), args.embedding_dim, args.hidden_dim).to(device)
self.memory = ReplayMemory(args.memory_size)
self.save_path = args.output_dir
self.clip = args.clip
self.optimizer = torch.optim.Adam(self.network.parameters(),
lr=args.learning_rate)
def observe(self, state, act, rew, next_state, next_acts, done):
self.memory.push(state, act, rew, next_state, next_acts, done)
def build_state(self, obs, infos):
""" Returns a state representation built from various info sources. """
obs_ids = [self.sp.EncodeAsIds(o) for o in obs]
look_ids = [self.sp.EncodeAsIds(info['look']) for info in infos]
inv_ids = [self.sp.EncodeAsIds(info['inv']) for info in infos]
return [State(ob, lk, inv) for ob, lk, inv in zip(obs_ids, look_ids, inv_ids)]
def encode(self, obs_list):
""" Encode a list of observations """
return [self.sp.EncodeAsIds(o) for o in obs_list]
def act(self, states, poss_acts, sample=True):
""" Returns a string action from poss_acts. """
idxs, values = self.network.act(states, poss_acts, sample)
act_ids = [poss_acts[batch][idx] for batch, idx in enumerate(idxs)]
return act_ids, idxs, values
def update(self):
if len(self.memory) < self.batch_size:
return
transitions = self.memory.sample(self.batch_size)
batch = Transition(*zip(*transitions))
# Compute Q(s', a') for all a'
# TODO: Use a target network???
next_qvals = self.network(batch.next_state, batch.next_acts)
# Take the max over next q-values
next_qvals = torch.tensor([vals.max() for vals in next_qvals], device=device)
# Zero all the next_qvals that are done
next_qvals = next_qvals * (1-torch.tensor(batch.done, dtype=torch.float, device=device))
targets = torch.tensor(batch.reward, dtype=torch.float, device=device) + self.gamma * next_qvals
# Next compute Q(s, a)
# Nest each action in a list - so that it becomes the only admissible cmd
nested_acts = tuple([[a] for a in batch.act])
qvals = self.network(batch.state, nested_acts)
# Combine the qvals: Maybe just do a greedy max for generality
qvals = torch.cat(qvals)
# Compute Huber loss
loss = F.smooth_l1_loss(qvals, targets.detach())
self.optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(self.network.parameters(), self.clip)
self.optimizer.step()
return loss.item()
def load(self):
try:
self.memory = pickle.load(open(pjoin(self.save_path, 'memory.pkl'), 'rb'))
self.network = torch.load(pjoin(self.save_path, 'model.pt'))
except Exception as e:
print("Error saving model.")
logging.error(traceback.format_exc())
def save(self):
| try:
pickle.dump(self.memory, open(pjoin(self.save_path, 'memory.pkl'), 'wb'))
torch.save(self.network, pjoin(self.save_path, 'model.pt'))
except Exception as e:
print("Error saving model.")
logging.error(traceback.format_exc()) |
|
vim_monitor_utils.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import yaml
from oslo_config import cfg
from oslo_log import log as logging
from tacker.common import rpc
from tacker.mistral.actionrpc import kill_action as killaction
from tacker.mistral import mistral_client
from tacker.nfvo.workflows.vim_monitor import workflow_generator
from tacker.vnfm import keystone
LOG = logging.getLogger(__name__)
def get_mistral_client(auth_dict):
return mistral_client.MistralClient(
keystone.Keystone().initialize_client(**auth_dict),
auth_dict['token']).get_client()
def prepare_and_create_workflow(mistral_client, vim_id, action,
kwargs):
wg = workflow_generator.WorkflowGenerator(vim_id, action)
wg.task(**kwargs)
yaml.SafeDumper.ignore_aliases = lambda self, data: True
definition_yaml = yaml.safe_dump(wg.definition, default_flow_style=False)
LOG.debug('vim monitor workflow: %s', definition_yaml)
workflow = mistral_client.workflows.create(definition_yaml)
return {'id': workflow[0].id, 'input': wg.get_input_dict()}
def execute_workflow(mistral_client, workflow):
return mistral_client.executions.create(
wf_identifier=workflow['id'],
workflow_input=workflow['input'],
wf_params={})
def delete_executions(mistral_client, vim_id):
executions = mistral_client.executions.list(
workflow_name='vim_id_' + vim_id)
for execution in executions:
mistral_client.executions.delete(execution.id, force=True)
def | (mistral_client, vim_id):
return mistral_client.workflows.delete('vim_id_' + vim_id)
def monitor_vim(auth_dict, vim_obj):
mc = get_mistral_client(auth_dict)
auth_url = vim_obj["auth_url"]
vim_type = vim_obj['type']
if vim_type == 'openstack':
vim_ip = auth_url.split("//")[-1].split(":")[0].split("/")[0]
elif vim_type == 'kubernetes':
vim_ip = auth_url.split("//")[-1].split(":")[0]
workflow_input_dict = {
'vim_id': vim_obj['id'],
'count': cfg.CONF.vim_monitor.count,
'timeout': cfg.CONF.vim_monitor.timeout,
'interval': cfg.CONF.vim_monitor.interval,
'targetip': vim_ip}
workflow = prepare_and_create_workflow(
mc, vim_obj['id'], 'monitor',
workflow_input_dict)
execute_workflow(mc, workflow)
def kill_action(context, vim_obj):
target = killaction.MistralActionKillRPC.target
rpc_client = rpc.get_client(target)
cctxt = rpc_client.prepare(server=vim_obj['id'])
cctxt.cast(context, 'killAction')
def delete_vim_monitor(context, auth_dict, vim_obj):
mc = get_mistral_client(auth_dict)
delete_executions(mc, vim_obj['id'])
delete_workflow(mc, vim_obj['id'])
kill_action(context, vim_obj)
| delete_workflow |
controllers.py | from fastapi import FastAPI, Depends, Form
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from starlette.templating import Jinja2Templates
from starlette.requests import Request
from starlette.responses import RedirectResponse
from datetime import datetime, timedelta
import db
import hashlib
from mycalendar import MyCalendar
import re
from auth import auth
from models import User, Task
app = FastAPI(
title='FastAPIでつくるToDoアプリケーション',
description='FastAPIチュートリアル:FastAPI(とstarlette)でシンプルなToDoアプリの作成',
version='0.0.1'
)
security = HTTPBasic()
templates = Jinja2Templates(directory="templates")
jinja_env = templates.env
pattern = re.compile(r'\w{4,20}') # 任意の4~20の英数字を示す正規表現
pattern_pw = re.compile(r'\w{6,20}') # 任意の6~20の英数字を示す正規表現
pattern_mail = re.compile(r'^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$') # e-mailの正規表現
def index(request: Request):
return templates.TemplateResponse('index.html',
{'request': request})
def admin(request: Request, credentials: HTTPBasicCredentials = Depends(security)):
username = auth(credentials)
user = db.session.query(User).filter(User.username == username).first()
task = db.session.query(Task).filter(Task.user_id == user.id).all()
db.session.close()
""" [new] 今日の日付と来週の日付"""
today = datetime.now()
next_w = today + timedelta(days=7) # 1週間後の日付
""" [new] カレンダー関連 """
# カレンダーをHTML形式で取得
cal = MyCalendar(username,
{t.deadline.strftime('%Y%m%d'): t.done for t in task}) # 予定がある日付をキーとして渡す
cal = cal.formatyear(today.year, 4) # カレンダーをHTMLで取得
# 直近のタスクだけでいいので、リストを書き換える
task = [t for t in task if today <= t.deadline <= next_w]
links = [t.deadline.strftime('/todo/'+username+'/%Y/%m/%d') for t in task] # 直近の予定リンク
return templates.TemplateResponse('admin.html',
{'request': request,
'user': user,
'task': task,
'links': links,
'calender': cal})
async def register(request: Request):
if request.method == 'GET':
return templates.TemplateResponse('register.html',
{'request': request,
'username': '',
'error': []})
if request.method == 'POST':
data = await request.form()
username = data.get('username')
password = data.get('password')
password_tmp = data.get('password_tmp')
mail = data.get('mail')
error = []
tmp_user = db.session.query(User).filter(User.username == username).first()
if tmp_user is not None:
error.append('同じユーザ名のユーザが存在します。')
if password != password_tmp:
error.append('入力したパスワードが一致しません。')
if pattern.match(username) is None:
error.append('ユーザ名は4~20文字の半角英数字にしてください。')
if pattern_pw.match(password) is None:
error.append('パスワードは6~20文字の半角英数字にしてください。')
if pattern_mail.match(mail) is None:
error.append('正しくメールアドレスを入力してください。')
# エラーがあれば登録ページへ戻す
if error:
return templates.TemplateResponse('register.html',
{'request': request,
'username': username,
'error': error})
# 問題がなければユーザ登録
user = User(username, password, mail)
db.session.add(user)
db.session.commit()
db.session.close()
return templates.TemplateResponse('complete.html',
{'request': request,
'username': username})
def detail(request: Request, username, year, month, day,
credentials: HTTPBasicCredentials = Depends(security)):
username_tmp = auth(credentials)
if username_tmp != username: # もし他のユーザが訪問してきたらはじく
return RedirectResponse('/')
# ログインユーザを取得
user = db.session.query(User).filter(User.username == username).first()
# ログインユーザのタスクを取得
task = db.session.query(Task).filter(Task.user_id == user.id).all()
db.session.close()
# 該当の日付と一致するものだけのリストにする
theday = f'{year}{month.zfill(2)}{day.zfill(2)}' # 月日は0埋めする
task = [t for t in task if t.deadline.strftime('%Y%m%d') == theday]
return templates.TemplateResponse('detail.html',
{'request': request,
'username': username,
'task': task,
'year': year,
'month': month,
'day': day})
async def done(request: Request, credentials: HTTPBasicCredentials = Depends(security)):
username = auth(credentials)
# ユーザ情報を取得
user = db.session.query(User).filter(User.username == username).first()
# ログインユーザのタスクを取得
task = db.session.query(Task).filter(Task.user_id == user.id).all()
# フォームで受け取ったタスクの終了判定を見て内容を変更する
data = await request.form()
t_dones = data.getlist('done[]') # リストとして取得
for t in task:
if str(t.id) in t_dones: # もしIDが一致すれば "終了した予定" とする
t.done = True
db.session.commit() # update!!
db.session.close()
return RedirectResponse('/admin')
async def add(request: Request, credentials: HTTPBasicCredentials = Depends(security)):
username = auth(credentials)
user = db.session.query(User).filter(User.username == username).first()
# フォームからデータを取得
data = await request.form()
print(data)
year = int(data['year'])
month = int(data['month'])
day = int(data['day'])
hour = int(data['hour'])
minute = int(data['minute'])
deadline = datetime(year=year, month=month, day=day,
hour=hour, minute=minute)
# 新しくタスクを生成しコミット
task = Task(user.id, data['content'], deadline)
db.session.add(task)
db.session.commit()
db.session.close()
return RedirectResponse('/admin')
def delete(request: Request, t_id, credentials: HTTPBasicCredentials = Depends(security)):
username = auth(credentials)
user = db.session.query(User).filter(User.username == username).first()
task = db.session.query(Task).filter(Task.id == t_id).first()
# もしユーザIDが異なれば削除せずリダイレクト
if task.user_id != user.id:
return RedirectResponse('/admin')
# 削除してコミット
db.session.delete(task)
db.session.commit()
db.session.close()
return RedirectResponse('/admin')
def get(request: Request, credentials: HTTPBasicCredentials = Depends(security)):
username = auth(credentials)
user = db.session.query(User).filter(User.username == username).first()
task = db.session.query(Task).filter(Task.user_id == user.id).all()
db.session.close()
# JSONフォーマット
task = [{
'id': t.id,
'content': t.content,
'deadline': t.deadline.strftime('%Y-%m-%d %H:%M:%S'),
'published': t.date.strftime('%Y-%m-%d %H:%M:%S'),
'done': t.done,
} for t in task]
return task
async def insert(request: Request,
content: str = Form(...), deadline: str = Form(...),
credentials: HTTPBasicCredentials = Depends(security)):
"""
タスクを追加してJSONで新規タスクを返す。「deadline」は%Y-%m-%d_%H:%M:%S (e.g. 2019-11-03_12:30:00)の形式
"""
|
user = db.session.query(User).filter(User.username == username).first()
task = Task(user.id, content, datetime.strptime(deadline, '%Y-%m-%d_%H:%M:%S'))
db.session.add(task)
db.session.commit()
# テーブルから新しく追加したタスクを取得する
task = db.session.query(Task).all()[-1]
db.session.close()
# 新規タスクをJSONで返す
return {
'id': task.id,
'content': task.content,
'deadline': task.deadline.strftime('%Y-%m-%d %H:%M:%S'),
'published': task.date.strftime('%Y-%m-%d %H:%M:%S'),
'done': task.done,
} | username = auth(credentials)
|
uk.py | import sys
sys.path.append("site-packages")
import json
import string
from unidecode import unidecode
from urllib import parse
from azure.storage.blob import BlockBlobService
from datetime import datetime
import animesources
indexedShows = {}
shows = []
with open('title-map.json') as titlemap_file:
titlemap = json.load(titlemap_file)
with open('multi-season.json') as multiseason_file:
multiseason = json.load(multiseason_file)
with open('azure.json') as azure_file:
azure_storage = json.load(azure_file)
azure_blob = BlockBlobService(account_name=azure_storage['account'], account_key=azure_storage['key'])
with open('proxies.json') as proxies_file:
proxy_data = json.load(proxies_file)
proxy = proxy_data['uk']
sources = [
animesources.Crunchyroll(titlemap, multiseason, 'uk', proxy),
animesources.Funimation(titlemap, multiseason, 'gb', proxy), | animesources.Netflix(titlemap, multiseason, 'uk', proxy),
animesources.HiDive(titlemap, multiseason, 'uk', proxy),
animesources.AmazonPrime(titlemap, multiseason, 'uk', proxy)
]
for source in sources:
source.UpdateShowList(indexedShows)
print(source.GetName() + ': ' + str(len(indexedShows)))
shows = indexedShows.values()
with open('alternates.json') as alternates_file:
alternates = json.load(alternates_file)
for alternate in alternates:
match_index = next((i for i, x in enumerate(shows) if animesources.compare(x['name'], alternate)), False)
if (match_index):
shows[match_index]['alt'] = alternates[alternate]
shows = sorted(shows, key = lambda show: show['name'].lower())
blob = {"lastUpdated": datetime.utcnow().isoformat(), "shows": shows}
out_file = open('uk.json', 'w')
json.dump(blob, out_file)
out_file.close()
azure_blob.create_blob_from_path(
'assets',
'uk.json',
'uk.json'
)
print('done') | |
lib.rs | #[macro_use]
extern crate bitflags;
#[macro_export]
macro_rules! w {
() => {
256
};
(.0) => {
256.0
};
}
#[macro_export]
macro_rules! h {
() => {
256
};
(.0) => {
256.0
};
}
//in pixels
pub const SCREEN_WIDTH: usize = w!();
pub const SCREEN_HEIGHT: usize = h!();
pub const SCREEN_LENGTH: usize = SCREEN_WIDTH * SCREEN_HEIGHT;
#[derive(Clone, Copy, Default, Debug)]
pub struct Input {
pub gamepad: Button::Ty,
pub previous_gamepad: Button::Ty,
}
impl Input {
pub fn new() -> Self {
Input {
gamepad: Button::Ty::empty(),
previous_gamepad: Button::Ty::empty(),
}
}
pub fn pressed_this_frame(&self, buttons: Button::Ty) -> bool {
!self.previous_gamepad.contains(buttons) && self.gamepad.contains(buttons)
}
pub fn | (&self, buttons: Button::Ty) -> bool {
self.previous_gamepad.contains(buttons) && !self.gamepad.contains(buttons)
}
}
//TODO more meaningful names for these?
#[derive(Clone, Copy, Debug)]
pub enum SFX {
Wud,
MovePiece,
}
impl SFX {
pub fn to_sound_key(&self) -> &'static str {
match *self {
SFX::Wud => "wud",
SFX::MovePiece => "movePiece",
}
}
}
pub struct Speaker {
requests: Vec<SFX>,
}
impl Speaker {
pub fn new() -> Self {
Speaker {
requests: Vec::with_capacity(8),
}
}
pub fn request_sfx(&mut self, sfx: SFX) {
self.requests.push(sfx);
}
pub fn drain<'a>(&'a mut self) -> impl Iterator<Item = SFX> + 'a {
self.requests.drain(..)
}
}
// These values are deliberately picked to be the same as the ones in NES' input registers.
#[allow(non_snake_case)]
pub mod Button {
bitflags! {
#[derive(Default)]
pub flags Ty: u8 {
const A = 1 << 0,
const B = 1 << 1,
const Select = 1 << 2,
const Start = 1 << 3,
const Up = 1 << 4,
const Down = 1 << 5,
const Left = 1 << 6,
const Right = 1 << 7
}
}
}
pub type Logger = Option<fn(&str) -> ()>;
pub type StateParams = ([u8; 16], Logger, Logger);
pub trait State {
fn frame(&mut self, handle_sound: fn(SFX));
fn press(&mut self, button: Button::Ty);
fn release(&mut self, button: Button::Ty);
fn get_frame_buffer(&self) -> &[u32];
fn update_bytes(&mut self, bytes: Vec<u8>);
}
| released_this_frame |
kendo.validator.js | /**
* Copyright 2018 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function (f, define) {
define('kendo.validator', ['kendo.core'], f);
}(function () {
var __meta__ = {
id: 'validator',
name: 'Validator',
category: 'web',
description: 'The Validator offers an easy way to do a client-side form validation.',
depends: ['core']
};
(function ($, undefined) {
var kendo = window.kendo, Widget = kendo.ui.Widget, NS = '.kendoValidator', INVALIDMSG = 'k-invalid-msg', invalidMsgRegExp = new RegExp(INVALIDMSG, 'i'), INVALIDINPUT = 'k-invalid', VALIDINPUT = 'k-valid', emailRegExp = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/i, urlRegExp = /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, INPUTSELECTOR = ':input:not(:button,[type=submit],[type=reset],[disabled],[readonly])', CHECKBOXSELECTOR = ':checkbox:not([disabled],[readonly])', NUMBERINPUTSELECTOR = '[type=number],[type=range]', BLUR = 'blur', NAME = 'name', FORM = 'form', NOVALIDATE = 'novalidate', VALIDATE = 'validate', CHANGE = 'change', VALIDATE_INPUT = 'validateInput', proxy = $.proxy, patternMatcher = function (value, pattern) {
if (typeof pattern === 'string') {
pattern = new RegExp('^(?:' + pattern + ')$');
}
return pattern.test(value);
}, matcher = function (input, selector, pattern) {
var value = input.val();
if (input.filter(selector).length && value !== '') {
return patternMatcher(value, pattern);
}
return true;
}, hasAttribute = function (input, name) {
if (input.length) {
return input[0].attributes[name] != null;
}
return false;
};
if (!kendo.ui.validator) {
kendo.ui.validator = {
rules: {},
messages: {}
};
}
function resolveRules(element) {
var resolvers = kendo.ui.validator.ruleResolvers || {}, rules = {}, name;
for (name in resolvers) {
$.extend(true, rules, resolvers[name].resolve(element));
}
return rules;
}
function | (value) {
return value.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, '\'').replace(/</g, '<').replace(/>/g, '>');
}
function numberOfDecimalDigits(value) {
value = (value + '').split('.');
if (value.length > 1) {
return value[1].length;
}
return 0;
}
function parseHtml(text) {
if ($.parseHTML) {
return $($.parseHTML(text));
}
return $(text);
}
function searchForMessageContainer(elements, fieldName) {
var containers = $(), element, attr;
for (var idx = 0, length = elements.length; idx < length; idx++) {
element = elements[idx];
if (invalidMsgRegExp.test(element.className)) {
attr = element.getAttribute(kendo.attr('for'));
if (attr === fieldName) {
containers = containers.add(element);
}
}
}
return containers;
}
var Validator = Widget.extend({
init: function (element, options) {
var that = this, resolved = resolveRules(element), validateAttributeSelector = '[' + kendo.attr('validate') + '!=false]';
options = options || {};
options.rules = $.extend({}, kendo.ui.validator.rules, resolved.rules, options.rules);
options.messages = $.extend({}, kendo.ui.validator.messages, resolved.messages, options.messages);
Widget.fn.init.call(that, element, options);
that._errorTemplate = kendo.template(that.options.errorTemplate);
if (that.element.is(FORM)) {
that.element.attr(NOVALIDATE, NOVALIDATE);
}
that._inputSelector = INPUTSELECTOR + validateAttributeSelector;
that._checkboxSelector = CHECKBOXSELECTOR + validateAttributeSelector;
that._errors = {};
that._attachEvents();
that._isValidated = false;
},
events: [
VALIDATE,
CHANGE,
VALIDATE_INPUT
],
options: {
name: 'Validator',
errorTemplate: '<span class="k-widget k-tooltip k-tooltip-validation">' + '<span class="k-icon k-i-warning"> </span> #=message#</span>',
messages: {
required: '{0} is required',
pattern: '{0} is not valid',
min: '{0} should be greater than or equal to {1}',
max: '{0} should be smaller than or equal to {1}',
step: '{0} is not valid',
email: '{0} is not valid email',
url: '{0} is not valid URL',
date: '{0} is not valid date',
dateCompare: 'End date should be greater than or equal to the start date'
},
rules: {
required: function (input) {
var checkbox = input.filter('[type=checkbox]').length && !input.is(':checked'), value = input.val();
return !(hasAttribute(input, 'required') && (!value || value === '' || value.length === 0 || checkbox));
},
pattern: function (input) {
if (input.filter('[type=text],[type=email],[type=url],[type=tel],[type=search],[type=password]').filter('[pattern]').length && input.val() !== '') {
return patternMatcher(input.val(), input.attr('pattern'));
}
return true;
},
min: function (input) {
if (input.filter(NUMBERINPUTSELECTOR + ',[' + kendo.attr('type') + '=number]').filter('[min]').length && input.val() !== '') {
var min = parseFloat(input.attr('min')) || 0, val = kendo.parseFloat(input.val());
return min <= val;
}
return true;
},
max: function (input) {
if (input.filter(NUMBERINPUTSELECTOR + ',[' + kendo.attr('type') + '=number]').filter('[max]').length && input.val() !== '') {
var max = parseFloat(input.attr('max')) || 0, val = kendo.parseFloat(input.val());
return max >= val;
}
return true;
},
step: function (input) {
if (input.filter(NUMBERINPUTSELECTOR + ',[' + kendo.attr('type') + '=number]').filter('[step]').length && input.val() !== '') {
var min = parseFloat(input.attr('min')) || 0, step = parseFloat(input.attr('step')) || 1, val = parseFloat(input.val()), decimals = numberOfDecimalDigits(step), raise;
if (decimals) {
raise = Math.pow(10, decimals);
return Math.floor((val - min) * raise) % (step * raise) / Math.pow(100, decimals) === 0;
}
return (val - min) % step === 0;
}
return true;
},
email: function (input) {
return matcher(input, '[type=email],[' + kendo.attr('type') + '=email]', emailRegExp);
},
url: function (input) {
return matcher(input, '[type=url],[' + kendo.attr('type') + '=url]', urlRegExp);
},
date: function (input) {
if (input.filter('[type^=date],[' + kendo.attr('type') + '=date]').length && input.val() !== '') {
return kendo.parseDate(input.val(), input.attr(kendo.attr('format'))) !== null;
}
return true;
}
},
validateOnBlur: true
},
destroy: function () {
Widget.fn.destroy.call(this);
this.element.off(NS);
},
value: function () {
if (!this._isValidated) {
return false;
}
return this.errors().length === 0;
},
_submit: function (e) {
if (!this.validate()) {
e.stopPropagation();
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
return true;
},
_checkElement: function (element) {
var state = this.value();
this.validateInput(element);
if (this.value() !== state) {
this.trigger(CHANGE);
}
},
_attachEvents: function () {
var that = this;
if (that.element.is(FORM)) {
that.element.on('submit' + NS, proxy(that._submit, that));
}
if (that.options.validateOnBlur) {
if (!that.element.is(INPUTSELECTOR)) {
that.element.on(BLUR + NS, that._inputSelector, function () {
that._checkElement($(this));
});
that.element.on('click' + NS, that._checkboxSelector, function () {
that._checkElement($(this));
});
} else {
that.element.on(BLUR + NS, function () {
that._checkElement(that.element);
});
if (that.element.is(CHECKBOXSELECTOR)) {
that.element.on('click' + NS, function () {
that._checkElement(that.element);
});
}
}
}
},
validate: function () {
var inputs;
var idx;
var result = false;
var length;
var isValid = this.value();
this._errors = {};
if (!this.element.is(INPUTSELECTOR)) {
var invalid = false;
inputs = this.element.find(this._inputSelector);
for (idx = 0, length = inputs.length; idx < length; idx++) {
if (!this.validateInput(inputs.eq(idx))) {
invalid = true;
}
}
result = !invalid;
} else {
result = this.validateInput(this.element);
}
this.trigger(VALIDATE, { valid: result });
if (isValid !== result) {
this.trigger(CHANGE);
}
return result;
},
validateInput: function (input) {
input = $(input);
this._isValidated = true;
var that = this, template = that._errorTemplate, result = that._checkValidity(input), valid = result.valid, className = '.' + INVALIDMSG, fieldName = input.attr(NAME) || '', lbl = that._findMessageContainer(fieldName).add(input.next(className).filter(function () {
var element = $(this);
if (element.filter('[' + kendo.attr('for') + ']').length) {
return element.attr(kendo.attr('for')) === fieldName;
}
return true;
})).hide(), messageText, wasValid = !input.attr('aria-invalid');
input.removeAttr('aria-invalid');
if (!valid) {
messageText = that._extractMessage(input, result.key);
that._errors[fieldName] = messageText;
var messageLabel = parseHtml(template({ message: decode(messageText) }));
var lblId = lbl.attr('id');
that._decorateMessageContainer(messageLabel, fieldName);
if (lblId) {
messageLabel.attr('id', lblId);
}
if (!lbl.replaceWith(messageLabel).length) {
messageLabel.insertAfter(input);
}
messageLabel.show();
input.attr('aria-invalid', true);
} else {
delete that._errors[fieldName];
}
if (wasValid !== valid) {
this.trigger(VALIDATE_INPUT, {
valid: valid,
input: input
});
}
input.toggleClass(INVALIDINPUT, !valid);
input.toggleClass(VALIDINPUT, valid);
return valid;
},
hideMessages: function () {
var that = this, className = '.' + INVALIDMSG, element = that.element;
if (!element.is(INPUTSELECTOR)) {
element.find(className).hide();
} else {
element.next(className).hide();
}
},
_findMessageContainer: function (fieldName) {
var locators = kendo.ui.validator.messageLocators, name, containers = $();
for (var idx = 0, length = this.element.length; idx < length; idx++) {
containers = containers.add(searchForMessageContainer(this.element[idx].getElementsByTagName('*'), fieldName));
}
for (name in locators) {
containers = containers.add(locators[name].locate(this.element, fieldName));
}
return containers;
},
_decorateMessageContainer: function (container, fieldName) {
var locators = kendo.ui.validator.messageLocators, name;
container.addClass(INVALIDMSG).attr(kendo.attr('for'), fieldName || '');
for (name in locators) {
locators[name].decorate(container, fieldName);
}
container.attr('role', 'alert');
},
_extractMessage: function (input, ruleKey) {
var that = this, customMessage = that.options.messages[ruleKey], fieldName = input.attr(NAME), nonDefaultMessage;
if (!kendo.ui.Validator.prototype.options.messages[ruleKey]) {
nonDefaultMessage = kendo.isFunction(customMessage) ? customMessage(input) : customMessage;
}
customMessage = kendo.isFunction(customMessage) ? customMessage(input) : customMessage;
return kendo.format(input.attr(kendo.attr(ruleKey + '-msg')) || input.attr('validationMessage') || nonDefaultMessage || input.attr('title') || customMessage || '', fieldName, input.attr(ruleKey) || input.attr(kendo.attr(ruleKey)));
},
_checkValidity: function (input) {
var rules = this.options.rules, rule;
for (rule in rules) {
if (!rules[rule].call(this, input)) {
return {
valid: false,
key: rule
};
}
}
return { valid: true };
},
errors: function () {
var results = [], errors = this._errors, error;
for (error in errors) {
results.push(errors[error]);
}
return results;
}
});
kendo.ui.plugin(Validator);
}(window.kendo.jQuery));
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function (a1, a2, a3) {
(a3 || a2)();
})); | decode |
native.py | import torch
from .observation_type import ObservationType
import torch.nn.qat as nnqat
def | ():
""" Get backend for PyTorch Native backend_config_dict (fbgemm/qnnpack)
"""
# dtype configs
# weighted op int8 config
# activation: quint8, weight: qint8, bias: float
weighted_op_int8_dtype_config = {
# optional, input activation dtype
"input_dtype": torch.quint8,
# optional, weight dtype
"weight_dtype": torch.qint8,
# optional, bias dtype
"bias_dtype": torch.float,
# optional, output activation dtype
"output_dtype": torch.quint8
}
# operator (module/functional/torch ops) configs
linear_module_config = {
# Please see README under this folder for pattern format
"pattern": torch.nn.Linear,
"observation_type": ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
"dtype_configs": [
weighted_op_int8_dtype_config,
],
# the root module for the pattern, used to query the reference quantized module
# e.g. for a (torch.nn.ReLU, torch.nn.Linear) pattern, the root will be torch.nn.Linear
"root_module": torch.nn.Linear,
# the corresponding reference quantized module for the root module
"reference_quantized_module_for_root": torch.nn.quantized._reference.Linear,
"qat_module": nnqat.Linear,
}
return {
# optional
"name": "native",
"configs": [
linear_module_config,
],
}
| get_native_backend_config_dict |
RequestManager.py | import requests
import config
import datetime
import os
import json
import copy
from constants import *
class RequestManager:
"""A class that handles submitting TiIndicators to MS Graph API
to use the class:
with RequestManager() as request_manager:
request_manager.handle_indicator(tiindicator)
"""
RJUST = 5
def __init__(self, total_indicators):
self.total_indicators = total_indicators
def __enter__(self):
try:
self.existing_indicators_hash_fd = open(EXISTING_INDICATORS_HASH_FILE_NAME, 'r+')
self.existing_indicators_hash = json.load(self.existing_indicators_hash_fd)
except (FileNotFoundError, json.decoder.JSONDecodeError):
self.existing_indicators_hash_fd = open(EXISTING_INDICATORS_HASH_FILE_NAME, 'w')
self.existing_indicators_hash = {}
try:
self.expiration_date_fd = open(EXPIRATION_DATE_FILE_NAME, 'r+')
self.expiration_date = self.expiration_date_fd.read()
except FileNotFoundError:
self.expiration_date_fd = open(EXPIRATION_DATE_FILE_NAME, 'w')
self.expiration_date = self._get_expiration_date_from_config()
if self.expiration_date <= datetime.datetime.utcnow().strftime('%Y-%m-%d'):
self.existing_indicators_hash = {}
self.expiration_date = self._get_expiration_date_from_config()
self.hash_of_indicators_to_delete = copy.deepcopy(self.existing_indicators_hash)
print(f"hash of indicators to delete {self.hash_of_indicators_to_delete}")
access_token = self._get_access_token(
config.graph_auth[TENANT],
config.graph_auth[CLIENT_ID],
config.graph_auth[CLIENT_SECRET])
self.headers = {"Authorization": f"Bearer {access_token}", 'user-agent': 'MISP/1.0'}
self.headers_expiration_time = self._get_timestamp() + 3500
self.success_count = 0
self.error_count = 0
self.del_count = 0
self.indicators_to_be_sent = []
self.indicators_to_be_sent_size = 0
self.start_time = self.last_batch_done_timestamp = self._get_timestamp()
if not os.path.exists(LOG_DIRECTORY_NAME):
os.makedirs(LOG_DIRECTORY_NAME)
return self
@staticmethod
def _get_expiration_date_from_config():
return (datetime.datetime.utcnow() + datetime.timedelta(config.days_to_expire)).strftime('%Y-%m-%d')
@staticmethod
def _get_access_token(tenant, client_id, client_secret):
data = {
CLIENT_ID: client_id,
'scope': 'https://graph.microsoft.com/.default',
CLIENT_SECRET: client_secret,
'grant_type': 'client_credentials'
}
access_token = requests.post(
f'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token',
data=data
).json()[ACCESS_TOKEN]
return access_token
@staticmethod
def read_tiindicators():
access_token = RequestManager._get_access_token(
config.graph_auth[TENANT],
config.graph_auth[CLIENT_ID],
config.graph_auth[CLIENT_SECRET])
print(json.dumps(requests.get(
GRAPH_TI_INDICATORS_URL,
headers={"Authorization": f"Bearer {access_token}"}
).json(), indent=2))
@staticmethod
def _get_request_hash(request):
return str(hash(frozenset({
k: str(v) for k, v in request.items()
if k != 'expirationDateTime' and k != 'lastReportedDateTime'
}.items())))
def _log_post(self, response):
self._clear_screen()
cur_batch_success_count = cur_batch_error_count = 0
print(f"response: {response}")
if len(response['value']) > 0:
for value in response['value']:
if "Error" in value:
self.error_count += 1
cur_batch_error_count += 1
log_file_name = f"{self._get_datetime_now()}_error_{value[INDICATOR_REQUEST_HASH]}.json"
else:
self.success_count += 1
cur_batch_success_count += 1
self.existing_indicators_hash[value[INDICATOR_REQUEST_HASH]] = value['id']
# if not config.verbose_log:
# continue
log_file_name = f"{self._get_datetime_now()}_{value[INDICATOR_REQUEST_HASH]}.json"
json.dump(value, open(f'{LOG_DIRECTORY_NAME}/{log_file_name}', 'w'), indent=2)
print('sending security indicators to Microsoft Graph Security\n')
print(f'{self.total_indicators} indicators are parsed from misp events. Only those that do not exist in Microsoft Graph Security will be sent.\n')
print(f"current batch indicators sent: {str(cur_batch_success_count + cur_batch_error_count).rjust(self.RJUST)}")
print(f"current batch response success: {str(cur_batch_success_count).rjust(self.RJUST)}")
print(f"current batch response error: {str(cur_batch_error_count).rjust(self.RJUST)}\n")
#print(f"total indicators sent: {str(self._get_total_indicators_sent()).rjust(self.RJUST)}")
#print(f"total response success: {str(self.success_count).rjust(self.RJUST)}")
#print(f"total response error: {str(self.error_count).rjust(self.RJUST)}\n")
##cur_batch_took = self._get_timestamp() - self.last_batch_done_timestamp
##self.last_batch_done_timestamp = self._get_timestamp()
##print(f'current batch took: {round(cur_batch_took, 2):{6}} seconds')
# avg_speed = self._get_total_indicators_sent() / (self.last_batch_done_timestamp - self.start_time)
# print(f'average speed so far: {round(avg_speed, 2):{6}} indicators per second')
# time_left = (self.total_indicators - self._get_total_indicators_sent()) / avg_speed
# print(f'estimated time left: {round(time_left, 2):{6}} seconds')
@staticmethod
def _get_datetime_now():
return str(datetime.datetime.now()).replace(' ', '_')
def __exit__(self, exc_type, exc_val, exc_tb):
if config.targetProduct in TARGET_PRODUCT_BULK_SUPPORT:
self._post_to_graph()
else:
self._post_one_to_graph()
self._del_indicators_no_longer_exist()
self.expiration_date_fd.seek(0)
self.expiration_date_fd.write(self.expiration_date)
self.expiration_date_fd.truncate()
self.existing_indicators_hash_fd.seek(0)
json.dump(self.existing_indicators_hash, self.existing_indicators_hash_fd, indent=2)
self.existing_indicators_hash_fd.truncate()
self._print_summary()
def _del_indicators_no_longer_exist(self):
indicators = list(self.hash_of_indicators_to_delete.values())
self.del_count = len(indicators)
for i in range(0, len(indicators), 100):
request_body = {'value': indicators[i: i+100]}
response = requests.post(GRAPH_BULK_DEL_URL, headers=self.headers, json=request_body).json()
log_file_name = f"del_{self._get_datetime_now()}.json"
print(log_file_name)
print(json.dumps(response, indent=2))
print()
json.dump(response, open(f'{LOG_DIRECTORY_NAME}/{log_file_name}', 'w'), indent=2)
for hash_of_indicator_to_delete in self.hash_of_indicators_to_delete.keys():
self.existing_indicators_hash.pop(hash_of_indicator_to_delete, None)
def _print_summary(self):
self._clear_screen()
print('script finished running\n')
#print(f"total indicators sent: {str(self._get_total_indicators_sent()).rjust(self.RJUST)}")
#print(f"total response success: {str(self.success_count).rjust(self.RJUST)}")
#print(f"total response error: {str(self.error_count).rjust(self.RJUST)}")
print(f"total indicators deleted: {str(self.del_count).rjust(self.RJUST)}")
def _post_one_to_graph(self):
for indicator in self.indicators_to_be_sent:
request_body = indicator
response = requests.post(GRAPH_TI_INDICATORS_URL, headers=self.headers, json=request_body).json()
self.indicators_to_be_sent = []
self._log_post(response)
def _post_to_graph(self):
request_body = {'value': self.indicators_to_be_sent}
response = requests.post(GRAPH_BULK_POST_URL, headers=self.headers, json=request_body).json()
self.indicators_to_be_sent = []
self._log_post(response)
def handle_indicator(self, indicator):
self._update_headers_if_expired()
indicator[EXPIRATION_DATE_TIME] = self.expiration_date
indicator_hash = self._get_request_hash(indicator)
indicator[INDICATOR_REQUEST_HASH] = indicator_hash
self.hash_of_indicators_to_delete.pop(indicator_hash, None)
if indicator_hash not in self.existing_indicators_hash:
self.indicators_to_be_sent.append(indicator)
print(f"number of indicators to be sent: {len(self.indicators_to_be_sent)}")
if len(self.indicators_to_be_sent) >= 100:
if config.targetProduct in TARGET_PRODUCT_BULK_SUPPORT:
self._post_to_graph()
else:
self._post_one_to_graph()
def _update_headers_if_expired(self):
if self._get_timestamp() > self.headers_expiration_time:
access_token = self._get_access_token(
config.graph_auth[TENANT],
config.graph_auth[CLIENT_ID],
config.graph_auth[CLIENT_SECRET])
self.headers = {"Authorization": f"Bearer {access_token}"}
@staticmethod
def _clear_screen():
if os.name == 'posix':
|
else:
os.system('cls')
@staticmethod
def _get_timestamp():
return datetime.datetime.now().timestamp()
def _get_total_indicators_sent(self):
return self.error_count + self.success_count
| os.system('clear') |
park_android.py | #!/usr/bin/env python
import rospy
import roslib
import tf
import sys
from std_msgs.msg import Float32
import os.path, time
from geometry_msgs.msg import PoseStamped
def | ():
file = open('Parking_Info.txt', 'r')
carname = file.read()
value = carname[4]
carname = carname[0:4]
value = float(value)
file.close()
time_initial = time.ctime(os.path.getmtime('Parking_Info.txt'))
## Three Publishers for car1, car2 and car3 to tell whether to park or unpark and which car.
publisher_topic1 = 'car1/Park'
pub1 = rospy.Publisher(publisher_topic1, Float32)
publisher_topic2 = 'car2/Park'
pub2 = rospy.Publisher(publisher_topic2, Float32)
publisher_topic3 = 'car3/Park'
pub3 = rospy.Publisher(publisher_topic3, Float32)
##
## Publishing goals for different cars
goal1 = 'car1/move_base_simple/goal'
pub_goal1 = rospy.Publisher(goal1, PoseStamped)
goal2 = 'car2/move_base_simple/goal'
pub_goal2 = rospy.Publisher(goal2, PoseStamped)
goal3 = 'car3/move_base_simple/goal'
pub_goal3 = rospy.Publisher(goal3, PoseStamped)
rospy.init_node('park_android')
current_time = rospy.get_rostime();
# Goal Spot
goal_spot = PoseStamped()
goal_spot.header.stamp = current_time;
goal_spot.header.frame_id = "/map";
print "CN: ", carname
while not rospy.is_shutdown():
time_modified = time.ctime(os.path.getmtime('Parking_Info.txt'))
# when the file "Parking_Info.txt" is changed that means command is received from the mobile
if (time_initial != time_modified):
time_initial = time_modified
time.sleep(3)
file = open('Parking_Info.txt', 'r')
carname = file.read()
value = carname[4]
carname = carname[0:4]
value = float(value)
print "Va: ", value
if value == 1.0:
print "AA"
files = '/home/naman/Desktop/AutoParking/parkcoord.txt'
coordinates = open(files,'r');
px = float(coordinates.readline());
py = float(coordinates.readline());
pz = float(coordinates.readline());
angle = float(coordinates.readline());
goal_spot.pose.position.x = px;
goal_spot.pose.position.y = py;
goal_spot.pose.position.z = pz;
if angle==0:
goal_spot.pose.orientation.x = 0;
goal_spot.pose.orientation.y = 0;
goal_spot.pose.orientation.z = -0;
goal_spot.pose.orientation.w = 1;
elif angle==180:
goal_spot.pose.orientation.x = 0;
goal_spot.pose.orientation.y = 0;
goal_spot.pose.orientation.z = 1;
goal_spot.pose.orientation.w = -0;
elif angle==90:
goal_spot.pose.orientation.x = 0;
goal_spot.pose.orientation.y = 0;
goal_spot.pose.orientation.z = 0.706;
goal_spot.pose.orientation.w = 0.709;
elif angle==-90:
goal_spot.pose.orientation.x = 0;
goal_spot.pose.orientation.y = 0;
goal_spot.pose.orientation.z = -0.706;
goal_spot.pose.orientation.w = 0.709;
if value == 0.0:
print "BB"
files = '/home/naman/Desktop/AutoParking/exitcoord.txt'
coordinates = open(files,'r');
px = float(coordinates.readline());
py = float(coordinates.readline());
pz = float(coordinates.readline());
angle = float(coordinates.readline());
goal_spot.pose.position.x = px;
goal_spot.pose.position.y = py;
goal_spot.pose.position.z = pz;
if angle==0:
goal_spot.pose.orientation.x = 0;
goal_spot.pose.orientation.y = 0;
goal_spot.pose.orientation.z = -0;
goal_spot.pose.orientation.w = 1;
elif angle==180:
goal_spot.pose.orientation.x = 0;
goal_spot.pose.orientation.y = 0;
goal_spot.pose.orientation.z = 1;
goal_spot.pose.orientation.w = -0;
elif angle==90:
goal_spot.pose.orientation.x = 0;
goal_spot.pose.orientation.y = 0;
goal_spot.pose.orientation.z = 0.706;
goal_spot.pose.orientation.w = 0.709;
elif angle==-90:
goal_spot.pose.orientation.x = 0;
goal_spot.pose.orientation.y = 0;
goal_spot.pose.orientation.z = -0.706;
goal_spot.pose.orientation.w = 0.709;
print goal_spot
if carname == "car1":
print "X"
rospy.loginfo(value)
pub1.publish(value)
rospy.sleep(5.0)
pub_goal1.publish(goal_spot)
if carname == "car2":
print "Y"
rospy.loginfo(value)
pub2.publish(value)
rospy.sleep(5.0)
pub_goal2.publish(goal_spot)
if carname == "car3":
print "Z"
rospy.loginfo(value)
pub3.publish(value)
rospy.sleep(5.0)
pub_goal3.publish(goal_spot)
file.close()
if __name__ == '__main__':
try:
park_android()
except rospy.ROSInterruptException:
pass
| park_android |
IssueDetails.js | /**
* Browse issue details and allow to put comment.
*/
import React, { useState, useEffect } from 'react';
import {
Text, SafeAreaView, Keyboard,
TouchableWithoutFeedback, Platform,
StyleSheet, ScrollView, View,
FlatList, TextInput, Button, ActivityIndicator,
KeyboardAvoidingView
} from 'react-native';
import 'react-native-get-random-values';
import { v4 as uuid } from 'uuid';
import { rowSeparatorView } from '../components/atoms/rowSeparatorView';
import StorageService from '../services/StorageService';
export const IssueDetails = ({ route }) => {
const [comments, setComments] = useState([]);
const [commentText, setCommentText] = useState('');
const [isSavingComment, setIsSavingComment] = useState(false);
let issue = route.params.issue;
let commentsText = 'List of comments:';
let saveCommentText = 'Save comment';
let infoText = 'Please write comment below:';
let helpDefaultText = 'Comment...';
useEffect(() => {
getData()
}, []);
const onSaveCommentPressed = () => {
try {
if (!commentText)
return;
setIsSavingComment(true);
saveData(issue.id);
getData();
}
catch (error) {
console.error('Exception on saving comment');
console.error(error);
}
finally {
setTimeout(() => {
setIsSavingComment(false);
setCommentText('');
}, 1000);
}
}
const saveData = async (id) => {
let updatedComments = comments;
updatedComments.push({ id: uuid(), comment: commentText });
const jsonValue = JSON.stringify(updatedComments);
StorageService.saveComments(id, jsonValue);
}
const getData = async () => {
try {
const userAge = await StorageService.readComments(issue.id);
var val = JSON.parse(userAge);
if (userAge !== null) {
setComments(val);
}
}
catch (error) {
console.error('Exception on saving comment');
console.error(error);
alert('Failed to get data from storage.');
}
}
const getItemView = ({ item }) => {
return (
<View style={styles.itemStyle}>
<Text style={styles.itemTextStyle}>{item.comment}</Text>
</View>
);
};
return (
<SafeAreaView style={styles.containerMain}>
<View style={styles.absoluteCenter}>{isSavingComment && (
<ActivityIndicator />)}
</View>
<ScrollView style={styles.sectionIssue}>
<Text style={styles.textDescriptionn}>Id: {issue.id}</Text>
<Text style={styles.textDescriptionn}>State: {issue.state}</Text>
<Text style={styles.textDescriptionn}>Title: {issue.title}</Text>
<Text style={styles.textDescriptionn}>Body: {issue.body}</Text>
</ScrollView>
<View style={styles.sectionCommentList}>
<Text style={styles.textCenter}>{commentsText}</Text>
<FlatList
data={comments}
keyExtractor={item => item.id}
ItemSeparatorComponent={rowSeparatorView}
renderItem={getItemView} />
</View>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
keyboardVerticalOffset={
Platform.select({
ios: () => 0,
android: () => 100
})()
}
style={styles.focusableKeyboardStyle}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.focusableViewStyle}>
<Text style={styles.textCenter}>{infoText}</Text>
<TextInput | onChangeText={setCommentText}
helpDefaultText={helpDefaultText}
value={commentText} />
<Button
disabled={isSavingComment}
title={saveCommentText}
onPress={onSaveCommentPressed}
/>
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</SafeAreaView>)
};
const styles = StyleSheet.create({
absoluteCenter: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
justifyContent: 'center',
alignItems: 'center'
},
containerMain: {
flex: 1,
flexDirection: 'column',
marginHorizontal: 8
},
sectionIssue: {
flex: 1,
marginVertical: 16
},
sectionCommentList: {
flex: 0.5,
maxHeight: 300,
height: 300,
},
sectionComment: {
marginVertical: 36,
},
inputStyle: {
height: 50,
marginVertical: 16,
borderBottomWidth: 1
},
textCenter: {
textAlign: 'center',
},
itemStyle: {
justifyContent: 'center',
height: 30
},
itemTextStyle: {
textAlign: 'center',
marginLeft: 16,
},
focusableKeyboardStyle: {
flex: 1,
justifyContent: 'center'
},
focusableViewStyle: {
padding: 24,
flex: 1,
justifyContent: 'space-around'
},
}); | style={styles.inputStyle}
multiline={false} |
prompt.go | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package prompt
import (
"github.com/ZupIT/ritchie-cli/pkg/formula"
)
| type InputTextValidator interface {
Text(name string, validate func(interface{}) error, helper ...string) (string, error)
}
type InputBool interface {
Bool(name string, items []string, helper ...string) (bool, error)
}
type InputPassword interface {
Password(label string, helper ...string) (string, error)
}
type InputMultiline interface {
MultiLineText(name string, required bool) (string, error)
}
type InputList interface {
List(name string, items []string, helper ...string) (string, error)
}
type InputInt interface {
Int(name string, helper ...string) (int64, error)
}
type InputEmail interface {
Email(name string) (string, error)
}
type InputURL interface {
URL(name, defaultValue string) (string, error)
}
type InputMultiselect interface {
Multiselect(input formula.Input) ([]string, error)
} | type InputText interface {
Text(name string, required bool, helper ...string) (string, error)
}
|
util.go | package mocktest
import (
"bytes"
"github.com/chubaofs/chubaofs/proto"
"net"
"net/http"
"time"
)
const (
ColonSeparator = ":"
hostAddr = "http://127.0.0.1:8080"
urlAddDataNode = hostAddr + "/dataNode/add"
urlAddMetaNode = hostAddr + "/metaNode/add"
// Operation response
urlMetaNodeResponse = hostAddr + "/metaNode/response" // Method: 'POST', ContentType: 'application/json'
urlDataNodeResponse = hostAddr + "/dataNode/response" // Method: 'POST', ContentType: 'application/json'
)
func responseAckOKToMaster(conn net.Conn, p *proto.Packet, data []byte) error {
if len(data) != 0 {
p.PacketOkWithBody(data)
} else {
p.PacketOkReply()
}
return p.WriteToConn(conn)
}
func responseAckErrToMaster(conn net.Conn, p *proto.Packet, err error) error {
status := proto.OpErr
buf := []byte(err.Error())
p.PacketErrorWithBody(status, buf)
p.ResultCode = proto.TaskFailed
return p.WriteToConn(conn)
}
func PostToMaster(method, url string, reqData []byte) (resp *http.Response, err error) {
client := &http.Client{}
reader := bytes.NewReader(reqData)
client.Timeout = time.Second * 3
var req *http.Request
if req, err = http.NewRequest(method, url, reader); err != nil |
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Connection", "close")
resp, err = client.Do(req)
return
}
| {
return
} |
clean_data.py | import json
def | (task_data_filename, task_vol_filename):
to_remove = []
with open(task_data_filename) as f:
task_data = json.load(f)
with open(task_vol_filename) as f:
task_vol = json.load(f)
for task in task_data:
if len(task_data[task]["aggregate"]) == 0:
to_remove.append(task)
for task in to_remove:
try:
task_data.pop(task)
except:
pass
try:
task_vol.pop(task)
except:
pass
with open(task_data_filename, 'w') as f:
json.dump(task_data, f)
with open(task_vol_filename, 'w') as f:
json.dump(task_vol, f) | clean |
main.py | from flask import Flask, render_template
from flask_wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import InputRequired, Email, Length, AnyOf
from flask_bootstrap import Bootstrap
app = Flask(__name__)
Bootstrap(app)
app.config['SECRET_KEY'] = 'DontTellAnyone'
class | (Form):
username = StringField('username', validators=[InputRequired(), Email(message='I don\'t like your email.')])
password = PasswordField('password', validators=[InputRequired(), Length(min=5, max=10), AnyOf(['secret', 'password'])])
@app.route('/', methods=['GET', 'POST'])
def index():
form = LoginForm()
if form.validate_on_submit():
return 'Form Successfully Submitted!'
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True) | LoginForm |
config.rs | use serde::{Deserialize, Serialize};
/// Consensus configuration.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields, default)]
pub struct Config {
/// Should Zebra sync using checkpoints?
///
/// Setting this option to true enables post-Canopy checkpoints.
/// (Zebra always checkpoints up to and including Canopy activation.)
///
/// Future versions of Zebra may change the mandatory checkpoint
/// height.
pub checkpoint_sync: bool,
}
// we like our default configs to be explicit
#[allow(unknown_lints)]
#[allow(clippy::derivable_impls)]
impl Default for Config {
fn | () -> Self {
Self {
checkpoint_sync: false,
}
}
}
| default |
libraries.py | # Some notes about static linking:
# There are two ways of linking to static library: using the -l command line
# option or specifying the full path to the library file as one of the inputs.
# When using the -l option, the library search paths will be searched for a
# dynamic version of the library, if that is not found, the search paths will
# be searched for a static version of the library. This means we cannot force
# static linking of a library this way. It is possible to force static linking
# of all libraries, but we want to control it per library.
# Conclusion: We have to specify the full path to each library that should be
# linked statically.
from executils import captureStdout, shjoin
from os import listdir
from os.path import isdir, isfile
from os import environ
class Library(object):
libName = None
makeName = None
header = None
configScriptName = None
dynamicLibsOption = '--libs'
staticLibsOption = None
function = None
# TODO: A library can give an application compile time and run time
# dependencies on other libraries. For example SDL_ttf depends on
# FreeType only at run time, but depends on SDL both compile time
# and run time, since SDL is part of its interface and FreeType is
# only used by the implementation. As a result, it is possible to
# compile against SDL_ttf without having the FreeType headers
# installed. But our getCompileFlags() does not support this.
# In pkg-config these are called private dependencies.
dependsOn = ()
@classmethod
def isSystemLibrary(cls, platform): # pylint: disable-msg=W0613
'''Returns True iff this library is a system library on the given
platform.
A system library is a library that is available systemwide in the
minimal installation of the OS.
The default implementation returns False.
'''
return False
@classmethod
def getConfigScript( # pylint: disable-msg=W0613
cls, platform, linkStatic, distroRoot
):
scriptName = cls.configScriptName
if scriptName is None:
return None
elif platform == 'dingux' and cls.isSystemLibrary(platform):
# TODO: A generic mechanism for locating config scripts in SDKs.
# Note that distroRoot is for non-system libs only.
# Trying a path relative to the compiler location would
# probably work well.
return '/opt/a320-toolchain/usr/mipsel-a320-linux-uclibc/sysroot/usr/bin/%s' % scriptName
elif distroRoot is None:
return scriptName
else:
return '%s/bin/%s' % (distroRoot, scriptName)
@classmethod
def getHeaders(cls, platform): # pylint: disable-msg=W0613
header = cls.header
return header if hasattr(header, '__iter__') else (header, )
@classmethod
def getLibName(cls, platform): # pylint: disable-msg=W0613
return cls.libName
@classmethod
def getCompileFlags(cls, platform, linkStatic, distroRoot):
if platform == 'android':
return environ['ANDROID_CXXFLAGS']
configScript = cls.getConfigScript(platform, linkStatic, distroRoot)
if configScript is not None:
flags = [ '`%s --cflags`' % configScript ]
elif distroRoot is None or cls.isSystemLibrary(platform):
flags = []
else:
flags = [ '-I%s/include' % distroRoot ]
dependentFlags = [
librariesByName[name].getCompileFlags(
platform, linkStatic, distroRoot
)
for name in cls.dependsOn
]
return ' '.join(flags + dependentFlags)
@classmethod
def getLinkFlags(cls, platform, linkStatic, distroRoot):
if platform == 'android':
return environ['ANDROID_LDFLAGS']
configScript = cls.getConfigScript(platform, linkStatic, distroRoot)
if configScript is not None:
libsOption = (
cls.dynamicLibsOption
if not linkStatic or cls.isSystemLibrary(platform)
else cls.staticLibsOption
)
if libsOption is not None:
return '`%s %s`' % (configScript, libsOption)
if distroRoot is None or cls.isSystemLibrary(platform):
return '-l%s' % cls.getLibName(platform)
else:
flags = [
'%s/lib/lib%s.a' % (distroRoot, cls.getLibName(platform))
] if linkStatic else [
'-L%s/lib -l%s' % (distroRoot, cls.getLibName(platform))
]
dependentFlags = [
librariesByName[name].getLinkFlags(
platform, linkStatic, distroRoot
)
for name in cls.dependsOn
]
systemDependentFlags = list(cls.getSystemDependentFlags(platform))
return ' '.join(flags + dependentFlags + systemDependentFlags)
@classmethod
def getSystemDependentFlags(cls, platform):
return ()
@classmethod
def getVersion(cls, platform, linkStatic, distroRoot):
'''Returns the version of this library, "unknown" if there is no
mechanism to retrieve the version, None if there is a mechanism
to retrieve the version but it failed, or a callable that takes a
CompileCommand and a log stream as its arguments and returns the
version or None if retrieval failed.
'''
configScript = cls.getConfigScript(platform, linkStatic, distroRoot)
if configScript is None:
return 'unknown'
else:
return '`%s --version`' % configScript
class FreeType(Library):
libName = 'freetype'
makeName = 'FREETYPE'
header = ('<ft2build.h>', 'FT_FREETYPE_H')
configScriptName = 'freetype-config'
function = 'FT_Open_Face'
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android', 'dingux')
@classmethod
def getConfigScript(cls, platform, linkStatic, distroRoot):
if platform in ('netbsd', 'openbsd'):
if distroRoot == '/usr/local':
# FreeType is located in the X11 tree, not the ports tree.
distroRoot = '/usr/X11R6'
return super(FreeType, cls).getConfigScript(
platform, linkStatic, distroRoot
)
@classmethod
def getVersion(cls, platform, linkStatic, distroRoot):
configScript = cls.getConfigScript(platform, linkStatic, distroRoot)
return '`%s --ftversion`' % configScript
class GL(Library):
libName = 'GL'
makeName = 'GL'
function = 'glGenTextures'
@classmethod
def isSystemLibrary(cls, platform):
# On *BSD, OpenGL is in ports, not in the base system.
return not platform.endswith('bsd')
@classmethod
def getHeaders(cls, platform):
if platform == 'darwin':
return ('<OpenGL/gl.h>', )
else:
return ('<GL/gl.h>', )
@classmethod
def getCompileFlags(cls, platform, linkStatic, distroRoot):
if platform in ('netbsd', 'openbsd'):
return '-I/usr/X11R6/include -I/usr/X11R7/include'
else:
return super(GL, cls).getCompileFlags(
platform, linkStatic, distroRoot
)
@classmethod
def getLinkFlags(cls, platform, linkStatic, distroRoot):
if platform == 'darwin':
return '-framework OpenGL'
elif platform.startswith('mingw'):
return '-lopengl32'
elif platform in ('netbsd', 'openbsd'):
return '-L/usr/X11R6/lib -L/usr/X11R7/lib -lGL'
else:
return super(GL, cls).getLinkFlags(platform, linkStatic, distroRoot)
@classmethod
def getVersion(cls, platform, linkStatic, distroRoot):
def execute(cmd, log):
versionPairs = tuple(
( major, minor )
for major in range(1, 10)
for minor in range(0, 10)
)
version = cmd.expand(log, cls.getHeaders(platform), *(
'GL_VERSION_%d_%d' % pair for pair in versionPairs
))
try:
return '%d.%d' % max(
ver
for ver, exp in zip(versionPairs, version)
if exp is not None
)
except ValueError:
return None
return execute
class GLEW(Library):
makeName = 'GLEW'
header = '<GL/glew.h>'
function = 'glewInit'
dependsOn = ('GL', )
@classmethod
def getLibName(cls, platform):
if platform.startswith('mingw'):
return 'glew32'
else:
return 'GLEW'
@classmethod
def getCompileFlags(cls, platform, linkStatic, distroRoot):
flags = super(GLEW, cls).getCompileFlags(
platform, linkStatic, distroRoot
)
if platform.startswith('mingw') and linkStatic:
return '%s -DGLEW_STATIC' % flags
else:
return flags
class LibPNG(Library):
libName = 'png12'
makeName = 'PNG'
header = '<png.h>'
configScriptName = 'libpng-config'
dynamicLibsOption = '--ldflags'
function = 'png_write_image'
dependsOn = ('ZLIB', )
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android', 'dingux')
class | (Library):
libName = 'xml2'
makeName = 'XML'
header = '<libxml/parser.h>'
configScriptName = 'xml2-config'
function = 'xmlParseDocument'
dependsOn = ('ZLIB', )
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android',)
@classmethod
def getCompileFlags(cls, platform, linkStatic, distroRoot):
flags = super(LibXML2, cls).getCompileFlags(
platform, linkStatic, distroRoot
)
if not linkStatic or cls.isSystemLibrary(platform):
return flags
else:
return flags + ' -DLIBXML_STATIC'
class OGG(Library):
libName = 'ogg'
makeName = 'OGG'
header = '<ogg/ogg.h>'
function = 'ogg_stream_init'
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android', 'dingux')
class SDL(Library):
libName = 'SDL'
makeName = 'SDL'
header = '<SDL.h>'
configScriptName = 'sdl-config'
staticLibsOption = '--static-libs'
function = 'SDL_Init'
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android', 'dingux')
class SDL_ttf(Library):
libName = 'SDL_ttf'
makeName = 'SDL_TTF'
header = '<SDL_ttf.h>'
function = 'TTF_OpenFont'
dependsOn = ('SDL', 'FREETYPE')
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android', 'dingux')
@classmethod
def getVersion(cls, platform, linkStatic, distroRoot):
def execute(cmd, log):
version = cmd.expand(log, cls.getHeaders(platform),
'SDL_TTF_MAJOR_VERSION',
'SDL_TTF_MINOR_VERSION',
'SDL_TTF_PATCHLEVEL',
)
return None if None in version else '%s.%s.%s' % version
return execute
class TCL(Library):
libName = 'tcl'
makeName = 'TCL'
header = '<tcl.h>'
function = 'Tcl_CreateInterp'
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android',)
@classmethod
def getTclConfig(cls, platform, distroRoot):
'''Tcl has a config script that is unlike the typical lib-config script.
Information is gathered by sourcing the config script, instead of
executing it and capturing the queried value from stdout. This script
is located in a library directory, not in a directory in the PATH.
Also, it does not have the executable bit set.
This method returns the location of the Tcl config script, or None if
it could not be found.
'''
if hasattr(cls, 'tclConfig'):
# Return cached value.
return cls.tclConfig
def iterLocations():
if platform == 'android':
# Under Android, the tcl set-up apparently differs from
# other cross-platform setups. the search algorithm to find the
# directory that will contain the tclConfig.sh script and the shared libs
# is not applicable to Android. Instead, immediately return the correct
# subdirectories to the routine that invokes iterLocations()
sdl_android_port_path = environ['SDL_ANDROID_PORT_PATH']
libpath = sdl_android_port_path + '/project/libs/armeabi'
yield libpath
tclpath = sdl_android_port_path + '/project/jni/tcl8.5/unix'
yield tclpath
else:
if distroRoot is None or cls.isSystemLibrary(platform):
roots = ('/usr/local', '/usr')
else:
roots = (distroRoot, )
for root in roots:
if isdir(root):
for libdir in ('lib', 'lib64', 'lib/tcl'):
libpath = root + '/' + libdir
if isdir(libpath):
yield libpath
for entry in listdir(libpath):
if entry.startswith('tcl8.'):
tclpath = libpath + '/' + entry
if isdir(tclpath):
yield tclpath
tclConfigs = {}
log = open('derived/tcl-search.log', 'w')
print >> log, 'Looking for Tcl...'
try:
for location in iterLocations():
path = location + '/tclConfig.sh'
if isfile(path):
print >> log, 'Config script:', path
text = captureStdout(
log,
"sh -c '. %s && echo %s'" % (
path, '$TCL_MAJOR_VERSION $TCL_MINOR_VERSION'
)
)
if text is not None:
try:
# pylint: disable-msg=E1103
major, minor = text.split()
version = int(major), int(minor)
except ValueError:
pass
else:
print >> log, 'Found: version %d.%d' % version
tclConfigs[path] = version
try:
# Minimum required version is 8.5.
# Pick the oldest possible version to minimize the risk of
# running into incompatible changes.
tclConfig = min(
( version, path )
for path, version in tclConfigs.iteritems()
if version >= (8, 5)
)[1]
except ValueError:
tclConfig = None
print >> log, 'No suitable versions found.'
else:
print >> log, 'Selected:', tclConfig
finally:
log.close()
cls.tclConfig = tclConfig
return tclConfig
@classmethod
def evalTclConfigExpr(cls, platform, distroRoot, expr, description):
tclConfig = cls.getTclConfig(platform, distroRoot)
if tclConfig is None:
return None
log = open('derived/tcl-search.log', 'a')
try:
print >> log, 'Getting Tcl %s...' % description
text = captureStdout(
log,
shjoin([
'sh', '-c',
'. %s && eval "echo \\"%s\\""' % (tclConfig, expr)
])
)
if text is not None:
print >> log, 'Result: %s' % text.strip()
finally:
log.close()
return None if text is None else text.strip()
@classmethod
def getCompileFlags(cls, platform, linkStatic, distroRoot):
if platform == 'android':
# Use the current ANDROID cross-compilation flags and not the TCL flags. Otherwise, the
# wrong version of libstdc++ will end-up on the include path; the minimal Android NDK
# version instead of the more complete GNU version. This is because TCL for Android has
# been configured with the minimal libstdc++ on the include path in the C(XX) flags and
# not with the more complete GNU version
return environ['ANDROID_CXXFLAGS']
wantShared = not linkStatic or cls.isSystemLibrary(platform)
# The -DSTATIC_BUILD is a hack to avoid including the complete
# TCL_DEFS (see 9f1dbddda2) but still being able to link on
# MinGW (tcl.h depends on this being defined properly).
return cls.evalTclConfigExpr(
platform,
distroRoot,
'${TCL_INCLUDE_SPEC}' + ('' if wantShared else ' -DSTATIC_BUILD'),
'compile flags'
)
@classmethod
def getLinkFlags(cls, platform, linkStatic, distroRoot):
if platform == 'android':
# Use the current ANDROID cross-compilation flags and not the TCL flags to
# prevent issues with libstdc++ version. See also getCompileFlags()
return environ['ANDROID_LDFLAGS']
# Tcl can be built as a shared or as a static library, but not both.
# Check whether the library type of Tcl matches the one we want.
wantShared = not linkStatic or cls.isSystemLibrary(platform)
tclShared = cls.evalTclConfigExpr(
platform,
distroRoot,
'${TCL_SHARED_BUILD}',
'library type (shared/static)'
)
log = open('derived/tcl-search.log', 'a')
try:
if tclShared == '0':
if wantShared:
print >> log, (
'Dynamic linking requested, but Tcl installation has '
'static library.'
)
return None
elif tclShared == '1':
if not wantShared:
print >> log, (
'Static linking requested, but Tcl installation has '
'dynamic library.'
)
return None
else:
print >> log, (
'Unable to determine whether Tcl installation has '
'shared or static library.'
)
return None
finally:
log.close()
# Now get the link flags.
if wantShared:
return cls.evalTclConfigExpr(
platform,
distroRoot,
'${TCL_LIB_SPEC}',
'dynamic link flags'
)
else:
return cls.evalTclConfigExpr(
platform,
distroRoot,
'${TCL_EXEC_PREFIX}/lib/${TCL_LIB_FILE} ${TCL_LIBS}',
'static link flags'
)
@classmethod
def getVersion(cls, platform, linkStatic, distroRoot):
return cls.evalTclConfigExpr(
platform,
distroRoot,
'${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_PATCH_LEVEL}',
'version'
)
class Theora(Library):
libName = 'theoradec'
makeName = 'THEORA'
header = '<theora/theoradec.h>'
function = 'th_decode_ycbcr_out'
dependsOn = ('OGG', )
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android', 'dingux')
class Vorbis(Library):
libName = 'vorbis'
makeName = 'VORBIS'
header = '<vorbis/codec.h>'
function = 'vorbis_synthesis_pcmout'
dependsOn = ('OGG', )
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android', 'dingux')
class ZLib(Library):
libName = 'z'
makeName = 'ZLIB'
header = '<zlib.h>'
function = 'inflate'
@classmethod
def isSystemLibrary(cls, platform):
return platform in ('android', 'dingux')
@classmethod
def getVersion(cls, platform, linkStatic, distroRoot):
def execute(cmd, log):
version = cmd.expand(log, cls.getHeaders(platform), 'ZLIB_VERSION')
return None if version is None else version.strip('"')
return execute
# Build a dictionary of libraries using introspection.
def _discoverLibraries(localObjects):
for obj in localObjects:
if isinstance(obj, type) and issubclass(obj, Library):
if not (obj is Library):
yield obj.makeName, obj
librariesByName = dict(_discoverLibraries(locals().itervalues()))
def allDependencies(makeNames):
'''Compute the set of all directly and indirectly required libraries to
build and use the given set of libraries.
Returns the make names of the required libraries.
'''
# Compute the reflexive-transitive closure.
transLibs = set()
newLibs = set(makeNames)
while newLibs:
transLibs.update(newLibs)
newLibs = set(
depMakeName
for makeName in newLibs
for depMakeName in librariesByName[makeName].dependsOn
if depMakeName not in transLibs
)
return transLibs
| LibXML2 |
partition_reconfiguration_completed_event.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .partition_event import PartitionEvent
class PartitionReconfigurationCompletedEvent(PartitionEvent):
"""Partition Reconfiguration Completed event.
:param event_instance_id: The identifier for the FabricEvent instance.
:type event_instance_id: str
:param time_stamp: The time event was logged.
:type time_stamp: datetime
:param has_correlated_events: Shows there is existing related events
available.
:type has_correlated_events: bool
:param kind: Constant filled by server.
:type kind: str
:param partition_id: An internal ID used by Service Fabric to uniquely
identify a partition. This is a randomly generated GUID when the service
was created. The partition ID is unique and does not change for the
lifetime of the service. If the same service was deleted and recreated the
IDs of its partitions would be different.
:type partition_id: str
:param node_name: The name of a Service Fabric node.
:type node_name: str
:param node_instance_id: Id of Node instance.
:type node_instance_id: str
:param service_type: Type of Service.
:type service_type: str
:param cc_epoch_data_loss_version: CcEpochDataLoss version.
:type cc_epoch_data_loss_version: long
:param cc_epoch_config_version: CcEpochConfig version.
:type cc_epoch_config_version: long
:param reconfig_type: Type of reconfiguration.
:type reconfig_type: str
:param result: Describes reconfiguration result.
:type result: str
:param phase0_duration_ms: Duration of Phase0 in milli-seconds.
:type phase0_duration_ms: float
:param phase1_duration_ms: Duration of Phase1 in milli-seconds.
:type phase1_duration_ms: float
:param phase2_duration_ms: Duration of Phase2 in milli-seconds.
:type phase2_duration_ms: float
:param phase3_duration_ms: Duration of Phase3 in milli-seconds.
:type phase3_duration_ms: float
:param phase4_duration_ms: Duration of Phase4 in milli-seconds.
:type phase4_duration_ms: float
:param total_duration_ms: Total duration in milli-seconds.
:type total_duration_ms: float
"""
_validation = {
'event_instance_id': {'required': True},
'time_stamp': {'required': True},
'kind': {'required': True},
'partition_id': {'required': True},
'node_name': {'required': True},
'node_instance_id': {'required': True},
'service_type': {'required': True},
'cc_epoch_data_loss_version': {'required': True},
'cc_epoch_config_version': {'required': True},
'reconfig_type': {'required': True},
'result': {'required': True},
'phase0_duration_ms': {'required': True},
'phase1_duration_ms': {'required': True},
'phase2_duration_ms': {'required': True},
'phase3_duration_ms': {'required': True},
'phase4_duration_ms': {'required': True},
'total_duration_ms': {'required': True},
}
_attribute_map = {
'event_instance_id': {'key': 'EventInstanceId', 'type': 'str'},
'time_stamp': {'key': 'TimeStamp', 'type': 'iso-8601'},
'has_correlated_events': {'key': 'HasCorrelatedEvents', 'type': 'bool'},
'kind': {'key': 'Kind', 'type': 'str'},
'partition_id': {'key': 'PartitionId', 'type': 'str'},
'node_name': {'key': 'NodeName', 'type': 'str'},
'node_instance_id': {'key': 'NodeInstanceId', 'type': 'str'},
'service_type': {'key': 'ServiceType', 'type': 'str'},
'cc_epoch_data_loss_version': {'key': 'CcEpochDataLossVersion', 'type': 'long'},
'cc_epoch_config_version': {'key': 'CcEpochConfigVersion', 'type': 'long'},
'reconfig_type': {'key': 'ReconfigType', 'type': 'str'},
'result': {'key': 'Result', 'type': 'str'},
'phase0_duration_ms': {'key': 'Phase0DurationMs', 'type': 'float'},
'phase1_duration_ms': {'key': 'Phase1DurationMs', 'type': 'float'},
'phase2_duration_ms': {'key': 'Phase2DurationMs', 'type': 'float'},
'phase3_duration_ms': {'key': 'Phase3DurationMs', 'type': 'float'},
'phase4_duration_ms': {'key': 'Phase4DurationMs', 'type': 'float'},
'total_duration_ms': {'key': 'TotalDurationMs', 'type': 'float'},
}
def | (self, event_instance_id, time_stamp, partition_id, node_name, node_instance_id, service_type, cc_epoch_data_loss_version, cc_epoch_config_version, reconfig_type, result, phase0_duration_ms, phase1_duration_ms, phase2_duration_ms, phase3_duration_ms, phase4_duration_ms, total_duration_ms, has_correlated_events=None):
super(PartitionReconfigurationCompletedEvent, self).__init__(event_instance_id=event_instance_id, time_stamp=time_stamp, has_correlated_events=has_correlated_events, partition_id=partition_id)
self.node_name = node_name
self.node_instance_id = node_instance_id
self.service_type = service_type
self.cc_epoch_data_loss_version = cc_epoch_data_loss_version
self.cc_epoch_config_version = cc_epoch_config_version
self.reconfig_type = reconfig_type
self.result = result
self.phase0_duration_ms = phase0_duration_ms
self.phase1_duration_ms = phase1_duration_ms
self.phase2_duration_ms = phase2_duration_ms
self.phase3_duration_ms = phase3_duration_ms
self.phase4_duration_ms = phase4_duration_ms
self.total_duration_ms = total_duration_ms
self.kind = 'PartitionReconfigurationCompleted'
| __init__ |
refuse-reaction-from-comment.dto.ts | import { ApiProperty } from "@nestjs/swagger";
import { IsEnum } from "class-validator";
import { Reactions } from "../enums/reactions.enum";
import { InputType, Field } from "@nestjs/graphql";
@InputType()
export class RefuseReactionFromCommentDto {
@Field()
@IsEnum(Reactions) | reaction: Reactions;
} | @ApiProperty({
enum: Reactions
}) |
panic.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Panic support in the standard library.
#![stable(feature = "std_panic", since = "1.9.0")]
use any::Any;
use cell::UnsafeCell;
use fmt;
use ops::{Deref, DerefMut};
use panicking;
use ptr::{Unique, NonNull};
use rc::Rc;
use sync::{Arc, Mutex, RwLock, atomic};
use thread::Result;
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub use panicking::{take_hook, set_hook};
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub use core::panic::{PanicInfo, Location};
/// A marker trait which represents "panic safe" types in Rust.
///
/// This trait is implemented by default for many types and behaves similarly in
/// terms of inference of implementation to the `Send` and `Sync` traits. The
/// purpose of this trait is to encode what types are safe to cross a `catch_unwind`
/// boundary with no fear of unwind safety.
///
/// ## What is unwind safety?
///
/// In Rust a function can "return" early if it either panics or calls a
/// function which transitively panics. This sort of control flow is not always
/// anticipated, and has the possibility of causing subtle bugs through a
/// combination of two critical components:
///
/// 1. A data structure is in a temporarily invalid state when the thread
/// panics.
/// 2. This broken invariant is then later observed.
///
/// Typically in Rust, it is difficult to perform step (2) because catching a
/// panic involves either spawning a thread (which in turns makes it difficult
/// to later witness broken invariants) or using the `catch_unwind` function in this
/// module. Additionally, even if an invariant is witnessed, it typically isn't a
/// problem in Rust because there are no uninitialized values (like in C or C++).
///
/// It is possible, however, for **logical** invariants to be broken in Rust,
/// which can end up causing behavioral bugs. Another key aspect of unwind safety
/// in Rust is that, in the absence of `unsafe` code, a panic cannot lead to
/// memory unsafety.
///
/// That was a bit of a whirlwind tour of unwind safety, but for more information
/// about unwind safety and how it applies to Rust, see an [associated RFC][rfc].
///
/// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
///
/// ## What is `UnwindSafe`?
///
/// Now that we've got an idea of what unwind safety is in Rust, it's also
/// important to understand what this trait represents. As mentioned above, one
/// way to witness broken invariants is through the `catch_unwind` function in this
/// module as it allows catching a panic and then re-using the environment of
/// the closure.
///
/// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow
/// witnessing a broken invariant through the use of `catch_unwind` (catching a
/// panic). This trait is a marker trait, so it is automatically implemented for
/// many types, and it is also structurally composed (e.g. a struct is unwind
/// safe if all of its components are unwind safe).
///
/// Note, however, that this is not an unsafe trait, so there is not a succinct
/// contract that this trait is providing. Instead it is intended as more of a
/// "speed bump" to alert users of `catch_unwind` that broken invariants may be
/// witnessed and may need to be accounted for.
///
/// ## Who implements `UnwindSafe`?
///
/// Types such as `&mut T` and `&RefCell<T>` are examples which are **not**
/// unwind safe. The general idea is that any mutable state which can be shared
/// across `catch_unwind` is not unwind safe by default. This is because it is very
/// easy to witness a broken invariant outside of `catch_unwind` as the data is
/// simply accessed as usual.
///
/// Types like `&Mutex<T>`, however, are unwind safe because they implement
/// poisoning by default. They still allow witnessing a broken invariant, but
/// they already provide their own "speed bumps" to do so.
///
/// ## When should `UnwindSafe` be used?
///
/// Is not intended that most types or functions need to worry about this trait.
/// It is only used as a bound on the `catch_unwind` function and as mentioned above,
/// the lack of `unsafe` means it is mostly an advisory. The `AssertUnwindSafe`
/// wrapper struct in this module can be used to force this trait to be
/// implemented for any closed over variables passed to the `catch_unwind` function
/// (more on this below).
#[stable(feature = "catch_unwind", since = "1.9.0")]
#[rustc_on_unimplemented = "the type {Self} may not be safely transferred \
across an unwind boundary"]
pub auto trait UnwindSafe {}
/// A marker trait representing types where a shared reference is considered
/// unwind safe.
///
/// This trait is namely not implemented by `UnsafeCell`, the root of all
/// interior mutability.
///
/// This is a "helper marker trait" used to provide impl blocks for the
/// `UnwindSafe` trait, for more information see that documentation.
#[stable(feature = "catch_unwind", since = "1.9.0")]
#[rustc_on_unimplemented = "the type {Self} may contain interior mutability \
and a reference may not be safely transferrable \
across a catch_unwind boundary"]
pub auto trait RefUnwindSafe {}
/// A simple wrapper around a type to assert that it is unwind safe.
///
/// When using `catch_unwind` it may be the case that some of the closed over
/// variables are not unwind safe. For example if `&mut T` is captured the
/// compiler will generate a warning indicating that it is not unwind safe. It
/// may not be the case, however, that this is actually a problem due to the
/// specific usage of `catch_unwind` if unwind safety is specifically taken into
/// account. This wrapper struct is useful for a quick and lightweight
/// annotation that a variable is indeed unwind safe.
///
/// # Examples
///
/// One way to use `AssertUnwindSafe` is to assert that the entire closure
/// itself is unwind safe, bypassing all checks for all variables:
///
/// ```
/// use std::panic::{self, AssertUnwindSafe};
///
/// let mut variable = 4;
///
/// // This code will not compile because the closure captures `&mut variable`
/// // which is not considered unwind safe by default.
///
/// // panic::catch_unwind(|| {
/// // variable += 3;
/// // });
///
/// // This, however, will compile due to the `AssertUnwindSafe` wrapper
/// let result = panic::catch_unwind(AssertUnwindSafe(|| {
/// variable += 3;
/// }));
/// // ...
/// ```
///
/// Wrapping the entire closure amounts to a blanket assertion that all captured
/// variables are unwind safe. This has the downside that if new captures are
/// added in the future, they will also be considered unwind safe. Therefore,
/// you may prefer to just wrap individual captures, as shown below. This is
/// more annotation, but it ensures that if a new capture is added which is not
/// unwind safe, you will get a compilation error at that time, which will
/// allow you to consider whether that new capture in fact represent a bug or
/// not.
///
/// ```
/// use std::panic::{self, AssertUnwindSafe};
///
/// let mut variable = 4;
/// let other_capture = 3;
///
/// let result = {
/// let mut wrapper = AssertUnwindSafe(&mut variable);
/// panic::catch_unwind(move || {
/// **wrapper += other_capture;
/// })
/// };
/// // ...
/// ```
#[stable(feature = "catch_unwind", since = "1.9.0")]
pub struct AssertUnwindSafe<T>(
#[stable(feature = "catch_unwind", since = "1.9.0")]
pub T
);
// Implementations of the `UnwindSafe` trait:
//
// * By default everything is unwind safe
// * pointers T contains mutability of some form are not unwind safe
// * Unique, an owning pointer, lifts an implementation
// * Types like Mutex/RwLock which are explicilty poisoned are unwind safe
// * Our custom AssertUnwindSafe wrapper is indeed unwind safe
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<'a, T: ?Sized> !UnwindSafe for &'a mut T {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<'a, T: RefUnwindSafe + ?Sized> UnwindSafe for &'a T {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *const T {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T: RefUnwindSafe + ?Sized> UnwindSafe for *mut T {}
#[unstable(feature = "ptr_internals", issue = "0")]
impl<T: UnwindSafe + ?Sized> UnwindSafe for Unique<T> {}
#[stable(feature = "nonnull", since = "1.25.0")]
impl<T: RefUnwindSafe + ?Sized> UnwindSafe for NonNull<T> {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T: ?Sized> UnwindSafe for Mutex<T> {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T: ?Sized> UnwindSafe for RwLock<T> {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T> UnwindSafe for AssertUnwindSafe<T> {}
// not covered via the Shared impl above b/c the inner contents use
// Cell/AtomicUsize, but the usage here is unwind safe so we can lift the
// impl up one level to Arc/Rc itself
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T> {}
// Pretty simple implementations for the `RefUnwindSafe` marker trait,
// basically just saying that `UnsafeCell` is the
// only thing which doesn't implement it (which then transitively applies to
// everything else).
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T: ?Sized> !RefUnwindSafe for UnsafeCell<T> {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T> RefUnwindSafe for AssertUnwindSafe<T> {}
#[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
impl<T: ?Sized> RefUnwindSafe for Mutex<T> {}
#[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
impl<T: ?Sized> RefUnwindSafe for RwLock<T> {}
#[cfg(target_has_atomic = "ptr")]
#[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
impl RefUnwindSafe for atomic::AtomicIsize {}
#[cfg(target_has_atomic = "8")]
#[unstable(feature = "integer_atomics", issue = "32976")]
impl RefUnwindSafe for atomic::AtomicI8 {}
#[cfg(target_has_atomic = "16")]
#[unstable(feature = "integer_atomics", issue = "32976")]
impl RefUnwindSafe for atomic::AtomicI16 {}
#[cfg(target_has_atomic = "32")]
#[unstable(feature = "integer_atomics", issue = "32976")]
impl RefUnwindSafe for atomic::AtomicI32 {}
#[cfg(target_has_atomic = "64")]
#[unstable(feature = "integer_atomics", issue = "32976")]
impl RefUnwindSafe for atomic::AtomicI64 {}
#[cfg(target_has_atomic = "ptr")]
#[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
impl RefUnwindSafe for atomic::AtomicUsize {}
#[cfg(target_has_atomic = "8")]
#[unstable(feature = "integer_atomics", issue = "32976")]
impl RefUnwindSafe for atomic::AtomicU8 {}
#[cfg(target_has_atomic = "16")]
#[unstable(feature = "integer_atomics", issue = "32976")]
impl RefUnwindSafe for atomic::AtomicU16 {}
#[cfg(target_has_atomic = "32")]
#[unstable(feature = "integer_atomics", issue = "32976")]
impl RefUnwindSafe for atomic::AtomicU32 {}
#[cfg(target_has_atomic = "64")]
#[unstable(feature = "integer_atomics", issue = "32976")]
impl RefUnwindSafe for atomic::AtomicU64 {}
#[cfg(target_has_atomic = "8")]
#[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
impl RefUnwindSafe for atomic::AtomicBool {}
#[cfg(target_has_atomic = "ptr")]
#[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")]
impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T> Deref for AssertUnwindSafe<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<T> DerefMut for AssertUnwindSafe<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
#[stable(feature = "catch_unwind", since = "1.9.0")]
impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
type Output = R;
extern "rust-call" fn call_once(self, _args: ()) -> R {
(self.0)()
}
}
#[stable(feature = "std_debug", since = "1.16.0")]
impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("AssertUnwindSafe")
.field(&self.0)
.finish()
}
}
/// Invokes a closure, capturing the cause of an unwinding panic if one occurs.
///
/// This function will return `Ok` with the closure's result if the closure
/// does not panic, and will return `Err(cause)` if the closure panics. The
/// `cause` returned is the object with which panic was originally invoked.
///
/// It is currently undefined behavior to unwind from Rust code into foreign
/// code, so this function is particularly useful when Rust is called from
/// another language (normally C). This can run arbitrary Rust code, capturing a
/// panic and allowing a graceful handling of the error.
///
/// It is **not** recommended to use this function for a general try/catch
/// mechanism. The `Result` type is more appropriate to use for functions that
/// can fail on a regular basis. Additionally, this function is not guaranteed
/// to catch all panics, see the "Notes" section below.
///
/// The closure provided is required to adhere to the `UnwindSafe` trait to ensure
/// that all captured variables are safe to cross this boundary. The purpose of
/// this bound is to encode the concept of [exception safety][rfc] in the type
/// system. Most usage of this function should not need to worry about this
/// bound as programs are naturally unwind safe without `unsafe` code. If it
/// becomes a problem the associated `AssertUnwindSafe` wrapper type in this
/// module can be used to quickly assert that the usage here is indeed unwind
/// safe.
///
/// [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md
///
/// # Notes
///
/// Note that this function **may not catch all panics** in Rust. A panic in
/// Rust is not always implemented via unwinding, but can be implemented by
/// aborting the process as well. This function *only* catches unwinding panics,
/// not those that abort the process.
///
/// # Examples
///
/// ```
/// use std::panic;
///
/// let result = panic::catch_unwind(|| {
/// println!("hello!");
/// });
/// assert!(result.is_ok());
///
/// let result = panic::catch_unwind(|| {
/// panic!("oh no!");
/// });
/// assert!(result.is_err());
/// ```
#[stable(feature = "catch_unwind", since = "1.9.0")]
pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
unsafe {
panicking::try(f)
}
}
/// Triggers a panic without invoking the panic hook.
///
/// This is designed to be used in conjunction with `catch_unwind` to, for
/// example, carry a panic across a layer of C code.
///
/// # Notes
///
/// Note that panics in Rust are not always implemented via unwinding, but they
/// may be implemented by aborting the process. If this function is called when
/// panics are implemented this way then this function will abort the process,
/// not trigger an unwind.
///
/// # Examples
///
/// ```should_panic
/// use std::panic;
///
/// let result = panic::catch_unwind(|| {
/// panic!("oh no!");
/// });
///
/// if let Err(err) = result {
/// panic::resume_unwind(err);
/// }
/// ```
#[stable(feature = "resume_unwind", since = "1.9.0")]
pub fn resume_unwind(payload: Box<Any + Send>) -> ! {
panicking::update_count_then_panic(payload)
}
| fmt |
tls.rs | use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use async_std::net::TcpStream;
use async_trait::async_trait;
use deadpool::managed::{Manager, Object, RecycleResult};
use futures::io::{AsyncRead, AsyncWrite};
use futures::task::{Context, Poll};
cfg_if::cfg_if! {
if #[cfg(feature = "rustls")] {
use async_tls::client::TlsStream;
} else if #[cfg(feature = "native-tls")] {
use async_native_tls::TlsStream;
}
}
use crate::{Config, Error};
#[derive(Clone)]
#[cfg_attr(not(feature = "rustls"), derive(std::fmt::Debug))]
pub(crate) struct TlsConnection {
host: String,
addr: SocketAddr,
config: Arc<Config>,
}
impl TlsConnection {
pub(crate) fn new(host: String, addr: SocketAddr, config: Arc<Config>) -> Self {
Self { host, addr, config }
}
}
pub(crate) struct TlsConnWrapper {
conn: Object<TlsStream<TcpStream>, Error>,
}
impl TlsConnWrapper {
pub(crate) fn new(conn: Object<TlsStream<TcpStream>, Error>) -> Self {
Self { conn }
}
}
impl AsyncRead for TlsConnWrapper {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize, std::io::Error>> {
Pin::new(&mut *self.conn).poll_read(cx, buf)
}
}
impl AsyncWrite for TlsConnWrapper {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut *self.conn).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut *self.conn).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut *self.conn).poll_close(cx)
}
}
#[async_trait]
impl Manager<TlsStream<TcpStream>, Error> for TlsConnection {
async fn create(&self) -> Result<TlsStream<TcpStream>, Error> {
let raw_stream = async_std::net::TcpStream::connect(self.addr).await?;
#[cfg(feature = "unstable-config")]
raw_stream.set_nodelay(self.config.tcp_no_delay)?;
let tls_stream = add_tls(&self.host, raw_stream, &self.config).await?;
Ok(tls_stream)
}
async fn | (&self, conn: &mut TlsStream<TcpStream>) -> RecycleResult<Error> {
let mut buf = [0; 4];
let mut cx = Context::from_waker(futures::task::noop_waker_ref());
#[cfg(feature = "unstable-config")]
conn.get_ref()
.set_nodelay(self.config.tcp_no_delay)
.map_err(Error::from)?;
match Pin::new(conn).poll_read(&mut cx, &mut buf) {
Poll::Ready(Err(error)) => Err(error),
Poll::Ready(Ok(bytes)) if bytes == 0 => Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"connection appeared to be closed (EoF)",
)),
_ => Ok(()),
}
.map_err(Error::from)?;
Ok(())
}
}
cfg_if::cfg_if! {
if #[cfg(feature = "rustls")] {
#[allow(unused_variables)]
pub(crate) async fn add_tls(host: &str, stream: TcpStream, config: &Config) -> Result<TlsStream<TcpStream>, std::io::Error> {
#[cfg(all(feature = "h1_client", feature = "unstable-config"))]
let connector = if let Some(tls_config) = config.tls_config.as_ref().cloned() {
tls_config.into()
} else {
async_tls::TlsConnector::default()
};
#[cfg(not(feature = "unstable-config"))]
let connector = async_tls::TlsConnector::default();
connector.connect(host, stream).await
}
} else if #[cfg(feature = "native-tls")] {
#[allow(unused_variables)]
pub(crate) async fn add_tls(
host: &str,
stream: TcpStream,
config: &Config,
) -> Result<TlsStream<TcpStream>, async_native_tls::Error> {
#[cfg(feature = "unstable-config")]
let connector = config.tls_config.as_ref().cloned().unwrap_or_default();
#[cfg(not(feature = "unstable-config"))]
let connector = async_native_tls::TlsConnector::new();
connector.connect(host, stream).await
}
}
}
| recycle |
modeling_bert_generation.py | # coding=utf-8
# Copyright 2020 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch BERT model specific for generation. """
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from ...file_utils import (
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
replace_return_docstrings,
)
from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
from ...modeling_utils import PreTrainedModel
from ..bert.modeling_bert import BertEncoder
from .configuration_bert_generation import BertGenerationConfig
from pycorrector.utils.logger import logger
_CONFIG_FOR_DOC = "BertGenerationConfig"
_TOKENIZER_FOR_DOC = "BertGenerationTokenizer"
def load_tf_weights_in_bert_generation(
model, tf_hub_path, model_class, is_encoder_named_decoder=False, is_encoder=False
):
try:
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
import tensorflow_text # noqa: F401
tf.disable_eager_execution()
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_model = hub.Module(tf_hub_path)
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
all_variables = tf_model.variable_map
keep_track_variables = all_variables.copy()
for key in list(all_variables.keys()):
if "global" in key:
logger.info(f"Skipping {key}...")
continue
if not is_encoder:
model_pointer = getattr(model, model_class)
else:
model_pointer = model
is_embedding = False
logger.info(f"Trying to match {key}...")
# remove start_string = "module/bert/"
sub_layers = key.split("/")[2:]
if is_encoder_named_decoder and sub_layers[0] == "encoder":
logger.info(f"Skipping encoder layer {key} for decoder")
continue
if is_encoder and sub_layers[0] == "decoder":
logger.info(f"Skipping decoder layer {key} for encoder")
continue
for i, sub_layer in enumerate(sub_layers):
if sub_layer == "embeddings":
is_embedding = True
elif sub_layer == "LayerNorm":
is_embedding = False
if "layer" in sub_layer:
model_pointer = model_pointer.layer[int(sub_layer.split("_")[-1])]
elif sub_layer in ["kernel", "gamma"]:
model_pointer = model_pointer.weight
elif sub_layer == "beta":
model_pointer = model_pointer.bias
elif sub_layer == "encdec":
model_pointer = model_pointer.crossattention.self
elif sub_layer == "encdec_output":
model_pointer = model_pointer.crossattention.output
elif is_encoder_named_decoder and sub_layer == "decoder":
model_pointer = model_pointer.encoder
else:
if sub_layer == "attention" and "encdec" in sub_layers[i + 1]:
continue
try:
model_pointer = getattr(model_pointer, sub_layer)
except AttributeError:
logger.info(f"Skipping to initialize {key} at {sub_layer}...")
raise AttributeError
array = np.asarray(sess.run(all_variables[key]))
if not is_embedding:
logger.info("Transposing numpy weight of shape {} for {}".format(array.shape, key))
array = np.transpose(array)
else:
model_pointer = model_pointer.weight
try:
assert (
model_pointer.shape == array.shape
), f"Pointer shape {model_pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (model_pointer.shape, array.shape)
raise
logger.info(f"Initialize PyTorch weight {key}")
model_pointer.data = torch.from_numpy(array.astype(np.float32))
keep_track_variables.pop(key, None)
logger.info("Weights not copied to PyTorch model: {}".format(", ".join(keep_track_variables.keys())))
return model
class BertGenerationEmbeddings(nn.Module):
"""Construct the embeddings from word and position embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
# any TensorFlow checkpoint file
self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0):
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None:
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
position_embeddings = self.position_embeddings(position_ids)
embeddings = inputs_embeds + position_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class BertGenerationPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
model_files.
"""
config_class = BertGenerationConfig
base_model_prefix = "bert"
_keys_to_ignore_on_load_missing = [r"position_ids"]
def _init_weights(self, module):
""" Initialize the weights """
if isinstance(module, (nn.Linear, nn.Embedding)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
if isinstance(module, nn.Linear) and module.bias is not None:
module.bias.data.zero_()
BERT_GENERATION_START_DOCSTRING = r"""
This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
pruning heads etc.)
This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__
subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
general usage and behavior.
Parameters:
config (:class:`~transformers.BertGenerationConfig`): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
weights.
"""
BERT_GENERATION_INPUTS_DOCSTRING = r"""
Args:
input_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using :class:`~transformers.BertGenerationTokenizer`. See
:meth:`transformers.PreTrainedTokenizer.__call__` and :meth:`transformers.PreTrainedTokenizer.encode` for
details.
`What are input IDs? <../glossary.html#input-ids>`__
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `optional`):
Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
`What are attention masks? <../glossary.html#attention-mask>`__
position_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,
config.max_position_embeddings - 1]``.
`What are position IDs? <../glossary.html#position-ids>`_
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`({0}, hidden_size)`, `optional`):
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
vectors than the model's internal embedding lookup matrix.
output_attentions (:obj:`bool`, `optional`):
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
tensors for more detail.
output_hidden_states (:obj:`bool`, `optional`):
Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
more detail.
return_dict (:obj:`bool`, `optional`):
Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
"""
@add_start_docstrings(
"The bare BertGeneration model transformer outputting raw hidden-states without any specific head on top.",
BERT_GENERATION_START_DOCSTRING,
)
class BertGenerationEncoder(BertGenerationPreTrainedModel):
"""
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
cross-attention is added between the self-attention layers, following the architecture described in `Attention is
all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
This model should be used when leveraging Bert or Roberta checkpoints for the
:class:`~transformers.EncoderDecoderModel` class as described in `Leveraging Pre-trained Checkpoints for Sequence
Generation Tasks <https://arxiv.org/abs/1907.12461>`__ by Sascha Rothe, Shashi Narayan, and Aliaksei Severyn.
To behave as an decoder the model needs to be initialized with the :obj:`is_decoder` argument of the configuration
set to :obj:`True`. To be used in a Seq2Seq model, the model needs to initialized with both :obj:`is_decoder`
argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
input to the forward pass.
"""
def __init__(self, config):
super().__init__(config)
self.config = config
self.embeddings = BertGenerationEmbeddings(config)
self.encoder = BertEncoder(config)
self.init_weights()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(BERT_GENERATION_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
tokenizer_class=_TOKENIZER_FOR_DOC,
checkpoint="google/bert_for_seq_generation_L-24_bbc_encoder",
output_type=BaseModelOutputWithPastAndCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: ``1`` for
tokens that are NOT MASKED, ``0`` for MASKED tokens.
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
use_cache (:obj:`bool`, `optional`):
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
decoding (see :obj:`past_key_values`).
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if self.config.is_decoder:
use_cache = use_cache if use_cache is not None else self.config.use_cache
else:
use_cache = False
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
batch_size, seq_length = input_shape
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
batch_size, seq_length = input_shape
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
# past_key_values_length
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
if attention_mask is None:
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask = None
if not use_cache:
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
attention_mask, input_shape, device
)
# If a 2D or 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if self.config.is_decoder and encoder_hidden_states is not None:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_extended_attention_mask = None
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
embedding_output = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
past_key_values_length=past_key_values_length,
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
if not return_dict:
return (sequence_output,) + encoder_outputs[1:]
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=sequence_output,
past_key_values=encoder_outputs.past_key_values,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
cross_attentions=encoder_outputs.cross_attentions,
)
class BertGenerationOnlyLMHead(nn.Module):
def __init__(self, config):
super().__init__()
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
logits = self.decoder(hidden_states)
return logits
@add_start_docstrings(
"""BertGeneration Model with a `language modeling` head on top for CLM fine-tuning. """,
BERT_GENERATION_START_DOCSTRING,
)
class BertGenerationDecoder(BertGenerationPreTrainedModel):
def __init__(self, config):
|
def get_output_embeddings(self):
return self.lm_head.decoder
def set_output_embeddings(self, new_embeddings):
self.lm_head.decoder = new_embeddings
@add_start_docstrings_to_model_forward(BERT_GENERATION_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
labels=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
ignored (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
use_cache (:obj:`bool`, `optional`):
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
decoding (see :obj:`past_key_values`).
Returns:
Example::
>>> from transformers import BertGenerationTokenizer, BertGenerationDecoder, BertGenerationConfig
>>> import torch
>>> tokenizer = BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder')
>>> config = BertGenerationConfig.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
>>> config.is_decoder = True
>>> model = BertGenerationDecoder.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder', config=config)
>>> inputs = tokenizer("Hello, my dog is cute", return_token_type_ids=False, return_tensors="pt")
>>> outputs = model(**inputs)
>>> prediction_logits = outputs.logits
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if labels is not None:
use_cache = False
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
prediction_scores = self.lm_head(sequence_output)
lm_loss = None
if labels is not None:
# we are doing next-token prediction; shift prediction scores and input ids by one
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
labels = labels[:, 1:].contiguous()
loss_fct = CrossEntropyLoss()
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + outputs[1:]
return ((lm_loss,) + output) if lm_loss is not None else output
return CausalLMOutputWithCrossAttentions(
loss=lm_loss,
logits=prediction_scores,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
cross_attentions=outputs.cross_attentions,
)
def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs):
input_shape = input_ids.shape
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
if attention_mask is None:
attention_mask = input_ids.new_ones(input_shape)
# cut decoder_input_ids if past is used
if past is not None:
input_ids = input_ids[:, -1:]
return {"input_ids": input_ids, "attention_mask": attention_mask}
def _reorder_cache(self, past, beam_idx):
reordered_past = ()
for layer_past in past:
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
return reordered_past
| super().__init__(config)
if not config.is_decoder:
logger.warn("If you want to use `BertGenerationDecoder` as a standalone, add `is_decoder=True.`")
self.bert = BertGenerationEncoder(config)
self.lm_head = BertGenerationOnlyLMHead(config)
self.init_weights() |
multi_value_legacy_extended_property_item_request_builder.go | package item
import (
ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9 "github.com/microsoft/kiota/abstractions/go"
i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87 "github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph"
i7df4e557a1198b9abe14a17b40c7ac7db49b0d3050c749c3169541cb6f012b8b "github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph/odataerrors"
)
// MultiValueLegacyExtendedPropertyItemRequestBuilder provides operations to manage the multiValueExtendedProperties property of the microsoft.graph.event entity.
type MultiValueLegacyExtendedPropertyItemRequestBuilder struct {
// Path parameters for the request
pathParameters map[string]string;
// The request adapter to use to execute the requests.
requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter;
// Url template to use to build the URL for the current request builder
urlTemplate string;
}
// MultiValueLegacyExtendedPropertyItemRequestBuilderDeleteOptions options for Delete
type MultiValueLegacyExtendedPropertyItemRequestBuilderDeleteOptions struct {
// Request headers
H map[string]string;
// Request options
O []ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestOption;
// Response handler to use in place of the default response handling provided by the core service
ResponseHandler ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ResponseHandler;
}
// MultiValueLegacyExtendedPropertyItemRequestBuilderGetOptions options for Get
type MultiValueLegacyExtendedPropertyItemRequestBuilderGetOptions struct {
// Request headers
H map[string]string;
// Request options
O []ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestOption;
// Request query parameters
Q *MultiValueLegacyExtendedPropertyItemRequestBuilderGetQueryParameters;
// Response handler to use in place of the default response handling provided by the core service
ResponseHandler ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ResponseHandler;
}
// MultiValueLegacyExtendedPropertyItemRequestBuilderGetQueryParameters the collection of multi-value extended properties defined for the event. Read-only. Nullable.
type MultiValueLegacyExtendedPropertyItemRequestBuilderGetQueryParameters struct {
// Expand related entities
Expand []string;
// Select properties to be returned
Select []string;
}
// MultiValueLegacyExtendedPropertyItemRequestBuilderPatchOptions options for Patch
type MultiValueLegacyExtendedPropertyItemRequestBuilderPatchOptions struct {
//
Body i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.MultiValueLegacyExtendedPropertyable;
// Request headers
H map[string]string;
// Request options
O []ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestOption;
// Response handler to use in place of the default response handling provided by the core service
ResponseHandler ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ResponseHandler;
}
// NewMultiValueLegacyExtendedPropertyItemRequestBuilderInternal instantiates a new MultiValueLegacyExtendedPropertyItemRequestBuilder and sets the default values.
func NewMultiValueLegacyExtendedPropertyItemRequestBuilderInternal(pathParameters map[string]string, requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter)(*MultiValueLegacyExtendedPropertyItemRequestBuilder) {
m := &MultiValueLegacyExtendedPropertyItemRequestBuilder{
}
m.urlTemplate = "{+baseurl}/users/{user_id}/calendarView/{event_id}/multiValueExtendedProperties/{multiValueLegacyExtendedProperty_id}{?select,expand}";
urlTplParams := make(map[string]string)
for idx, item := range pathParameters {
urlTplParams[idx] = item
}
m.pathParameters = urlTplParams;
m.requestAdapter = requestAdapter;
return m
}
// NewMultiValueLegacyExtendedPropertyItemRequestBuilder instantiates a new MultiValueLegacyExtendedPropertyItemRequestBuilder and sets the default values.
func NewMultiValueLegacyExtendedPropertyItemRequestBuilder(rawUrl string, requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter)(*MultiValueLegacyExtendedPropertyItemRequestBuilder) {
urlParams := make(map[string]string)
urlParams["request-raw-url"] = rawUrl
return NewMultiValueLegacyExtendedPropertyItemRequestBuilderInternal(urlParams, requestAdapter)
}
// CreateDeleteRequestInformation delete navigation property multiValueExtendedProperties for users
func (m *MultiValueLegacyExtendedPropertyItemRequestBuilder) CreateDeleteRequestInformation(options *MultiValueLegacyExtendedPropertyItemRequestBuilderDeleteOptions)(*ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestInformation, error) {
requestInfo := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.DELETE
if options != nil && options.H != nil {
requestInfo.Headers = options.H
}
if options != nil && len(options.O) != 0 {
err := requestInfo.AddRequestOptions(options.O...)
if err != nil |
}
return requestInfo, nil
}
// CreateGetRequestInformation the collection of multi-value extended properties defined for the event. Read-only. Nullable.
func (m *MultiValueLegacyExtendedPropertyItemRequestBuilder) CreateGetRequestInformation(options *MultiValueLegacyExtendedPropertyItemRequestBuilderGetOptions)(*ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestInformation, error) {
requestInfo := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.GET
if options != nil && options.Q != nil {
requestInfo.AddQueryParameters(*(options.Q))
}
if options != nil && options.H != nil {
requestInfo.Headers = options.H
}
if options != nil && len(options.O) != 0 {
err := requestInfo.AddRequestOptions(options.O...)
if err != nil {
return nil, err
}
}
return requestInfo, nil
}
// CreatePatchRequestInformation update the navigation property multiValueExtendedProperties in users
func (m *MultiValueLegacyExtendedPropertyItemRequestBuilder) CreatePatchRequestInformation(options *MultiValueLegacyExtendedPropertyItemRequestBuilderPatchOptions)(*ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestInformation, error) {
requestInfo := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.PATCH
requestInfo.SetContentFromParsable(m.requestAdapter, "application/json", options.Body)
if options != nil && options.H != nil {
requestInfo.Headers = options.H
}
if options != nil && len(options.O) != 0 {
err := requestInfo.AddRequestOptions(options.O...)
if err != nil {
return nil, err
}
}
return requestInfo, nil
}
// Delete delete navigation property multiValueExtendedProperties for users
func (m *MultiValueLegacyExtendedPropertyItemRequestBuilder) Delete(options *MultiValueLegacyExtendedPropertyItemRequestBuilderDeleteOptions)(error) {
requestInfo, err := m.CreateDeleteRequestInformation(options);
if err != nil {
return err
}
errorMapping := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ErrorMappings {
"4XX": i7df4e557a1198b9abe14a17b40c7ac7db49b0d3050c749c3169541cb6f012b8b.CreateODataErrorFromDiscriminatorValue,
"5XX": i7df4e557a1198b9abe14a17b40c7ac7db49b0d3050c749c3169541cb6f012b8b.CreateODataErrorFromDiscriminatorValue,
}
err = m.requestAdapter.SendNoContentAsync(requestInfo, nil, errorMapping)
if err != nil {
return err
}
return nil
}
// Get the collection of multi-value extended properties defined for the event. Read-only. Nullable.
func (m *MultiValueLegacyExtendedPropertyItemRequestBuilder) Get(options *MultiValueLegacyExtendedPropertyItemRequestBuilderGetOptions)(i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.MultiValueLegacyExtendedPropertyable, error) {
requestInfo, err := m.CreateGetRequestInformation(options);
if err != nil {
return nil, err
}
errorMapping := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ErrorMappings {
"4XX": i7df4e557a1198b9abe14a17b40c7ac7db49b0d3050c749c3169541cb6f012b8b.CreateODataErrorFromDiscriminatorValue,
"5XX": i7df4e557a1198b9abe14a17b40c7ac7db49b0d3050c749c3169541cb6f012b8b.CreateODataErrorFromDiscriminatorValue,
}
res, err := m.requestAdapter.SendAsync(requestInfo, i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.CreateMultiValueLegacyExtendedPropertyFromDiscriminatorValue, nil, errorMapping)
if err != nil {
return nil, err
}
return res.(i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.MultiValueLegacyExtendedPropertyable), nil
}
// Patch update the navigation property multiValueExtendedProperties in users
func (m *MultiValueLegacyExtendedPropertyItemRequestBuilder) Patch(options *MultiValueLegacyExtendedPropertyItemRequestBuilderPatchOptions)(error) {
requestInfo, err := m.CreatePatchRequestInformation(options);
if err != nil {
return err
}
errorMapping := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ErrorMappings {
"4XX": i7df4e557a1198b9abe14a17b40c7ac7db49b0d3050c749c3169541cb6f012b8b.CreateODataErrorFromDiscriminatorValue,
"5XX": i7df4e557a1198b9abe14a17b40c7ac7db49b0d3050c749c3169541cb6f012b8b.CreateODataErrorFromDiscriminatorValue,
}
err = m.requestAdapter.SendNoContentAsync(requestInfo, nil, errorMapping)
if err != nil {
return err
}
return nil
}
| {
return nil, err
} |
appcontext.go | // SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2020 Intel Corporation
package appcontext
import (
"fmt"
"strings"
log "github.com/open-ness/EMCO/src/orchestrator/pkg/infra/logutils"
"github.com/open-ness/EMCO/src/orchestrator/pkg/rtcontext"
pkgerrors "github.com/pkg/errors"
)
// metaPrefix used for denoting clusterMeta level
const metaGrpPREFIX = "!@#metaGrp"
type AppContext struct {
initDone bool
rtcObj rtcontext.RunTimeContext
rtc rtcontext.Rtcontext
}
// AppContextStatus represents the current status of the appcontext
// Instantiating - instantiate has been invoked and is still in progress
// Instantiated - instantiate has completed
// Terminating - terminate has been invoked and is still in progress
// Terminated - terminate has completed
// InstantiateFailed - the instantiate action has failed
// TerminateFailed - the terminate action has failed
type AppContextStatus struct {
Status StatusValue
}
type StatusValue string
type statuses struct {
Instantiating StatusValue
Instantiated StatusValue
Terminating StatusValue
Terminated StatusValue
InstantiateFailed StatusValue
TerminateFailed StatusValue
}
var AppContextStatusEnum = &statuses{
Instantiating: "Instantiating",
Instantiated: "Instantiated",
Terminating: "Terminating",
Terminated: "Terminated",
InstantiateFailed: "InstantiateFailed",
TerminateFailed: "TerminateFailed",
}
// CompositeAppMeta consists of projectName, CompositeAppName,
// CompositeAppVersion, ReleaseName. This shall be used for
// instantiation of a compositeApp
type CompositeAppMeta struct {
Project string `json:"Project"`
CompositeApp string `json:"CompositeApp"`
Version string `json:"Version"`
Release string `json:"Release"`
DeploymentIntentGroup string `json:"DeploymentIntentGroup"`
Namespace string `json:"Namespace"`
Level string `json:"Level"`
ChildContextIDs []string `json:"ChildContextIDs"`
}
// Init app context
func (ac *AppContext) InitAppContext() (interface{}, error) {
ac.rtcObj = rtcontext.RunTimeContext{}
ac.rtc = &ac.rtcObj
return ac.rtc.RtcInit()
}
// Load app context that was previously created
func (ac *AppContext) LoadAppContext(cid interface{}) (interface{}, error) {
ac.rtcObj = rtcontext.RunTimeContext{}
ac.rtc = &ac.rtcObj
return ac.rtc.RtcLoad(cid)
}
// CreateCompositeApp method returns composite app handle as interface.
func (ac *AppContext) CreateCompositeApp() (interface{}, error) {
h, err := ac.rtc.RtcCreate()
if err != nil {
return nil, err
}
log.Info(":: CreateCompositeApp ::", log.Fields{"CompositeAppHandle": h})
return h, nil
}
// AddCompositeAppMeta adds the meta data associated with a composite app
func (ac *AppContext) AddCompositeAppMeta(meta interface{}) error {
err := ac.rtc.RtcAddMeta(meta)
if err != nil {
return err
}
return nil
}
// Deletes the entire context
func (ac *AppContext) DeleteCompositeApp() error {
h, err := ac.rtc.RtcGet()
if err != nil {
return err
}
err = ac.rtc.RtcDeletePrefix(h)
if err != nil {
return err
}
return nil
}
//Returns the handles for a given composite app context
func (ac *AppContext) GetCompositeAppHandle() (interface{}, error) {
h, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
return h, nil
}
// GetLevelHandle returns the handle for the supplied level at the given handle.
// For example, to get the handle of the 'status' level at a given handle.
func (ac *AppContext) GetLevelHandle(handle interface{}, level string) (interface{}, error) {
ach := fmt.Sprintf("%v%v/", handle, level)
hs, err := ac.rtc.RtcGetHandles(ach)
if err != nil {
return nil, err
}
for _, v := range hs {
if v == ach {
return v, nil
}
}
return nil, pkgerrors.Errorf("No handle was found for level %v", level)
}
//Add app to the context under composite app
func (ac *AppContext) AddApp(handle interface{}, appname string) (interface{}, error) {
h, err := ac.rtc.RtcAddLevel(handle, "app", appname)
if err != nil {
return nil, err
}
log.Info(":: Added app handle ::", log.Fields{"AppHandle": h})
return h, nil
}
//Delete app from the context and everything underneth
func (ac *AppContext) DeleteApp(handle interface{}) error {
err := ac.rtc.RtcDeletePrefix(handle)
if err != nil {
return err
}
return nil
}
//Returns the handle for a given app
func (ac *AppContext) GetAppHandle(appname string) (interface{}, error) {
if appname == "" {
return nil, pkgerrors.Errorf("Not a valid run time context app name")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
apph := fmt.Sprintf("%v", rh) + "app/" + appname + "/"
hs, err := ac.rtc.RtcGetHandles(apph)
if err != nil {
return nil, err
}
for _, v := range hs {
if v == apph {
return v, nil
}
}
return nil, pkgerrors.Errorf("No handle was found for the given app")
}
// AddCluster helps to add cluster to the context under app. It takes in the app handle and clusterName as value.
func (ac *AppContext) AddCluster(handle interface{}, clustername string) (interface{}, error) {
h, err := ac.rtc.RtcAddLevel(handle, "cluster", clustername)
if err != nil {
return nil, err
}
log.Info(":: Added cluster handle ::", log.Fields{"ClusterHandler": h})
return h, nil
}
// AddClusterMetaGrp adds the meta info of groupNumber to which a cluster belongs.
// It takes in cluster handle and groupNumber as arguments
func (ac *AppContext) AddClusterMetaGrp(ch interface{}, gn string) error {
mh, err := ac.rtc.RtcAddOneLevel(ch, metaGrpPREFIX, gn)
if err != nil {
return err
}
log.Info(":: Added cluster meta handle ::", log.Fields{"ClusterMetaHandler": mh})
return nil
}
// DeleteClusterMetaGrpHandle deletes the group number to which the cluster belongs, it takes in the cluster handle.
func (ac *AppContext) DeleteClusterMetaGrpHandle(ch interface{}) error {
err := ac.rtc.RtcDeletePrefix(ch)
if err != nil {
return err
}
log.Info(":: Deleted cluster meta handle ::", log.Fields{"ClusterMetaHandler": ch})
return nil
}
/*
GetClusterMetaHandle takes in appName and ClusterName as string arguments and return the ClusterMetaHandle as string
*/
func (ac *AppContext) GetClusterMetaHandle(app string, cluster string) (string, error) {
if app == "" {
return "", pkgerrors.Errorf("Not a valid run time context app name")
}
if cluster == "" {
return "", pkgerrors.Errorf("Not a valid run time context cluster name")
}
ch, err := ac.GetClusterHandle(app, cluster)
if err != nil {
return "", err
}
cmh := fmt.Sprintf("%v", ch) + metaGrpPREFIX + "/"
return cmh, nil
}
/*
GetClusterGroupMap shall take in appName and return a map showing the grouping among the clusters.
sample output of "GroupMap" :{"1":["cluster_provider1+clusterName3","cluster_provider1+clusterName5"],"2":["cluster_provider2+clusterName4","cluster_provider2+clusterName6"]}
*/
func (ac *AppContext) GetClusterGroupMap(an string) (map[string][]string, error) {
cl, err := ac.GetClusterNames(an)
if err != nil {
log.Info(":: Unable to fetch clusterList for app ::", log.Fields{"AppName ": an})
return nil, err
}
rh, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
var gmap = make(map[string][]string)
for _, cn := range cl {
s := fmt.Sprintf("%v", rh) + "app/" + an + "/cluster/" + cn + "/" + metaGrpPREFIX + "/"
var v string
err = ac.rtc.RtcGetValue(s, &v)
if err != nil {
log.Info(":: No group number for cluster ::", log.Fields{"cluster": cn, "Reason": err})
continue
}
gn := fmt.Sprintf("%v", v)
log.Info(":: GroupNumber retrieved ::", log.Fields{"GroupNumber": gn})
cl, found := gmap[gn]
if found == false {
cl = make([]string, 0)
}
cl = append(cl, cn)
gmap[gn] = cl
}
return gmap, nil
}
//Delete cluster from the context and everything underneth
func (ac *AppContext) DeleteCluster(handle interface{}) error {
err := ac.rtc.RtcDeletePrefix(handle)
if err != nil {
return err
}
return nil
}
//Returns the handle for a given app and cluster
func (ac *AppContext) GetClusterHandle(appname string, clustername string) (interface{}, error) {
if appname == "" {
return nil, pkgerrors.Errorf("Not a valid run time context app name")
}
if clustername == "" {
return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
ach := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/"
hs, err := ac.rtc.RtcGetHandles(ach)
if err != nil {
return nil, err
}
for _, v := range hs {
if v == ach {
return v, nil
}
}
return nil, pkgerrors.Errorf("No handle was found for the given cluster")
}
//Returns a list of all clusters for a given app
func (ac *AppContext) GetClusterNames(appname string) ([]string, error) {
if appname == "" {
return nil, pkgerrors.Errorf("Not a valid run time context app name")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
prefix := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/"
hs, err := ac.rtc.RtcGetHandles(prefix)
if err != nil {
return nil, pkgerrors.Errorf("Error getting handles for %v", prefix)
}
var cs []string
for _, h := range hs {
hstr := fmt.Sprintf("%v", h)
ks := strings.Split(hstr, prefix)
for _, k := range ks {
ck := strings.Split(k, "/")
if len(ck) == 2 && ck[1] == "" {
cs = append(cs, ck[0])
}
}
}
if len(cs) == 0 {
err = pkgerrors.New("Cluster list is empty")
log.Error("Cluster list is empty",
log.Fields{"clusters": cs})
return cs, err
}
return cs, nil
}
//Add resource under app and cluster
func (ac *AppContext) AddResource(handle interface{}, resname string, value interface{}) (interface{}, error) {
h, err := ac.rtc.RtcAddResource(handle, resname, value)
if err != nil {
return nil, err
}
log.Info(":: Added resource handle ::", log.Fields{"ResourceHandler": h})
return h, nil
}
//Return the handle for given app, cluster and resource name
func (ac *AppContext) GetResourceHandle(appname string, clustername string, resname string) (interface{}, error) {
if appname == "" |
if clustername == "" {
return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
acrh := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/resource/" + resname + "/"
hs, err := ac.rtc.RtcGetHandles(acrh)
if err != nil {
return nil, err
}
for _, v := range hs {
if v == acrh {
return v, nil
}
}
return nil, pkgerrors.Errorf("No handle was found for the given resource")
}
//Update the resource value using the given handle
func (ac *AppContext) UpdateResourceValue(handle interface{}, value interface{}) error {
return ac.rtc.RtcUpdateValue(handle, value)
}
//Return the handle for given app, cluster and resource name
func (ac *AppContext) GetResourceStatusHandle(appname string, clustername string, resname string) (interface{}, error) {
if appname == "" {
return nil, pkgerrors.Errorf("Not a valid run time context app name")
}
if clustername == "" {
return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
}
if resname == "" {
return nil, pkgerrors.Errorf("Not a valid run time context resource name")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
acrh := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/resource/" + resname + "/status/"
hs, err := ac.rtc.RtcGetHandles(acrh)
if err != nil {
return nil, err
}
for _, v := range hs {
if v == acrh {
return v, nil
}
}
return nil, pkgerrors.Errorf("No handle was found for the given resource")
}
//GetResourceNames ... Returns a list of all resource names for a given app
func (ac *AppContext) GetResourceNames(appname string, clustername string) ([]string, error) {
if appname == "" {
return nil, pkgerrors.Errorf("Not a valid run time context app name")
}
if clustername == "" {
return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
prefix := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/resource/"
hs, err := ac.rtc.RtcGetHandles(prefix)
if err != nil {
return nil, pkgerrors.Errorf("Error getting handles for %v", prefix)
}
var cs []string
for _, h := range hs {
hstr := fmt.Sprintf("%v", h)
ks := strings.Split(hstr, prefix)
for _, k := range ks {
ck := strings.Split(k, "/")
if len(ck) == 2 && ck[1] == "" {
cs = append(cs, ck[0])
}
}
}
return cs, nil
}
//Add instruction under given handle and type
func (ac *AppContext) AddInstruction(handle interface{}, level string, insttype string, value interface{}) (interface{}, error) {
if !(insttype == "order" || insttype == "dependency") {
log.Error("Not a valid app context instruction type", log.Fields{})
return nil, pkgerrors.Errorf("Not a valid app context instruction type")
}
if !(level == "app" || level == "resource" || level == "subresource") {
log.Error("Not a valid app context instruction level", log.Fields{})
return nil, pkgerrors.Errorf("Not a valid app context instruction level")
}
h, err := ac.rtc.RtcAddInstruction(handle, level, insttype, value)
if err != nil {
log.Error("ac.rtc.RtcAddInstruction(handle, level, insttype, value)", log.Fields{"err": err})
return nil, err
}
log.Info(":: Added instruction handle ::", log.Fields{"InstructionHandler": h})
return h, nil
}
//Delete instruction under given handle
func (ac *AppContext) DeleteInstruction(handle interface{}) error {
err := ac.rtc.RtcDeletePair(handle)
if err != nil {
return err
}
return nil
}
//Returns the app instruction for a given instruction type
func (ac *AppContext) GetAppInstruction(insttype string) (interface{}, error) {
if !(insttype == "order" || insttype == "dependency") {
log.Error("Not a valid app context instruction type", log.Fields{})
return nil, pkgerrors.Errorf("Not a valid app context instruction type")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
log.Error("ac.rtc.RtcGet()", log.Fields{"err": err})
return nil, err
}
s := fmt.Sprintf("%v", rh) + "app/" + "instruction/" + insttype + "/"
log.Info("Getting app instruction", log.Fields{"s": s})
var v string
err = ac.rtc.RtcGetValue(s, &v)
if err != nil {
log.Error("ac.rtc.RtcGetValue(s, &v)", log.Fields{"err": err})
return nil, err
}
return v, nil
}
//Update the instruction usign the given handle
func (ac *AppContext) UpdateInstructionValue(handle interface{}, value interface{}) error {
return ac.rtc.RtcUpdateValue(handle, value)
}
//Returns the resource instruction for a given instruction type
func (ac *AppContext) GetResourceInstruction(appname string, clustername string, insttype string) (interface{}, error) {
if !(insttype == "order" || insttype == "dependency") {
log.Error("Not a valid app context instruction type", log.Fields{})
return nil, pkgerrors.Errorf("Not a valid app context instruction type")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
log.Error("ac.rtc.RtcGet()", log.Fields{"err": err})
return nil, err
}
s := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/resource/instruction/" + insttype + "/"
var v string
err = ac.rtc.RtcGetValue(s, &v)
if err != nil {
log.Error("ac.rtc.RtcGetValue(s, &v)", log.Fields{"err": err})
return nil, err
}
return v, nil
}
// AddLevelValue for holding a state object at a given level
// will make a handle with an appended "<level>/" to the key
func (ac *AppContext) AddLevelValue(handle interface{}, level string, value interface{}) (interface{}, error) {
h, err := ac.rtc.RtcAddOneLevel(handle, level, value)
if err != nil {
return nil, err
}
log.Info(":: Added handle ::", log.Fields{"Handle": h})
return h, nil
}
// GetClusterStatusHandle returns the handle for cluster status for a given app and cluster
func (ac *AppContext) GetClusterStatusHandle(appname string, clustername string) (interface{}, error) {
if appname == "" {
return nil, pkgerrors.Errorf("Not a valid run time context app name")
}
if clustername == "" {
return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
}
rh, err := ac.rtc.RtcGet()
if err != nil {
return nil, err
}
acrh := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/status/"
hs, err := ac.rtc.RtcGetHandles(acrh)
if err != nil {
return nil, err
}
for _, v := range hs {
if v == acrh {
return v, nil
}
}
return nil, pkgerrors.Errorf("No handle was found for the given resource")
}
//UpdateStatusValue updates the status value with the given handle
func (ac *AppContext) UpdateStatusValue(handle interface{}, value interface{}) error {
return ac.rtc.RtcUpdateValue(handle, value)
}
//UpdateValue updates the state value with the given handle
func (ac *AppContext) UpdateValue(handle interface{}, value interface{}) error {
return ac.rtc.RtcUpdateValue(handle, value)
}
//Return all the handles under the composite app
func (ac *AppContext) GetAllHandles(handle interface{}) ([]interface{}, error) {
hs, err := ac.rtc.RtcGetHandles(handle)
if err != nil {
return nil, err
}
return hs, nil
}
//Returns the value for a given handle
func (ac *AppContext) GetValue(handle interface{}) (interface{}, error) {
var v interface{}
err := ac.rtc.RtcGetValue(handle, &v)
if err != nil {
return nil, err
}
return v, nil
}
// GetCompositeAppMeta returns the meta data associated with the compositeApp
// Its return type is CompositeAppMeta
func (ac *AppContext) GetCompositeAppMeta() (CompositeAppMeta, error) {
mi, err := ac.rtcObj.RtcGetMeta()
if err != nil {
return CompositeAppMeta{}, pkgerrors.Errorf("Failed to get compositeApp meta")
}
datamap, ok := mi.(map[string]interface{})
if ok == false {
return CompositeAppMeta{}, pkgerrors.Errorf("Failed to cast meta interface to compositeApp meta")
}
p := fmt.Sprintf("%v", datamap["Project"])
ca := fmt.Sprintf("%v", datamap["CompositeApp"])
v := fmt.Sprintf("%v", datamap["Version"])
rn := fmt.Sprintf("%v", datamap["Release"])
dig := fmt.Sprintf("%v", datamap["DeploymentIntentGroup"])
namespace := fmt.Sprintf("%v", datamap["Namespace"])
level := fmt.Sprintf("%v", datamap["Level"])
var childInterface []interface{}
childCtxs := make([]string, len(childInterface))
if datamap["ChildContextIDs"] != nil {
childInterface = datamap["ChildContextIDs"].([]interface{})
for _, v := range childInterface {
childCtxs = append(childCtxs, v.(string))
}
}
return CompositeAppMeta{Project: p, CompositeApp: ca, Version: v, Release: rn, DeploymentIntentGroup: dig, Namespace: namespace, Level: level, ChildContextIDs: childCtxs}, nil
}
| {
return nil, pkgerrors.Errorf("Not a valid run time context app name")
} |
input.rs | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
use std::fmt::Write;
/// See [`CreateCertificateAuthorityInput`](crate::input::CreateCertificateAuthorityInput)
pub mod create_certificate_authority_input {
/// A builder for [`CreateCertificateAuthorityInput`](crate::input::CreateCertificateAuthorityInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_configuration:
std::option::Option<crate::model::CertificateAuthorityConfiguration>,
pub(crate) revocation_configuration:
std::option::Option<crate::model::RevocationConfiguration>,
pub(crate) certificate_authority_type:
std::option::Option<crate::model::CertificateAuthorityType>,
pub(crate) idempotency_token: std::option::Option<std::string::String>,
pub(crate) key_storage_security_standard:
std::option::Option<crate::model::KeyStorageSecurityStandard>,
pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl Builder {
/// <p>Name and bit size of the private key algorithm, the name of the signing algorithm, and
/// X.500 certificate subject information.</p>
pub fn certificate_authority_configuration(
mut self,
input: crate::model::CertificateAuthorityConfiguration,
) -> Self {
self.certificate_authority_configuration = Some(input);
self
}
pub fn set_certificate_authority_configuration(
mut self,
input: std::option::Option<crate::model::CertificateAuthorityConfiguration>,
) -> Self {
self.certificate_authority_configuration = input;
self
}
/// <p>Contains information to enable Online Certificate Status Protocol (OCSP) support,
/// to enable a certificate revocation list (CRL), to enable both, or to enable neither. The
/// default is for both certificate validation mechanisms to be disabled. For more
/// information, see the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_OcspConfiguration.html">OcspConfiguration</a> and <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CrlConfiguration.html">CrlConfiguration</a> types.</p>
pub fn revocation_configuration(
mut self,
input: crate::model::RevocationConfiguration,
) -> Self {
self.revocation_configuration = Some(input);
self
}
pub fn set_revocation_configuration(
mut self,
input: std::option::Option<crate::model::RevocationConfiguration>,
) -> Self {
self.revocation_configuration = input;
self
}
/// <p>The type of the certificate authority.</p>
pub fn certificate_authority_type(
mut self,
input: crate::model::CertificateAuthorityType,
) -> Self {
self.certificate_authority_type = Some(input);
self
}
pub fn set_certificate_authority_type(
mut self,
input: std::option::Option<crate::model::CertificateAuthorityType>,
) -> Self {
self.certificate_authority_type = input;
self
}
/// <p>Custom string that can be used to distinguish between calls to the <b>CreateCertificateAuthority</b> action. Idempotency tokens for
/// <b>CreateCertificateAuthority</b> time out after five
/// minutes. Therefore, if you call <b>CreateCertificateAuthority</b> multiple times with the same idempotency
/// token within five minutes, ACM Private CA recognizes that you are requesting only certificate
/// authority and will issue only one. If you change the idempotency token for each call,
/// PCA recognizes that you are requesting multiple certificate authorities.</p>
pub fn idempotency_token(mut self, input: impl Into<std::string::String>) -> Self {
self.idempotency_token = Some(input.into());
self
}
pub fn set_idempotency_token(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.idempotency_token = input;
self
}
/// <p>Specifies a
/// cryptographic key management compliance standard used for handling CA keys.</p>
/// <p>Default: FIPS_140_2_LEVEL_3_OR_HIGHER</p>
/// <p>Note: <code>FIPS_140_2_LEVEL_3_OR_HIGHER</code> is not supported in Region
/// ap-northeast-3. When creating a CA in the ap-northeast-3, you must provide
/// <code>FIPS_140_2_LEVEL_2_OR_HIGHER</code> as the argument for
/// <code>KeyStorageSecurityStandard</code>. Failure to do this results in an
/// <code>InvalidArgsException</code> with the message, "A certificate authority cannot
/// be created in this region with the specified security standard."</p>
pub fn key_storage_security_standard(
mut self,
input: crate::model::KeyStorageSecurityStandard,
) -> Self {
self.key_storage_security_standard = Some(input);
self
}
pub fn set_key_storage_security_standard(
mut self,
input: std::option::Option<crate::model::KeyStorageSecurityStandard>,
) -> Self {
self.key_storage_security_standard = input;
self
}
pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self {
let mut v = self.tags.unwrap_or_default();
v.push(input.into());
self.tags = Some(v);
self
}
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.tags = input;
self
}
/// Consumes the builder and constructs a [`CreateCertificateAuthorityInput`](crate::input::CreateCertificateAuthorityInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateCertificateAuthorityInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateCertificateAuthorityInput {
certificate_authority_configuration: self.certificate_authority_configuration,
revocation_configuration: self.revocation_configuration,
certificate_authority_type: self.certificate_authority_type,
idempotency_token: self.idempotency_token,
key_storage_security_standard: self.key_storage_security_standard,
tags: self.tags,
})
}
}
}
#[doc(hidden)]
pub type CreateCertificateAuthorityInputOperationOutputAlias =
crate::operation::CreateCertificateAuthority;
#[doc(hidden)]
pub type CreateCertificateAuthorityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl CreateCertificateAuthorityInput {
/// Consumes the builder and constructs an Operation<[`CreateCertificateAuthority`](crate::operation::CreateCertificateAuthority)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::CreateCertificateAuthority,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_create_certificate_authority(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::CreateCertificateAuthority::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"CreateCertificateAuthority",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.CreateCertificateAuthority",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`CreateCertificateAuthorityInput`](crate::input::CreateCertificateAuthorityInput)
pub fn builder() -> crate::input::create_certificate_authority_input::Builder {
crate::input::create_certificate_authority_input::Builder::default()
}
}
/// See [`CreateCertificateAuthorityAuditReportInput`](crate::input::CreateCertificateAuthorityAuditReportInput)
pub mod create_certificate_authority_audit_report_input {
/// A builder for [`CreateCertificateAuthorityAuditReportInput`](crate::input::CreateCertificateAuthorityAuditReportInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) s3_bucket_name: std::option::Option<std::string::String>,
pub(crate) audit_report_response_format:
std::option::Option<crate::model::AuditReportResponseFormat>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) of the CA to be audited. This is of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.</p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>The name of the S3 bucket that will contain the audit report.</p>
pub fn s3_bucket_name(mut self, input: impl Into<std::string::String>) -> Self {
self.s3_bucket_name = Some(input.into());
self
}
pub fn set_s3_bucket_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.s3_bucket_name = input;
self
}
/// <p>The format in which to create the report. This can be either <b>JSON</b> or <b>CSV</b>.</p>
pub fn audit_report_response_format(
mut self,
input: crate::model::AuditReportResponseFormat,
) -> Self {
self.audit_report_response_format = Some(input);
self
}
pub fn set_audit_report_response_format(
mut self,
input: std::option::Option<crate::model::AuditReportResponseFormat>,
) -> Self {
self.audit_report_response_format = input;
self
}
/// Consumes the builder and constructs a [`CreateCertificateAuthorityAuditReportInput`](crate::input::CreateCertificateAuthorityAuditReportInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateCertificateAuthorityAuditReportInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateCertificateAuthorityAuditReportInput {
certificate_authority_arn: self.certificate_authority_arn,
s3_bucket_name: self.s3_bucket_name,
audit_report_response_format: self.audit_report_response_format,
})
}
}
}
#[doc(hidden)]
pub type CreateCertificateAuthorityAuditReportInputOperationOutputAlias =
crate::operation::CreateCertificateAuthorityAuditReport;
#[doc(hidden)]
pub type CreateCertificateAuthorityAuditReportInputOperationRetryAlias =
aws_http::AwsErrorRetryPolicy;
impl CreateCertificateAuthorityAuditReportInput {
/// Consumes the builder and constructs an Operation<[`CreateCertificateAuthorityAuditReport`](crate::operation::CreateCertificateAuthorityAuditReport)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::CreateCertificateAuthorityAuditReport,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_create_certificate_authority_audit_report(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::CreateCertificateAuthorityAuditReport::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"CreateCertificateAuthorityAuditReport",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.CreateCertificateAuthorityAuditReport",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`CreateCertificateAuthorityAuditReportInput`](crate::input::CreateCertificateAuthorityAuditReportInput)
pub fn builder() -> crate::input::create_certificate_authority_audit_report_input::Builder {
crate::input::create_certificate_authority_audit_report_input::Builder::default()
}
}
/// See [`CreatePermissionInput`](crate::input::CreatePermissionInput)
pub mod create_permission_input {
/// A builder for [`CreatePermissionInput`](crate::input::CreatePermissionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) principal: std::option::Option<std::string::String>,
pub(crate) source_account: std::option::Option<std::string::String>,
pub(crate) actions: std::option::Option<std::vec::Vec<crate::model::ActionType>>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) of the CA that grants the permissions. You can find the
/// ARN by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action. This must have the following form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>The AWS service or identity that receives the permission. At this time, the only
/// valid principal is <code>acm.amazonaws.com</code>.</p>
pub fn principal(mut self, input: impl Into<std::string::String>) -> Self {
self.principal = Some(input.into());
self
}
pub fn set_principal(mut self, input: std::option::Option<std::string::String>) -> Self {
self.principal = input;
self
}
/// <p>The ID of the calling account.</p>
pub fn source_account(mut self, input: impl Into<std::string::String>) -> Self {
self.source_account = Some(input.into());
self
}
pub fn set_source_account(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.source_account = input;
self
}
pub fn actions(mut self, input: impl Into<crate::model::ActionType>) -> Self {
let mut v = self.actions.unwrap_or_default();
v.push(input.into());
self.actions = Some(v);
self
}
pub fn set_actions(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ActionType>>,
) -> Self {
self.actions = input;
self
}
/// Consumes the builder and constructs a [`CreatePermissionInput`](crate::input::CreatePermissionInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreatePermissionInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::CreatePermissionInput {
certificate_authority_arn: self.certificate_authority_arn,
principal: self.principal,
source_account: self.source_account,
actions: self.actions,
})
}
}
}
#[doc(hidden)]
pub type CreatePermissionInputOperationOutputAlias = crate::operation::CreatePermission;
#[doc(hidden)]
pub type CreatePermissionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl CreatePermissionInput {
/// Consumes the builder and constructs an Operation<[`CreatePermission`](crate::operation::CreatePermission)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::CreatePermission,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_create_permission(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::CreatePermission::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"CreatePermission",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.CreatePermission",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`CreatePermissionInput`](crate::input::CreatePermissionInput)
pub fn builder() -> crate::input::create_permission_input::Builder {
crate::input::create_permission_input::Builder::default()
}
}
/// See [`DeleteCertificateAuthorityInput`](crate::input::DeleteCertificateAuthorityInput)
pub mod delete_certificate_authority_input {
/// A builder for [`DeleteCertificateAuthorityInput`](crate::input::DeleteCertificateAuthorityInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) permanent_deletion_time_in_days: std::option::Option<i32>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must have the following form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>The number of days to make a CA restorable after it has been deleted. This can be
/// anywhere from 7 to 30 days, with 30 being the default.</p>
pub fn permanent_deletion_time_in_days(mut self, input: i32) -> Self {
self.permanent_deletion_time_in_days = Some(input);
self
}
pub fn set_permanent_deletion_time_in_days(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.permanent_deletion_time_in_days = input;
self
}
/// Consumes the builder and constructs a [`DeleteCertificateAuthorityInput`](crate::input::DeleteCertificateAuthorityInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeleteCertificateAuthorityInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::DeleteCertificateAuthorityInput {
certificate_authority_arn: self.certificate_authority_arn,
permanent_deletion_time_in_days: self.permanent_deletion_time_in_days,
})
}
}
}
#[doc(hidden)]
pub type DeleteCertificateAuthorityInputOperationOutputAlias =
crate::operation::DeleteCertificateAuthority;
#[doc(hidden)]
pub type DeleteCertificateAuthorityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl DeleteCertificateAuthorityInput {
/// Consumes the builder and constructs an Operation<[`DeleteCertificateAuthority`](crate::operation::DeleteCertificateAuthority)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::DeleteCertificateAuthority,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_delete_certificate_authority(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::DeleteCertificateAuthority::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"DeleteCertificateAuthority",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.DeleteCertificateAuthority",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`DeleteCertificateAuthorityInput`](crate::input::DeleteCertificateAuthorityInput)
pub fn builder() -> crate::input::delete_certificate_authority_input::Builder {
crate::input::delete_certificate_authority_input::Builder::default()
}
}
/// See [`DeletePermissionInput`](crate::input::DeletePermissionInput)
pub mod delete_permission_input {
/// A builder for [`DeletePermissionInput`](crate::input::DeletePermissionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) principal: std::option::Option<std::string::String>,
pub(crate) source_account: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Number (ARN) of the private CA that issued the permissions. You
/// can find the CA's ARN by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action. This must have the following form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>The AWS service or identity that will have its CA permissions revoked. At this time,
/// the only valid service principal is <code>acm.amazonaws.com</code>
/// </p>
pub fn principal(mut self, input: impl Into<std::string::String>) -> Self {
self.principal = Some(input.into());
self
}
pub fn set_principal(mut self, input: std::option::Option<std::string::String>) -> Self {
self.principal = input;
self
}
/// <p>The AWS account that calls this action.</p>
pub fn source_account(mut self, input: impl Into<std::string::String>) -> Self {
self.source_account = Some(input.into());
self
}
pub fn set_source_account(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.source_account = input;
self
}
/// Consumes the builder and constructs a [`DeletePermissionInput`](crate::input::DeletePermissionInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeletePermissionInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::DeletePermissionInput {
certificate_authority_arn: self.certificate_authority_arn,
principal: self.principal,
source_account: self.source_account,
})
}
}
}
#[doc(hidden)]
pub type DeletePermissionInputOperationOutputAlias = crate::operation::DeletePermission;
#[doc(hidden)]
pub type DeletePermissionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl DeletePermissionInput {
/// Consumes the builder and constructs an Operation<[`DeletePermission`](crate::operation::DeletePermission)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::DeletePermission,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_delete_permission(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::DeletePermission::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"DeletePermission",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.DeletePermission",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`DeletePermissionInput`](crate::input::DeletePermissionInput)
pub fn builder() -> crate::input::delete_permission_input::Builder {
crate::input::delete_permission_input::Builder::default()
}
}
/// See [`DeletePolicyInput`](crate::input::DeletePolicyInput)
pub mod delete_policy_input {
/// A builder for [`DeletePolicyInput`](crate::input::DeletePolicyInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) resource_arn: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Number (ARN) of the private CA that will have its policy deleted.
/// You can find the CA's ARN by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action. The ARN value must have the form
/// <code>arn:aws:acm-pca:region:account:certificate-authority/01234567-89ab-cdef-0123-0123456789ab</code>.
/// </p>
pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_arn = Some(input.into());
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.resource_arn = input;
self
}
/// Consumes the builder and constructs a [`DeletePolicyInput`](crate::input::DeletePolicyInput)
pub fn build(
self,
) -> std::result::Result<crate::input::DeletePolicyInput, smithy_http::operation::BuildError>
{
Ok(crate::input::DeletePolicyInput {
resource_arn: self.resource_arn,
})
}
}
}
#[doc(hidden)]
pub type DeletePolicyInputOperationOutputAlias = crate::operation::DeletePolicy;
#[doc(hidden)]
pub type DeletePolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl DeletePolicyInput {
/// Consumes the builder and constructs an Operation<[`DeletePolicy`](crate::operation::DeletePolicy)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::DeletePolicy,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_delete_policy(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::DeletePolicy::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"DeletePolicy",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.DeletePolicy",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`DeletePolicyInput`](crate::input::DeletePolicyInput)
pub fn builder() -> crate::input::delete_policy_input::Builder {
crate::input::delete_policy_input::Builder::default()
}
}
/// See [`DescribeCertificateAuthorityInput`](crate::input::DescribeCertificateAuthorityInput)
pub mod describe_certificate_authority_input {
/// A builder for [`DescribeCertificateAuthorityInput`](crate::input::DescribeCertificateAuthorityInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// Consumes the builder and constructs a [`DescribeCertificateAuthorityInput`](crate::input::DescribeCertificateAuthorityInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeCertificateAuthorityInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeCertificateAuthorityInput {
certificate_authority_arn: self.certificate_authority_arn,
})
}
}
}
#[doc(hidden)]
pub type DescribeCertificateAuthorityInputOperationOutputAlias =
crate::operation::DescribeCertificateAuthority;
#[doc(hidden)]
pub type DescribeCertificateAuthorityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl DescribeCertificateAuthorityInput {
/// Consumes the builder and constructs an Operation<[`DescribeCertificateAuthority`](crate::operation::DescribeCertificateAuthority)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::DescribeCertificateAuthority,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> |
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.DescribeCertificateAuthority",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`DescribeCertificateAuthorityInput`](crate::input::DescribeCertificateAuthorityInput)
pub fn builder() -> crate::input::describe_certificate_authority_input::Builder {
crate::input::describe_certificate_authority_input::Builder::default()
}
}
/// See [`DescribeCertificateAuthorityAuditReportInput`](crate::input::DescribeCertificateAuthorityAuditReportInput)
pub mod describe_certificate_authority_audit_report_input {
/// A builder for [`DescribeCertificateAuthorityAuditReportInput`](crate::input::DescribeCertificateAuthorityAuditReportInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) audit_report_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) of the private CA. This must be of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>The report ID returned by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthorityAuditReport.html">CreateCertificateAuthorityAuditReport</a> action.</p>
pub fn audit_report_id(mut self, input: impl Into<std::string::String>) -> Self {
self.audit_report_id = Some(input.into());
self
}
pub fn set_audit_report_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.audit_report_id = input;
self
}
/// Consumes the builder and constructs a [`DescribeCertificateAuthorityAuditReportInput`](crate::input::DescribeCertificateAuthorityAuditReportInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeCertificateAuthorityAuditReportInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeCertificateAuthorityAuditReportInput {
certificate_authority_arn: self.certificate_authority_arn,
audit_report_id: self.audit_report_id,
})
}
}
}
#[doc(hidden)]
pub type DescribeCertificateAuthorityAuditReportInputOperationOutputAlias =
crate::operation::DescribeCertificateAuthorityAuditReport;
#[doc(hidden)]
pub type DescribeCertificateAuthorityAuditReportInputOperationRetryAlias =
aws_http::AwsErrorRetryPolicy;
impl DescribeCertificateAuthorityAuditReportInput {
/// Consumes the builder and constructs an Operation<[`DescribeCertificateAuthorityAuditReport`](crate::operation::DescribeCertificateAuthorityAuditReport)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::DescribeCertificateAuthorityAuditReport,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_describe_certificate_authority_audit_report(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::DescribeCertificateAuthorityAuditReport::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"DescribeCertificateAuthorityAuditReport",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.DescribeCertificateAuthorityAuditReport",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`DescribeCertificateAuthorityAuditReportInput`](crate::input::DescribeCertificateAuthorityAuditReportInput)
pub fn builder() -> crate::input::describe_certificate_authority_audit_report_input::Builder {
crate::input::describe_certificate_authority_audit_report_input::Builder::default()
}
}
/// See [`GetCertificateInput`](crate::input::GetCertificateInput)
pub mod get_certificate_input {
/// A builder for [`GetCertificateInput`](crate::input::GetCertificateInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) certificate_arn: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>The ARN of the issued certificate. The ARN contains the certificate serial number and
/// must be in the following form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>/certificate/<i>286535153982981100925020015808220737245</i>
/// </code>
/// </p>
pub fn certificate_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_arn = Some(input.into());
self
}
pub fn set_certificate_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_arn = input;
self
}
/// Consumes the builder and constructs a [`GetCertificateInput`](crate::input::GetCertificateInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::GetCertificateInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::GetCertificateInput {
certificate_authority_arn: self.certificate_authority_arn,
certificate_arn: self.certificate_arn,
})
}
}
}
#[doc(hidden)]
pub type GetCertificateInputOperationOutputAlias = crate::operation::GetCertificate;
#[doc(hidden)]
pub type GetCertificateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl GetCertificateInput {
/// Consumes the builder and constructs an Operation<[`GetCertificate`](crate::operation::GetCertificate)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::GetCertificate,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_get_certificate(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::GetCertificate::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"GetCertificate",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.GetCertificate",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`GetCertificateInput`](crate::input::GetCertificateInput)
pub fn builder() -> crate::input::get_certificate_input::Builder {
crate::input::get_certificate_input::Builder::default()
}
}
/// See [`GetCertificateAuthorityCertificateInput`](crate::input::GetCertificateAuthorityCertificateInput)
pub mod get_certificate_authority_certificate_input {
/// A builder for [`GetCertificateAuthorityCertificateInput`](crate::input::GetCertificateAuthorityCertificateInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) of your private CA. This is of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// Consumes the builder and constructs a [`GetCertificateAuthorityCertificateInput`](crate::input::GetCertificateAuthorityCertificateInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::GetCertificateAuthorityCertificateInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::GetCertificateAuthorityCertificateInput {
certificate_authority_arn: self.certificate_authority_arn,
})
}
}
}
#[doc(hidden)]
pub type GetCertificateAuthorityCertificateInputOperationOutputAlias =
crate::operation::GetCertificateAuthorityCertificate;
#[doc(hidden)]
pub type GetCertificateAuthorityCertificateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl GetCertificateAuthorityCertificateInput {
/// Consumes the builder and constructs an Operation<[`GetCertificateAuthorityCertificate`](crate::operation::GetCertificateAuthorityCertificate)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::GetCertificateAuthorityCertificate,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_get_certificate_authority_certificate(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::GetCertificateAuthorityCertificate::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"GetCertificateAuthorityCertificate",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.GetCertificateAuthorityCertificate",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`GetCertificateAuthorityCertificateInput`](crate::input::GetCertificateAuthorityCertificateInput)
pub fn builder() -> crate::input::get_certificate_authority_certificate_input::Builder {
crate::input::get_certificate_authority_certificate_input::Builder::default()
}
}
/// See [`GetCertificateAuthorityCsrInput`](crate::input::GetCertificateAuthorityCsrInput)
pub mod get_certificate_authority_csr_input {
/// A builder for [`GetCertificateAuthorityCsrInput`](crate::input::GetCertificateAuthorityCsrInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a> action. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// Consumes the builder and constructs a [`GetCertificateAuthorityCsrInput`](crate::input::GetCertificateAuthorityCsrInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::GetCertificateAuthorityCsrInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::GetCertificateAuthorityCsrInput {
certificate_authority_arn: self.certificate_authority_arn,
})
}
}
}
#[doc(hidden)]
pub type GetCertificateAuthorityCsrInputOperationOutputAlias =
crate::operation::GetCertificateAuthorityCsr;
#[doc(hidden)]
pub type GetCertificateAuthorityCsrInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl GetCertificateAuthorityCsrInput {
/// Consumes the builder and constructs an Operation<[`GetCertificateAuthorityCsr`](crate::operation::GetCertificateAuthorityCsr)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::GetCertificateAuthorityCsr,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_get_certificate_authority_csr(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::GetCertificateAuthorityCsr::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"GetCertificateAuthorityCsr",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.GetCertificateAuthorityCsr",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`GetCertificateAuthorityCsrInput`](crate::input::GetCertificateAuthorityCsrInput)
pub fn builder() -> crate::input::get_certificate_authority_csr_input::Builder {
crate::input::get_certificate_authority_csr_input::Builder::default()
}
}
/// See [`GetPolicyInput`](crate::input::GetPolicyInput)
pub mod get_policy_input {
/// A builder for [`GetPolicyInput`](crate::input::GetPolicyInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) resource_arn: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Number (ARN) of the private CA that will have its policy
/// retrieved. You can find the CA's ARN by calling the ListCertificateAuthorities action.
/// </p>
pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_arn = Some(input.into());
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.resource_arn = input;
self
}
/// Consumes the builder and constructs a [`GetPolicyInput`](crate::input::GetPolicyInput)
pub fn build(
self,
) -> std::result::Result<crate::input::GetPolicyInput, smithy_http::operation::BuildError>
{
Ok(crate::input::GetPolicyInput {
resource_arn: self.resource_arn,
})
}
}
}
#[doc(hidden)]
pub type GetPolicyInputOperationOutputAlias = crate::operation::GetPolicy;
#[doc(hidden)]
pub type GetPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl GetPolicyInput {
/// Consumes the builder and constructs an Operation<[`GetPolicy`](crate::operation::GetPolicy)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::GetPolicy,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body = crate::operation_ser::serialize_operation_crate_operation_get_policy(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op =
smithy_http::operation::Operation::new(request, crate::operation::GetPolicy::new())
.with_metadata(smithy_http::operation::Metadata::new("GetPolicy", "acmpca"));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.GetPolicy",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`GetPolicyInput`](crate::input::GetPolicyInput)
pub fn builder() -> crate::input::get_policy_input::Builder {
crate::input::get_policy_input::Builder::default()
}
}
/// See [`ImportCertificateAuthorityCertificateInput`](crate::input::ImportCertificateAuthorityCertificateInput)
pub mod import_certificate_authority_certificate_input {
/// A builder for [`ImportCertificateAuthorityCertificateInput`](crate::input::ImportCertificateAuthorityCertificateInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) certificate: std::option::Option<smithy_types::Blob>,
pub(crate) certificate_chain: std::option::Option<smithy_types::Blob>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>The PEM-encoded certificate for a private CA. This may be a self-signed certificate in
/// the case of a root CA, or it may be signed by another CA that you control.</p>
pub fn certificate(mut self, input: smithy_types::Blob) -> Self {
self.certificate = Some(input);
self
}
pub fn set_certificate(mut self, input: std::option::Option<smithy_types::Blob>) -> Self {
self.certificate = input;
self
}
/// <p>A PEM-encoded file that contains all of your certificates, other than the certificate
/// you're importing, chaining up to your root CA. Your ACM Private CA-hosted or on-premises root
/// certificate is the last in the chain, and each certificate in the chain signs the one
/// preceding. </p>
/// <p>This parameter must be supplied when you import a subordinate CA. When you import a
/// root CA, there is no chain.</p>
pub fn certificate_chain(mut self, input: smithy_types::Blob) -> Self {
self.certificate_chain = Some(input);
self
}
pub fn set_certificate_chain(
mut self,
input: std::option::Option<smithy_types::Blob>,
) -> Self {
self.certificate_chain = input;
self
}
/// Consumes the builder and constructs a [`ImportCertificateAuthorityCertificateInput`](crate::input::ImportCertificateAuthorityCertificateInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ImportCertificateAuthorityCertificateInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::ImportCertificateAuthorityCertificateInput {
certificate_authority_arn: self.certificate_authority_arn,
certificate: self.certificate,
certificate_chain: self.certificate_chain,
})
}
}
}
#[doc(hidden)]
pub type ImportCertificateAuthorityCertificateInputOperationOutputAlias =
crate::operation::ImportCertificateAuthorityCertificate;
#[doc(hidden)]
pub type ImportCertificateAuthorityCertificateInputOperationRetryAlias =
aws_http::AwsErrorRetryPolicy;
impl ImportCertificateAuthorityCertificateInput {
/// Consumes the builder and constructs an Operation<[`ImportCertificateAuthorityCertificate`](crate::operation::ImportCertificateAuthorityCertificate)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::ImportCertificateAuthorityCertificate,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_import_certificate_authority_certificate(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::ImportCertificateAuthorityCertificate::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"ImportCertificateAuthorityCertificate",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.ImportCertificateAuthorityCertificate",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`ImportCertificateAuthorityCertificateInput`](crate::input::ImportCertificateAuthorityCertificateInput)
pub fn builder() -> crate::input::import_certificate_authority_certificate_input::Builder {
crate::input::import_certificate_authority_certificate_input::Builder::default()
}
}
/// See [`IssueCertificateInput`](crate::input::IssueCertificateInput)
pub mod issue_certificate_input {
/// A builder for [`IssueCertificateInput`](crate::input::IssueCertificateInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) api_passthrough: std::option::Option<crate::model::ApiPassthrough>,
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) csr: std::option::Option<smithy_types::Blob>,
pub(crate) signing_algorithm: std::option::Option<crate::model::SigningAlgorithm>,
pub(crate) template_arn: std::option::Option<std::string::String>,
pub(crate) validity: std::option::Option<crate::model::Validity>,
pub(crate) validity_not_before: std::option::Option<crate::model::Validity>,
pub(crate) idempotency_token: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Specifies X.509 certificate information to be included in the issued certificate. An
/// <code>APIPassthrough</code> or <code>APICSRPassthrough</code> template variant must
/// be selected, or else this parameter is ignored. For more information about using these
/// templates, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/UsingTemplates.html">Understanding Certificate Templates</a>.</p>
/// <p>If conflicting or duplicate certificate information is supplied during certificate
/// issuance, ACM Private CA applies <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/UsingTemplates.html#template-order-of-operations">order of
/// operation rules</a> to determine what information is used.</p>
pub fn api_passthrough(mut self, input: crate::model::ApiPassthrough) -> Self {
self.api_passthrough = Some(input);
self
}
pub fn set_api_passthrough(
mut self,
input: std::option::Option<crate::model::ApiPassthrough>,
) -> Self {
self.api_passthrough = input;
self
}
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>The certificate signing request (CSR) for the certificate you want to issue. As an
/// example, you can use the following OpenSSL command to create the CSR and a 2048 bit RSA
/// private key. </p>
/// <p>
/// <code>openssl req -new -newkey rsa:2048 -days 365 -keyout private/test_cert_priv_key.pem
/// -out csr/test_cert_.csr</code>
/// </p>
/// <p>If you have a configuration file, you can then use the following OpenSSL command. The
/// <code>usr_cert</code> block in the configuration file contains your X509 version 3
/// extensions. </p>
/// <p>
/// <code>openssl req -new -config openssl_rsa.cnf -extensions usr_cert -newkey rsa:2048
/// -days -365 -keyout private/test_cert_priv_key.pem -out
/// csr/test_cert_.csr</code>
/// </p>
/// <p>Note: A CSR must provide either a <i>subject name</i> or a
/// <i>subject alternative name</i> or the request will be rejected.
/// </p>
pub fn csr(mut self, input: smithy_types::Blob) -> Self {
self.csr = Some(input);
self
}
pub fn set_csr(mut self, input: std::option::Option<smithy_types::Blob>) -> Self {
self.csr = input;
self
}
/// <p>The name of the algorithm that will be used to sign the certificate to be issued. </p>
/// <p>This parameter should not be confused with the <code>SigningAlgorithm</code> parameter
/// used to sign a CSR in the <code>CreateCertificateAuthority</code> action.</p>
pub fn signing_algorithm(mut self, input: crate::model::SigningAlgorithm) -> Self {
self.signing_algorithm = Some(input);
self
}
pub fn set_signing_algorithm(
mut self,
input: std::option::Option<crate::model::SigningAlgorithm>,
) -> Self {
self.signing_algorithm = input;
self
}
/// <p>Specifies a custom configuration template to use when issuing a certificate. If this
/// parameter is not provided, ACM Private CA defaults to the <code>EndEntityCertificate/V1</code>
/// template. For CA certificates, you should choose the shortest path length that meets
/// your needs. The path length is indicated by the PathLen<i>N</i> portion of
/// the ARN, where <i>N</i> is the <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaTerms.html#terms-cadepth">CA depth</a>.</p>
/// <p>Note: The CA depth configured on a subordinate CA certificate must not exceed the
/// limit set by its parents in the CA hierarchy.</p>
/// <p>For a list of <code>TemplateArn</code> values supported by ACM Private CA, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/UsingTemplates.html">Understanding Certificate
/// Templates</a>.</p>
pub fn template_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.template_arn = Some(input.into());
self
}
pub fn set_template_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.template_arn = input;
self
}
/// <p>Information describing the end of the validity period of the certificate. This
/// parameter sets the “Not After” date for the certificate.</p>
/// <p>Certificate validity is the period of time during which a certificate is valid.
/// Validity can be expressed as an explicit date and time when the certificate expires, or
/// as a span of time after issuance, stated in days, months, or years. For more
/// information, see <a href="https://tools.ietf.org/html/rfc5280#section-4.1.2.5">Validity</a> in RFC 5280. </p>
/// <p>This value is unaffected when <code>ValidityNotBefore</code> is also specified. For
/// example, if <code>Validity</code> is set to 20 days in the future, the certificate will
/// expire 20 days from issuance time regardless of the <code>ValidityNotBefore</code>
/// value.</p>
/// <p>The end of the validity period configured on a certificate must not exceed the limit
/// set on its parents in the CA hierarchy.</p>
pub fn validity(mut self, input: crate::model::Validity) -> Self {
self.validity = Some(input);
self
}
pub fn set_validity(mut self, input: std::option::Option<crate::model::Validity>) -> Self {
self.validity = input;
self
}
/// <p>Information describing the start of the validity period of the certificate. This
/// parameter sets the “Not Before" date for the certificate.</p>
/// <p>By default, when issuing a certificate, ACM Private CA sets the "Not Before" date to the
/// issuance time minus 60 minutes. This compensates for clock inconsistencies across
/// computer systems. The <code>ValidityNotBefore</code> parameter can be used to customize
/// the “Not Before” value. </p>
/// <p>Unlike the <code>Validity</code> parameter, the <code>ValidityNotBefore</code>
/// parameter is optional.</p>
/// <p>The <code>ValidityNotBefore</code> value is expressed as an explicit date and time,
/// using the <code>Validity</code> type value <code>ABSOLUTE</code>. For more information,
/// see <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_Validity.html">Validity</a> in this API reference and <a href="https://tools.ietf.org/html/rfc5280#section-4.1.2.5">Validity</a> in RFC
/// 5280.</p>
pub fn validity_not_before(mut self, input: crate::model::Validity) -> Self {
self.validity_not_before = Some(input);
self
}
pub fn set_validity_not_before(
mut self,
input: std::option::Option<crate::model::Validity>,
) -> Self {
self.validity_not_before = input;
self
}
/// <p>Alphanumeric string that can be used to distinguish between calls to the <b>IssueCertificate</b> action. Idempotency tokens for <b>IssueCertificate</b> time out after one minute. Therefore, if you
/// call <b>IssueCertificate</b> multiple times with the same
/// idempotency token within one minute, ACM Private CA recognizes that you are requesting only one
/// certificate and will issue only one. If you change the idempotency token for each call,
/// PCA recognizes that you are requesting multiple certificates.</p>
pub fn idempotency_token(mut self, input: impl Into<std::string::String>) -> Self {
self.idempotency_token = Some(input.into());
self
}
pub fn set_idempotency_token(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.idempotency_token = input;
self
}
/// Consumes the builder and constructs a [`IssueCertificateInput`](crate::input::IssueCertificateInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::IssueCertificateInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::IssueCertificateInput {
api_passthrough: self.api_passthrough,
certificate_authority_arn: self.certificate_authority_arn,
csr: self.csr,
signing_algorithm: self.signing_algorithm,
template_arn: self.template_arn,
validity: self.validity,
validity_not_before: self.validity_not_before,
idempotency_token: self.idempotency_token,
})
}
}
}
#[doc(hidden)]
pub type IssueCertificateInputOperationOutputAlias = crate::operation::IssueCertificate;
#[doc(hidden)]
pub type IssueCertificateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl IssueCertificateInput {
/// Consumes the builder and constructs an Operation<[`IssueCertificate`](crate::operation::IssueCertificate)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::IssueCertificate,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_issue_certificate(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::IssueCertificate::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"IssueCertificate",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.IssueCertificate",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`IssueCertificateInput`](crate::input::IssueCertificateInput)
pub fn builder() -> crate::input::issue_certificate_input::Builder {
crate::input::issue_certificate_input::Builder::default()
}
}
/// See [`ListCertificateAuthoritiesInput`](crate::input::ListCertificateAuthoritiesInput)
pub mod list_certificate_authorities_input {
/// A builder for [`ListCertificateAuthoritiesInput`](crate::input::ListCertificateAuthoritiesInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) max_results: std::option::Option<i32>,
pub(crate) resource_owner: std::option::Option<crate::model::ResourceOwner>,
}
impl Builder {
/// <p>Use this parameter when paginating results in a subsequent request after you receive a
/// response with truncated results. Set it to the value of the <code>NextToken</code>
/// parameter from the response you just received.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>Use this parameter when paginating results to specify the maximum number of items to
/// return in the response on each page. If additional items exist beyond the number you
/// specify, the <code>NextToken</code> element is sent in the response. Use this
/// <code>NextToken</code> value in a subsequent request to retrieve additional
/// items.</p>
pub fn max_results(mut self, input: i32) -> Self {
self.max_results = Some(input);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.max_results = input;
self
}
/// <p>Use this parameter to filter the returned set of certificate authorities based on
/// their owner. The default is SELF.</p>
pub fn resource_owner(mut self, input: crate::model::ResourceOwner) -> Self {
self.resource_owner = Some(input);
self
}
pub fn set_resource_owner(
mut self,
input: std::option::Option<crate::model::ResourceOwner>,
) -> Self {
self.resource_owner = input;
self
}
/// Consumes the builder and constructs a [`ListCertificateAuthoritiesInput`](crate::input::ListCertificateAuthoritiesInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ListCertificateAuthoritiesInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::ListCertificateAuthoritiesInput {
next_token: self.next_token,
max_results: self.max_results,
resource_owner: self.resource_owner,
})
}
}
}
#[doc(hidden)]
pub type ListCertificateAuthoritiesInputOperationOutputAlias =
crate::operation::ListCertificateAuthorities;
#[doc(hidden)]
pub type ListCertificateAuthoritiesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl ListCertificateAuthoritiesInput {
/// Consumes the builder and constructs an Operation<[`ListCertificateAuthorities`](crate::operation::ListCertificateAuthorities)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::ListCertificateAuthorities,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_list_certificate_authorities(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::ListCertificateAuthorities::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"ListCertificateAuthorities",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.ListCertificateAuthorities",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`ListCertificateAuthoritiesInput`](crate::input::ListCertificateAuthoritiesInput)
pub fn builder() -> crate::input::list_certificate_authorities_input::Builder {
crate::input::list_certificate_authorities_input::Builder::default()
}
}
/// See [`ListPermissionsInput`](crate::input::ListPermissionsInput)
pub mod list_permissions_input {
/// A builder for [`ListPermissionsInput`](crate::input::ListPermissionsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) max_results: std::option::Option<i32>,
}
impl Builder {
/// <p>The Amazon Resource Number (ARN) of the private CA to inspect. You can find the ARN by
/// calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action. This must be of the form:
/// <code>arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012</code>
/// You can get a private CA's ARN by running the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action.</p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>When paginating results, use this parameter in a subsequent request after you receive
/// a response with truncated results. Set it to the value of <b>NextToken</b> from the response you just received.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>When paginating results, use this parameter to specify the maximum number of items to
/// return in the response. If additional items exist beyond the number you specify, the
/// <b>NextToken</b> element is sent in the response. Use this
/// <b>NextToken</b> value in a subsequent request to retrieve
/// additional items.</p>
pub fn max_results(mut self, input: i32) -> Self {
self.max_results = Some(input);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.max_results = input;
self
}
/// Consumes the builder and constructs a [`ListPermissionsInput`](crate::input::ListPermissionsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ListPermissionsInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::ListPermissionsInput {
certificate_authority_arn: self.certificate_authority_arn,
next_token: self.next_token,
max_results: self.max_results,
})
}
}
}
#[doc(hidden)]
pub type ListPermissionsInputOperationOutputAlias = crate::operation::ListPermissions;
#[doc(hidden)]
pub type ListPermissionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl ListPermissionsInput {
/// Consumes the builder and constructs an Operation<[`ListPermissions`](crate::operation::ListPermissions)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::ListPermissions,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_list_permissions(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::ListPermissions::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"ListPermissions",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.ListPermissions",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`ListPermissionsInput`](crate::input::ListPermissionsInput)
pub fn builder() -> crate::input::list_permissions_input::Builder {
crate::input::list_permissions_input::Builder::default()
}
}
/// See [`ListTagsInput`](crate::input::ListTagsInput)
pub mod list_tags_input {
/// A builder for [`ListTagsInput`](crate::input::ListTagsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) max_results: std::option::Option<i32>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a> action. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>Use this parameter when paginating results in a subsequent request after you receive a
/// response with truncated results. Set it to the value of <b>NextToken</b> from the response you just received.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>Use this parameter when paginating results to specify the maximum number of items to
/// return in the response. If additional items exist beyond the number you specify, the
/// <b>NextToken</b> element is sent in the response. Use this
/// <b>NextToken</b> value in a subsequent request to retrieve
/// additional items.</p>
pub fn max_results(mut self, input: i32) -> Self {
self.max_results = Some(input);
self
}
pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self {
self.max_results = input;
self
}
/// Consumes the builder and constructs a [`ListTagsInput`](crate::input::ListTagsInput)
pub fn build(
self,
) -> std::result::Result<crate::input::ListTagsInput, smithy_http::operation::BuildError>
{
Ok(crate::input::ListTagsInput {
certificate_authority_arn: self.certificate_authority_arn,
next_token: self.next_token,
max_results: self.max_results,
})
}
}
}
#[doc(hidden)]
pub type ListTagsInputOperationOutputAlias = crate::operation::ListTags;
#[doc(hidden)]
pub type ListTagsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl ListTagsInput {
/// Consumes the builder and constructs an Operation<[`ListTags`](crate::operation::ListTags)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::ListTags,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body = crate::operation_ser::serialize_operation_crate_operation_list_tags(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op =
smithy_http::operation::Operation::new(request, crate::operation::ListTags::new())
.with_metadata(smithy_http::operation::Metadata::new("ListTags", "acmpca"));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.ListTags",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`ListTagsInput`](crate::input::ListTagsInput)
pub fn builder() -> crate::input::list_tags_input::Builder {
crate::input::list_tags_input::Builder::default()
}
}
/// See [`PutPolicyInput`](crate::input::PutPolicyInput)
pub mod put_policy_input {
/// A builder for [`PutPolicyInput`](crate::input::PutPolicyInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) resource_arn: std::option::Option<std::string::String>,
pub(crate) policy: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Number (ARN) of the private CA to associate with the policy. The
/// ARN of the CA can be found by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action.</p>
/// <p></p>
pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_arn = Some(input.into());
self
}
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.resource_arn = input;
self
}
/// <p>The path and file name of a JSON-formatted IAM policy to attach to the specified
/// private CA resource. If this policy does not contain all required statements or if it
/// includes any statement that is not allowed, the <code>PutPolicy</code> action returns an
/// <code>InvalidPolicyException</code>. For information about IAM policy and
/// statement structure, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json">Overview of JSON Policies</a>.</p>
pub fn policy(mut self, input: impl Into<std::string::String>) -> Self {
self.policy = Some(input.into());
self
}
pub fn set_policy(mut self, input: std::option::Option<std::string::String>) -> Self {
self.policy = input;
self
}
/// Consumes the builder and constructs a [`PutPolicyInput`](crate::input::PutPolicyInput)
pub fn build(
self,
) -> std::result::Result<crate::input::PutPolicyInput, smithy_http::operation::BuildError>
{
Ok(crate::input::PutPolicyInput {
resource_arn: self.resource_arn,
policy: self.policy,
})
}
}
}
#[doc(hidden)]
pub type PutPolicyInputOperationOutputAlias = crate::operation::PutPolicy;
#[doc(hidden)]
pub type PutPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl PutPolicyInput {
/// Consumes the builder and constructs an Operation<[`PutPolicy`](crate::operation::PutPolicy)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::PutPolicy,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body = crate::operation_ser::serialize_operation_crate_operation_put_policy(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op =
smithy_http::operation::Operation::new(request, crate::operation::PutPolicy::new())
.with_metadata(smithy_http::operation::Metadata::new("PutPolicy", "acmpca"));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.PutPolicy",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`PutPolicyInput`](crate::input::PutPolicyInput)
pub fn builder() -> crate::input::put_policy_input::Builder {
crate::input::put_policy_input::Builder::default()
}
}
/// See [`RestoreCertificateAuthorityInput`](crate::input::RestoreCertificateAuthorityInput)
pub mod restore_certificate_authority_input {
/// A builder for [`RestoreCertificateAuthorityInput`](crate::input::RestoreCertificateAuthorityInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a> action. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// Consumes the builder and constructs a [`RestoreCertificateAuthorityInput`](crate::input::RestoreCertificateAuthorityInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RestoreCertificateAuthorityInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::RestoreCertificateAuthorityInput {
certificate_authority_arn: self.certificate_authority_arn,
})
}
}
}
#[doc(hidden)]
pub type RestoreCertificateAuthorityInputOperationOutputAlias =
crate::operation::RestoreCertificateAuthority;
#[doc(hidden)]
pub type RestoreCertificateAuthorityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl RestoreCertificateAuthorityInput {
/// Consumes the builder and constructs an Operation<[`RestoreCertificateAuthority`](crate::operation::RestoreCertificateAuthority)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::RestoreCertificateAuthority,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_restore_certificate_authority(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::RestoreCertificateAuthority::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"RestoreCertificateAuthority",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.RestoreCertificateAuthority",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`RestoreCertificateAuthorityInput`](crate::input::RestoreCertificateAuthorityInput)
pub fn builder() -> crate::input::restore_certificate_authority_input::Builder {
crate::input::restore_certificate_authority_input::Builder::default()
}
}
/// See [`RevokeCertificateInput`](crate::input::RevokeCertificateInput)
pub mod revoke_certificate_input {
/// A builder for [`RevokeCertificateInput`](crate::input::RevokeCertificateInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) certificate_serial: std::option::Option<std::string::String>,
pub(crate) revocation_reason: std::option::Option<crate::model::RevocationReason>,
}
impl Builder {
/// <p>Amazon Resource Name (ARN) of the private CA that issued the certificate to be
/// revoked. This must be of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>Serial number of the certificate to be revoked. This must be in hexadecimal format.
/// You can retrieve the serial number by calling <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_GetCertificate.html">GetCertificate</a> with the Amazon
/// Resource Name (ARN) of the certificate you want and the ARN of your private CA. The
/// <b>GetCertificate</b> action retrieves the certificate in
/// the PEM format. You can use the following OpenSSL command to list the certificate in
/// text format and copy the hexadecimal serial number. </p>
/// <p>
/// <code>openssl x509 -in <i>file_path</i> -text -noout</code>
/// </p>
/// <p>You can also copy the serial number from the console or use the <a href="https://docs.aws.amazon.com/acm/latest/APIReference/API_DescribeCertificate.html">DescribeCertificate</a> action in the <i>AWS Certificate Manager API
/// Reference</i>. </p>
pub fn certificate_serial(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_serial = Some(input.into());
self
}
pub fn set_certificate_serial(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_serial = input;
self
}
/// <p>Specifies why you revoked the certificate.</p>
pub fn revocation_reason(mut self, input: crate::model::RevocationReason) -> Self {
self.revocation_reason = Some(input);
self
}
pub fn set_revocation_reason(
mut self,
input: std::option::Option<crate::model::RevocationReason>,
) -> Self {
self.revocation_reason = input;
self
}
/// Consumes the builder and constructs a [`RevokeCertificateInput`](crate::input::RevokeCertificateInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RevokeCertificateInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::RevokeCertificateInput {
certificate_authority_arn: self.certificate_authority_arn,
certificate_serial: self.certificate_serial,
revocation_reason: self.revocation_reason,
})
}
}
}
#[doc(hidden)]
pub type RevokeCertificateInputOperationOutputAlias = crate::operation::RevokeCertificate;
#[doc(hidden)]
pub type RevokeCertificateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl RevokeCertificateInput {
/// Consumes the builder and constructs an Operation<[`RevokeCertificate`](crate::operation::RevokeCertificate)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::RevokeCertificate,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_revoke_certificate(&self)
.map_err(|err| {
smithy_http::operation::BuildError::SerializationError(err.into())
})?;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::RevokeCertificate::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"RevokeCertificate",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.RevokeCertificate",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`RevokeCertificateInput`](crate::input::RevokeCertificateInput)
pub fn builder() -> crate::input::revoke_certificate_input::Builder {
crate::input::revoke_certificate_input::Builder::default()
}
}
/// See [`TagCertificateAuthorityInput`](crate::input::TagCertificateAuthorityInput)
pub mod tag_certificate_authority_input {
/// A builder for [`TagCertificateAuthorityInput`](crate::input::TagCertificateAuthorityInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self {
let mut v = self.tags.unwrap_or_default();
v.push(input.into());
self.tags = Some(v);
self
}
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.tags = input;
self
}
/// Consumes the builder and constructs a [`TagCertificateAuthorityInput`](crate::input::TagCertificateAuthorityInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::TagCertificateAuthorityInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::TagCertificateAuthorityInput {
certificate_authority_arn: self.certificate_authority_arn,
tags: self.tags,
})
}
}
}
#[doc(hidden)]
pub type TagCertificateAuthorityInputOperationOutputAlias =
crate::operation::TagCertificateAuthority;
#[doc(hidden)]
pub type TagCertificateAuthorityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl TagCertificateAuthorityInput {
/// Consumes the builder and constructs an Operation<[`TagCertificateAuthority`](crate::operation::TagCertificateAuthority)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::TagCertificateAuthority,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_tag_certificate_authority(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::TagCertificateAuthority::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"TagCertificateAuthority",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.TagCertificateAuthority",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`TagCertificateAuthorityInput`](crate::input::TagCertificateAuthorityInput)
pub fn builder() -> crate::input::tag_certificate_authority_input::Builder {
crate::input::tag_certificate_authority_input::Builder::default()
}
}
/// See [`UntagCertificateAuthorityInput`](crate::input::UntagCertificateAuthorityInput)
pub mod untag_certificate_authority_input {
/// A builder for [`UntagCertificateAuthorityInput`](crate::input::UntagCertificateAuthorityInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl Builder {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self {
let mut v = self.tags.unwrap_or_default();
v.push(input.into());
self.tags = Some(v);
self
}
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.tags = input;
self
}
/// Consumes the builder and constructs a [`UntagCertificateAuthorityInput`](crate::input::UntagCertificateAuthorityInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::UntagCertificateAuthorityInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::UntagCertificateAuthorityInput {
certificate_authority_arn: self.certificate_authority_arn,
tags: self.tags,
})
}
}
}
#[doc(hidden)]
pub type UntagCertificateAuthorityInputOperationOutputAlias =
crate::operation::UntagCertificateAuthority;
#[doc(hidden)]
pub type UntagCertificateAuthorityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl UntagCertificateAuthorityInput {
/// Consumes the builder and constructs an Operation<[`UntagCertificateAuthority`](crate::operation::UntagCertificateAuthority)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::UntagCertificateAuthority,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_untag_certificate_authority(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::UntagCertificateAuthority::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"UntagCertificateAuthority",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.UntagCertificateAuthority",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`UntagCertificateAuthorityInput`](crate::input::UntagCertificateAuthorityInput)
pub fn builder() -> crate::input::untag_certificate_authority_input::Builder {
crate::input::untag_certificate_authority_input::Builder::default()
}
}
/// See [`UpdateCertificateAuthorityInput`](crate::input::UpdateCertificateAuthorityInput)
pub mod update_certificate_authority_input {
/// A builder for [`UpdateCertificateAuthorityInput`](crate::input::UpdateCertificateAuthorityInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) certificate_authority_arn: std::option::Option<std::string::String>,
pub(crate) revocation_configuration:
std::option::Option<crate::model::RevocationConfiguration>,
pub(crate) status: std::option::Option<crate::model::CertificateAuthorityStatus>,
}
impl Builder {
/// <p>Amazon Resource Name (ARN) of the private CA that issued the certificate to be
/// revoked. This must be of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub fn certificate_authority_arn(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_authority_arn = Some(input.into());
self
}
pub fn set_certificate_authority_arn(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_authority_arn = input;
self
}
/// <p>Contains information to enable Online Certificate Status Protocol (OCSP) support,
/// to enable a certificate revocation list (CRL), to enable both, or to enable neither. If
/// this parameter is not supplied, existing capibilites remain unchanged. For more
/// information, see the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_OcspConfiguration.html">OcspConfiguration</a> and <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CrlConfiguration.html">CrlConfiguration</a> types.</p>
pub fn revocation_configuration(
mut self,
input: crate::model::RevocationConfiguration,
) -> Self {
self.revocation_configuration = Some(input);
self
}
pub fn set_revocation_configuration(
mut self,
input: std::option::Option<crate::model::RevocationConfiguration>,
) -> Self {
self.revocation_configuration = input;
self
}
/// <p>Status of your private CA.</p>
pub fn status(mut self, input: crate::model::CertificateAuthorityStatus) -> Self {
self.status = Some(input);
self
}
pub fn set_status(
mut self,
input: std::option::Option<crate::model::CertificateAuthorityStatus>,
) -> Self {
self.status = input;
self
}
/// Consumes the builder and constructs a [`UpdateCertificateAuthorityInput`](crate::input::UpdateCertificateAuthorityInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::UpdateCertificateAuthorityInput,
smithy_http::operation::BuildError,
> {
Ok(crate::input::UpdateCertificateAuthorityInput {
certificate_authority_arn: self.certificate_authority_arn,
revocation_configuration: self.revocation_configuration,
status: self.status,
})
}
}
}
#[doc(hidden)]
pub type UpdateCertificateAuthorityInputOperationOutputAlias =
crate::operation::UpdateCertificateAuthority;
#[doc(hidden)]
pub type UpdateCertificateAuthorityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl UpdateCertificateAuthorityInput {
/// Consumes the builder and constructs an Operation<[`UpdateCertificateAuthority`](crate::operation::UpdateCertificateAuthority)>
#[allow(clippy::let_and_return)]
pub fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
smithy_http::operation::Operation<
crate::operation::UpdateCertificateAuthority,
aws_http::AwsErrorRetryPolicy,
>,
smithy_http::operation::BuildError,
> {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_update_certificate_authority(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::UpdateCertificateAuthority::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"UpdateCertificateAuthority",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
}
fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
&self,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut uri = String::new();
self.uri_base(&mut uri)?;
Ok(builder.method("POST").uri(uri))
}
#[allow(clippy::unnecessary_wraps)]
fn request_builder_base(
&self,
) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> {
let mut builder = self.update_http_builder(http::request::Builder::new())?;
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("content-type"),
"application/x-amz-json-1.1",
);
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"ACMPrivateCA.UpdateCertificateAuthority",
);
Ok(builder)
}
fn assemble(
mut builder: http::request::Builder,
body: smithy_http::body::SdkBody,
) -> http::request::Request<smithy_http::body::SdkBody> {
if let Some(content_length) = body.content_length() {
builder = smithy_http::header::set_header_if_absent(
builder,
http::header::CONTENT_LENGTH,
content_length,
);
}
builder.body(body).expect("should be valid request")
}
/// Creates a new builder-style object to manufacture [`UpdateCertificateAuthorityInput`](crate::input::UpdateCertificateAuthorityInput)
pub fn builder() -> crate::input::update_certificate_authority_input::Builder {
crate::input::update_certificate_authority_input::Builder::default()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UpdateCertificateAuthorityInput {
/// <p>Amazon Resource Name (ARN) of the private CA that issued the certificate to be
/// revoked. This must be of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>Contains information to enable Online Certificate Status Protocol (OCSP) support,
/// to enable a certificate revocation list (CRL), to enable both, or to enable neither. If
/// this parameter is not supplied, existing capibilites remain unchanged. For more
/// information, see the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_OcspConfiguration.html">OcspConfiguration</a> and <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CrlConfiguration.html">CrlConfiguration</a> types.</p>
pub revocation_configuration: std::option::Option<crate::model::RevocationConfiguration>,
/// <p>Status of your private CA.</p>
pub status: std::option::Option<crate::model::CertificateAuthorityStatus>,
}
impl std::fmt::Debug for UpdateCertificateAuthorityInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UpdateCertificateAuthorityInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("revocation_configuration", &self.revocation_configuration);
formatter.field("status", &self.status);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UntagCertificateAuthorityInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>List of tags to be removed from the CA.</p>
pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl std::fmt::Debug for UntagCertificateAuthorityInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UntagCertificateAuthorityInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("tags", &self.tags);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct TagCertificateAuthorityInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>List of tags to be associated with the CA.</p>
pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl std::fmt::Debug for TagCertificateAuthorityInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("TagCertificateAuthorityInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("tags", &self.tags);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RevokeCertificateInput {
/// <p>Amazon Resource Name (ARN) of the private CA that issued the certificate to be
/// revoked. This must be of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>Serial number of the certificate to be revoked. This must be in hexadecimal format.
/// You can retrieve the serial number by calling <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_GetCertificate.html">GetCertificate</a> with the Amazon
/// Resource Name (ARN) of the certificate you want and the ARN of your private CA. The
/// <b>GetCertificate</b> action retrieves the certificate in
/// the PEM format. You can use the following OpenSSL command to list the certificate in
/// text format and copy the hexadecimal serial number. </p>
/// <p>
/// <code>openssl x509 -in <i>file_path</i> -text -noout</code>
/// </p>
/// <p>You can also copy the serial number from the console or use the <a href="https://docs.aws.amazon.com/acm/latest/APIReference/API_DescribeCertificate.html">DescribeCertificate</a> action in the <i>AWS Certificate Manager API
/// Reference</i>. </p>
pub certificate_serial: std::option::Option<std::string::String>,
/// <p>Specifies why you revoked the certificate.</p>
pub revocation_reason: std::option::Option<crate::model::RevocationReason>,
}
impl std::fmt::Debug for RevokeCertificateInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RevokeCertificateInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("certificate_serial", &self.certificate_serial);
formatter.field("revocation_reason", &self.revocation_reason);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RestoreCertificateAuthorityInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a> action. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for RestoreCertificateAuthorityInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RestoreCertificateAuthorityInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct PutPolicyInput {
/// <p>The Amazon Resource Number (ARN) of the private CA to associate with the policy. The
/// ARN of the CA can be found by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action.</p>
/// <p></p>
pub resource_arn: std::option::Option<std::string::String>,
/// <p>The path and file name of a JSON-formatted IAM policy to attach to the specified
/// private CA resource. If this policy does not contain all required statements or if it
/// includes any statement that is not allowed, the <code>PutPolicy</code> action returns an
/// <code>InvalidPolicyException</code>. For information about IAM policy and
/// statement structure, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json">Overview of JSON Policies</a>.</p>
pub policy: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for PutPolicyInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("PutPolicyInput");
formatter.field("resource_arn", &self.resource_arn);
formatter.field("policy", &self.policy);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListTagsInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a> action. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>Use this parameter when paginating results in a subsequent request after you receive a
/// response with truncated results. Set it to the value of <b>NextToken</b> from the response you just received.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>Use this parameter when paginating results to specify the maximum number of items to
/// return in the response. If additional items exist beyond the number you specify, the
/// <b>NextToken</b> element is sent in the response. Use this
/// <b>NextToken</b> value in a subsequent request to retrieve
/// additional items.</p>
pub max_results: std::option::Option<i32>,
}
impl std::fmt::Debug for ListTagsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListTagsInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("next_token", &self.next_token);
formatter.field("max_results", &self.max_results);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListPermissionsInput {
/// <p>The Amazon Resource Number (ARN) of the private CA to inspect. You can find the ARN by
/// calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action. This must be of the form:
/// <code>arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012</code>
/// You can get a private CA's ARN by running the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action.</p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>When paginating results, use this parameter in a subsequent request after you receive
/// a response with truncated results. Set it to the value of <b>NextToken</b> from the response you just received.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>When paginating results, use this parameter to specify the maximum number of items to
/// return in the response. If additional items exist beyond the number you specify, the
/// <b>NextToken</b> element is sent in the response. Use this
/// <b>NextToken</b> value in a subsequent request to retrieve
/// additional items.</p>
pub max_results: std::option::Option<i32>,
}
impl std::fmt::Debug for ListPermissionsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListPermissionsInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("next_token", &self.next_token);
formatter.field("max_results", &self.max_results);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListCertificateAuthoritiesInput {
/// <p>Use this parameter when paginating results in a subsequent request after you receive a
/// response with truncated results. Set it to the value of the <code>NextToken</code>
/// parameter from the response you just received.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>Use this parameter when paginating results to specify the maximum number of items to
/// return in the response on each page. If additional items exist beyond the number you
/// specify, the <code>NextToken</code> element is sent in the response. Use this
/// <code>NextToken</code> value in a subsequent request to retrieve additional
/// items.</p>
pub max_results: std::option::Option<i32>,
/// <p>Use this parameter to filter the returned set of certificate authorities based on
/// their owner. The default is SELF.</p>
pub resource_owner: std::option::Option<crate::model::ResourceOwner>,
}
impl std::fmt::Debug for ListCertificateAuthoritiesInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListCertificateAuthoritiesInput");
formatter.field("next_token", &self.next_token);
formatter.field("max_results", &self.max_results);
formatter.field("resource_owner", &self.resource_owner);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct IssueCertificateInput {
/// <p>Specifies X.509 certificate information to be included in the issued certificate. An
/// <code>APIPassthrough</code> or <code>APICSRPassthrough</code> template variant must
/// be selected, or else this parameter is ignored. For more information about using these
/// templates, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/UsingTemplates.html">Understanding Certificate Templates</a>.</p>
/// <p>If conflicting or duplicate certificate information is supplied during certificate
/// issuance, ACM Private CA applies <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/UsingTemplates.html#template-order-of-operations">order of
/// operation rules</a> to determine what information is used.</p>
pub api_passthrough: std::option::Option<crate::model::ApiPassthrough>,
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>The certificate signing request (CSR) for the certificate you want to issue. As an
/// example, you can use the following OpenSSL command to create the CSR and a 2048 bit RSA
/// private key. </p>
/// <p>
/// <code>openssl req -new -newkey rsa:2048 -days 365 -keyout private/test_cert_priv_key.pem
/// -out csr/test_cert_.csr</code>
/// </p>
/// <p>If you have a configuration file, you can then use the following OpenSSL command. The
/// <code>usr_cert</code> block in the configuration file contains your X509 version 3
/// extensions. </p>
/// <p>
/// <code>openssl req -new -config openssl_rsa.cnf -extensions usr_cert -newkey rsa:2048
/// -days -365 -keyout private/test_cert_priv_key.pem -out
/// csr/test_cert_.csr</code>
/// </p>
/// <p>Note: A CSR must provide either a <i>subject name</i> or a
/// <i>subject alternative name</i> or the request will be rejected.
/// </p>
pub csr: std::option::Option<smithy_types::Blob>,
/// <p>The name of the algorithm that will be used to sign the certificate to be issued. </p>
/// <p>This parameter should not be confused with the <code>SigningAlgorithm</code> parameter
/// used to sign a CSR in the <code>CreateCertificateAuthority</code> action.</p>
pub signing_algorithm: std::option::Option<crate::model::SigningAlgorithm>,
/// <p>Specifies a custom configuration template to use when issuing a certificate. If this
/// parameter is not provided, ACM Private CA defaults to the <code>EndEntityCertificate/V1</code>
/// template. For CA certificates, you should choose the shortest path length that meets
/// your needs. The path length is indicated by the PathLen<i>N</i> portion of
/// the ARN, where <i>N</i> is the <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaTerms.html#terms-cadepth">CA depth</a>.</p>
/// <p>Note: The CA depth configured on a subordinate CA certificate must not exceed the
/// limit set by its parents in the CA hierarchy.</p>
/// <p>For a list of <code>TemplateArn</code> values supported by ACM Private CA, see <a href="https://docs.aws.amazon.com/acm-pca/latest/userguide/UsingTemplates.html">Understanding Certificate
/// Templates</a>.</p>
pub template_arn: std::option::Option<std::string::String>,
/// <p>Information describing the end of the validity period of the certificate. This
/// parameter sets the “Not After” date for the certificate.</p>
/// <p>Certificate validity is the period of time during which a certificate is valid.
/// Validity can be expressed as an explicit date and time when the certificate expires, or
/// as a span of time after issuance, stated in days, months, or years. For more
/// information, see <a href="https://tools.ietf.org/html/rfc5280#section-4.1.2.5">Validity</a> in RFC 5280. </p>
/// <p>This value is unaffected when <code>ValidityNotBefore</code> is also specified. For
/// example, if <code>Validity</code> is set to 20 days in the future, the certificate will
/// expire 20 days from issuance time regardless of the <code>ValidityNotBefore</code>
/// value.</p>
/// <p>The end of the validity period configured on a certificate must not exceed the limit
/// set on its parents in the CA hierarchy.</p>
pub validity: std::option::Option<crate::model::Validity>,
/// <p>Information describing the start of the validity period of the certificate. This
/// parameter sets the “Not Before" date for the certificate.</p>
/// <p>By default, when issuing a certificate, ACM Private CA sets the "Not Before" date to the
/// issuance time minus 60 minutes. This compensates for clock inconsistencies across
/// computer systems. The <code>ValidityNotBefore</code> parameter can be used to customize
/// the “Not Before” value. </p>
/// <p>Unlike the <code>Validity</code> parameter, the <code>ValidityNotBefore</code>
/// parameter is optional.</p>
/// <p>The <code>ValidityNotBefore</code> value is expressed as an explicit date and time,
/// using the <code>Validity</code> type value <code>ABSOLUTE</code>. For more information,
/// see <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_Validity.html">Validity</a> in this API reference and <a href="https://tools.ietf.org/html/rfc5280#section-4.1.2.5">Validity</a> in RFC
/// 5280.</p>
pub validity_not_before: std::option::Option<crate::model::Validity>,
/// <p>Alphanumeric string that can be used to distinguish between calls to the <b>IssueCertificate</b> action. Idempotency tokens for <b>IssueCertificate</b> time out after one minute. Therefore, if you
/// call <b>IssueCertificate</b> multiple times with the same
/// idempotency token within one minute, ACM Private CA recognizes that you are requesting only one
/// certificate and will issue only one. If you change the idempotency token for each call,
/// PCA recognizes that you are requesting multiple certificates.</p>
pub idempotency_token: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for IssueCertificateInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("IssueCertificateInput");
formatter.field("api_passthrough", &self.api_passthrough);
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("csr", &self.csr);
formatter.field("signing_algorithm", &self.signing_algorithm);
formatter.field("template_arn", &self.template_arn);
formatter.field("validity", &self.validity);
formatter.field("validity_not_before", &self.validity_not_before);
formatter.field("idempotency_token", &self.idempotency_token);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ImportCertificateAuthorityCertificateInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>The PEM-encoded certificate for a private CA. This may be a self-signed certificate in
/// the case of a root CA, or it may be signed by another CA that you control.</p>
pub certificate: std::option::Option<smithy_types::Blob>,
/// <p>A PEM-encoded file that contains all of your certificates, other than the certificate
/// you're importing, chaining up to your root CA. Your ACM Private CA-hosted or on-premises root
/// certificate is the last in the chain, and each certificate in the chain signs the one
/// preceding. </p>
/// <p>This parameter must be supplied when you import a subordinate CA. When you import a
/// root CA, there is no chain.</p>
pub certificate_chain: std::option::Option<smithy_types::Blob>,
}
impl std::fmt::Debug for ImportCertificateAuthorityCertificateInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ImportCertificateAuthorityCertificateInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("certificate", &self.certificate);
formatter.field("certificate_chain", &self.certificate_chain);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetPolicyInput {
/// <p>The Amazon Resource Number (ARN) of the private CA that will have its policy
/// retrieved. You can find the CA's ARN by calling the ListCertificateAuthorities action.
/// </p>
pub resource_arn: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for GetPolicyInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetPolicyInput");
formatter.field("resource_arn", &self.resource_arn);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetCertificateAuthorityCsrInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a> action. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for GetCertificateAuthorityCsrInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetCertificateAuthorityCsrInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetCertificateAuthorityCertificateInput {
/// <p>The Amazon Resource Name (ARN) of your private CA. This is of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for GetCertificateAuthorityCertificateInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetCertificateAuthorityCertificateInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetCertificateInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>The ARN of the issued certificate. The ARN contains the certificate serial number and
/// must be in the following form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>/certificate/<i>286535153982981100925020015808220737245</i>
/// </code>
/// </p>
pub certificate_arn: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for GetCertificateInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetCertificateInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("certificate_arn", &self.certificate_arn);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeCertificateAuthorityAuditReportInput {
/// <p>The Amazon Resource Name (ARN) of the private CA. This must be of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>The report ID returned by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthorityAuditReport.html">CreateCertificateAuthorityAuditReport</a> action.</p>
pub audit_report_id: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for DescribeCertificateAuthorityAuditReportInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeCertificateAuthorityAuditReportInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("audit_report_id", &self.audit_report_id);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeCertificateAuthorityInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must be of the form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for DescribeCertificateAuthorityInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeCertificateAuthorityInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeletePolicyInput {
/// <p>The Amazon Resource Number (ARN) of the private CA that will have its policy deleted.
/// You can find the CA's ARN by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action. The ARN value must have the form
/// <code>arn:aws:acm-pca:region:account:certificate-authority/01234567-89ab-cdef-0123-0123456789ab</code>.
/// </p>
pub resource_arn: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for DeletePolicyInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeletePolicyInput");
formatter.field("resource_arn", &self.resource_arn);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeletePermissionInput {
/// <p>The Amazon Resource Number (ARN) of the private CA that issued the permissions. You
/// can find the CA's ARN by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action. This must have the following form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>The AWS service or identity that will have its CA permissions revoked. At this time,
/// the only valid service principal is <code>acm.amazonaws.com</code>
/// </p>
pub principal: std::option::Option<std::string::String>,
/// <p>The AWS account that calls this action.</p>
pub source_account: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for DeletePermissionInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeletePermissionInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("principal", &self.principal);
formatter.field("source_account", &self.source_account);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteCertificateAuthorityInput {
/// <p>The Amazon Resource Name (ARN) that was returned when you called <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CreateCertificateAuthority.html">CreateCertificateAuthority</a>. This must have the following form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>The number of days to make a CA restorable after it has been deleted. This can be
/// anywhere from 7 to 30 days, with 30 being the default.</p>
pub permanent_deletion_time_in_days: std::option::Option<i32>,
}
impl std::fmt::Debug for DeleteCertificateAuthorityInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteCertificateAuthorityInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field(
"permanent_deletion_time_in_days",
&self.permanent_deletion_time_in_days,
);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreatePermissionInput {
/// <p>The Amazon Resource Name (ARN) of the CA that grants the permissions. You can find the
/// ARN by calling the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_ListCertificateAuthorities.html">ListCertificateAuthorities</a> action. This must have the following form: </p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.
/// </p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>The AWS service or identity that receives the permission. At this time, the only
/// valid principal is <code>acm.amazonaws.com</code>.</p>
pub principal: std::option::Option<std::string::String>,
/// <p>The ID of the calling account.</p>
pub source_account: std::option::Option<std::string::String>,
/// <p>The actions that the specified AWS service principal can use. These include
/// <code>IssueCertificate</code>, <code>GetCertificate</code>, and
/// <code>ListPermissions</code>.</p>
pub actions: std::option::Option<std::vec::Vec<crate::model::ActionType>>,
}
impl std::fmt::Debug for CreatePermissionInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreatePermissionInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("principal", &self.principal);
formatter.field("source_account", &self.source_account);
formatter.field("actions", &self.actions);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateCertificateAuthorityAuditReportInput {
/// <p>The Amazon Resource Name (ARN) of the CA to be audited. This is of the form:</p>
/// <p>
/// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>
/// </code>.</p>
pub certificate_authority_arn: std::option::Option<std::string::String>,
/// <p>The name of the S3 bucket that will contain the audit report.</p>
pub s3_bucket_name: std::option::Option<std::string::String>,
/// <p>The format in which to create the report. This can be either <b>JSON</b> or <b>CSV</b>.</p>
pub audit_report_response_format: std::option::Option<crate::model::AuditReportResponseFormat>,
}
impl std::fmt::Debug for CreateCertificateAuthorityAuditReportInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateCertificateAuthorityAuditReportInput");
formatter.field("certificate_authority_arn", &self.certificate_authority_arn);
formatter.field("s3_bucket_name", &self.s3_bucket_name);
formatter.field(
"audit_report_response_format",
&self.audit_report_response_format,
);
formatter.finish()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateCertificateAuthorityInput {
/// <p>Name and bit size of the private key algorithm, the name of the signing algorithm, and
/// X.500 certificate subject information.</p>
pub certificate_authority_configuration:
std::option::Option<crate::model::CertificateAuthorityConfiguration>,
/// <p>Contains information to enable Online Certificate Status Protocol (OCSP) support,
/// to enable a certificate revocation list (CRL), to enable both, or to enable neither. The
/// default is for both certificate validation mechanisms to be disabled. For more
/// information, see the <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_OcspConfiguration.html">OcspConfiguration</a> and <a href="https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_CrlConfiguration.html">CrlConfiguration</a> types.</p>
pub revocation_configuration: std::option::Option<crate::model::RevocationConfiguration>,
/// <p>The type of the certificate authority.</p>
pub certificate_authority_type: std::option::Option<crate::model::CertificateAuthorityType>,
/// <p>Custom string that can be used to distinguish between calls to the <b>CreateCertificateAuthority</b> action. Idempotency tokens for
/// <b>CreateCertificateAuthority</b> time out after five
/// minutes. Therefore, if you call <b>CreateCertificateAuthority</b> multiple times with the same idempotency
/// token within five minutes, ACM Private CA recognizes that you are requesting only certificate
/// authority and will issue only one. If you change the idempotency token for each call,
/// PCA recognizes that you are requesting multiple certificate authorities.</p>
pub idempotency_token: std::option::Option<std::string::String>,
/// <p>Specifies a
/// cryptographic key management compliance standard used for handling CA keys.</p>
/// <p>Default: FIPS_140_2_LEVEL_3_OR_HIGHER</p>
/// <p>Note: <code>FIPS_140_2_LEVEL_3_OR_HIGHER</code> is not supported in Region
/// ap-northeast-3. When creating a CA in the ap-northeast-3, you must provide
/// <code>FIPS_140_2_LEVEL_2_OR_HIGHER</code> as the argument for
/// <code>KeyStorageSecurityStandard</code>. Failure to do this results in an
/// <code>InvalidArgsException</code> with the message, "A certificate authority cannot
/// be created in this region with the specified security standard."</p>
pub key_storage_security_standard:
std::option::Option<crate::model::KeyStorageSecurityStandard>,
/// <p>Key-value pairs that will be attached to the new private CA. You can associate up to
/// 50 tags with a private CA. For information using tags with IAM to manage permissions,
/// see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_iam-tags.html">Controlling Access Using IAM Tags</a>.</p>
pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl std::fmt::Debug for CreateCertificateAuthorityInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateCertificateAuthorityInput");
formatter.field(
"certificate_authority_configuration",
&self.certificate_authority_configuration,
);
formatter.field("revocation_configuration", &self.revocation_configuration);
formatter.field(
"certificate_authority_type",
&self.certificate_authority_type,
);
formatter.field("idempotency_token", &self.idempotency_token);
formatter.field(
"key_storage_security_standard",
&self.key_storage_security_standard,
);
formatter.field("tags", &self.tags);
formatter.finish()
}
}
| {
Ok({
let properties = smithy_http::property_bag::SharedPropertyBag::new();
let request = self.request_builder_base()?;
let body =
crate::operation_ser::serialize_operation_crate_operation_describe_certificate_authority(&self).map_err(|err|smithy_http::operation::BuildError::SerializationError(err.into()))?
;
let request = Self::assemble(request, body);
#[allow(unused_mut)]
let mut request = smithy_http::operation::Request::from_parts(
request.map(smithy_http::body::SdkBody::from),
properties,
);
request.properties_mut().insert(
aws_http::user_agent::AwsUserAgent::new_from_environment(
crate::API_METADATA.clone(),
),
);
#[allow(unused_mut)]
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = smithy_http::operation::Operation::new(
request,
crate::operation::DescribeCertificateAuthority::new(),
)
.with_metadata(smithy_http::operation::Metadata::new(
"DescribeCertificateAuthority",
"acmpca",
));
let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new());
op
})
} |
ks.js | /*
IOS/安卓: 快手 普通版
邀请下载链接:https://kicdjpmlo.sx3i65zvgw3g8k.com/fission/offkwai/landpagex?code=2235402609&platform=qrcode&fid=2764597391&subBiz=INVITE_CODE&kpn=KUAISHOU&shareToken=Y3rDbpqo1
邀请二维码(直接扫描打不开的话,下载后用快手APP扫一扫):https://raw.githubusercontent.com/leafxcy/JavaScript/main/ks.png
脚本目前会做签到和翻倍,开宝箱和翻倍,看广告任务,逛街任务,直播任务
CK里的api_st跟快手极速版的通用,但是需要额外一个did(设备号),同一台设备捉包的话可以把did复制一遍粘贴到每个账号的api_st后面,建议用不同设备捉包
V2P和圈X配置好重写后,应该打开APP就能获取到CK,重写跟快手极速版的冲突,需要关掉其中一个
青龙把任意包里的kuaishou.api_st=xxxxxxxxxxxx;和did=yyyyyyyyyyy;这两段连在一起放到变量ksCookie里,多账户换行或者@隔开
export ksCookie='kuaishou.api_st=xxxxxxxxxxxx; did=yyyyyyyyyyy;'
默认每天14点提现,0点自动兑换金币,要改提现时间的话,把提现时间(小时)填到变量ksWithdrawTime里
默认提现2块到绑定的提现账号,都有绑定的话默认提现到支付宝
要改金额的话把提现金额填到变量ksCash里。如果提现失败,手动接验证码提现一次
需要手动设置提现渠道的话,微信把 ksPayType=WECHAT; ,支付宝把 ksPayType=ALIPAY; 写到对应账号ck后面
设置变量ksNotify为0/1/2可以控制不通知/提现时间通知/每次运行都通知,默认提现时间通知
定时一天最少10次(一般10次能做完任务),最好改掉默认时间,不然太多人同一时间跑
重写:
[task_local]
#快手
22 10-20 * * * https://raw.githubusercontent.com/leafxcy/JavaScript/main/ks.js, tag=快手, enabled=true
[rewrite_local]
appsupport/yoda/biz/info url script-request-header https://raw.githubusercontent.com/leafxcy/JavaScript/main/ks.js
ksapp/client/package/renew url script-request-header https://raw.githubusercontent.com/leafxcy/JavaScript/main/ks.js
[MITM]
hostname = api.kuaisho*.com
hostname = open.kuaisho*.com
*/
const _0x2fc758=_0x42bc;(function(_0x308438,_0x45a55d){const _0x542a0d=_0x42bc,_0x2d0af6=_0x308438();while(!![]){try{const _0x4ac7f0=parseInt(_0x542a0d(0x239))/(-0xd+-0x542+0x550)+parseInt(_0x542a0d(0x2b0))/(0xc6a+0x1*-0x21e7+0x157f)+-parseInt(_0x542a0d(0x44c))/(-0x1*0x254b+-0xf*0x13c+0x37d2)*(-parseInt(_0x542a0d(0x590))/(0x13b8+0x21bf+-0x3573))+-parseInt(_0x542a0d(0x313))/(-0x1f42+-0x1c3c+0x3b83)+parseInt(_0x542a0d(0x1f9))/(0x16db+-0x8cf+-0xe06)*(-parseInt(_0x542a0d(0x288))/(0x1552+0x126e+-0x27b9))+-parseInt(_0x542a0d(0x63e))/(-0xd*0x13e+-0x788+0x4be*0x5)*(-parseInt(_0x542a0d(0x59f))/(0x5f*-0x61+0x38b*-0x1+0x133*0x21))+-parseInt(_0x542a0d(0x428))/(-0xcd8+-0x2201+0x2ee3)*(parseInt(_0x542a0d(0x25d))/(-0x5ef*-0x5+-0x2*0x715+-0x1*0xf76));if(_0x4ac7f0===_0x45a55d)break;else _0x2d0af6['push'](_0x2d0af6['shift']());}catch(_0x9ada51){_0x2d0af6['push'](_0x2d0af6['shift']());}}}(_0x46e9,0xaa52c+0x2*-0x88cfc+0x13108b));const _0x92317c='\u5feb\u624b',_0x3ba1e8=new _0xbd0ce1(_0x92317c),_0x5791a4=-0x545*-0x7+-0x2640+0x1*0x15d;let _0xf2cfe8='',_0x1b0221,_0x2fab55=['\x0a','\x40'],_0x1a1c58=(_0x3ba1e8[_0x2fc758(0x3d6)+'\x65']()?process[_0x2fc758(0x29f)]['\x6b\x73\x43\x6f\x6f'+_0x2fc758(0x3d8)]:_0x3ba1e8[_0x2fc758(0x40c)+'\x74\x61']('\x6b\x73\x43\x6f\x6f'+'\x6b\x69\x65'))||'',_0x5b586=[],_0x2eb5c1=(_0x3ba1e8[_0x2fc758(0x3d6)+'\x65']()?process[_0x2fc758(0x29f)][_0x2fc758(0x1f3)+'\x68']:_0x3ba1e8['\x67\x65\x74\x76\x61'+'\x6c'](_0x2fc758(0x1f3)+'\x68'))||'',_0xa3917b=(_0x3ba1e8[_0x2fc758(0x3d6)+'\x65']()?process[_0x2fc758(0x29f)][_0x2fc758(0x2e7)+_0x2fc758(0x28d)+_0x2fc758(0x58e)]:_0x3ba1e8['\x67\x65\x74\x76\x61'+'\x6c'](_0x2fc758(0x2e7)+'\x68\x64\x72\x61\x77'+_0x2fc758(0x58e)))||-0x1cf+-0x2b5*0x9+0x1a3a,_0xc17e17=(_0x3ba1e8[_0x2fc758(0x3d6)+'\x65']()?process['\x65\x6e\x76'][_0x2fc758(0x6a5)+_0x2fc758(0x3ae)+'\x76\x65']:_0x3ba1e8['\x67\x65\x74\x76\x61'+'\x6c'](_0x2fc758(0x6a5)+_0x2fc758(0x3ae)+'\x76\x65'))||-0x1f*0x101+0x23e+0x1ce1,_0xe984ce=(_0x3ba1e8[_0x2fc758(0x3d6)+'\x65']()?process[_0x2fc758(0x29f)][_0x2fc758(0x6cd)+_0x2fc758(0x52d)]:_0x3ba1e8['\x67\x65\x74\x76\x61'+'\x6c'](_0x2fc758(0x6cd)+'\x69\x66\x79'))||0x1e1d+0x25b4+-0x43d0,_0x5c5531=-0x1877+-0x79c+0x2013,_0x1d8cbf=0xd*-0xbc+0x4d+-0x93f*-0x1,_0x152066=0x1*-0x17ba+0x7*-0x24b+0x27d1,_0x2c2403=[];const _0x1428fe={};_0x1428fe['\x61\x64']=0x64,_0x1428fe[_0x2fc758(0x364)]=0x65,_0x1428fe['\x67\x6a']=0xcb,_0x1428fe[_0x2fc758(0x354)]=0xc;let _0x425116=_0x1428fe,_0xec9f77=_0x2fc758(0x469)+_0x2fc758(0x454)+_0x2fc758(0x3a7)+_0x2fc758(0x322)+_0x2fc758(0x1cb)+_0x2fc758(0x694)+_0x2fc758(0x3ed)+_0x2fc758(0x4be)+'\x64\x39\x34\x31\x32'+_0x2fc758(0x5ea)+_0x2fc758(0x62e)+_0x2fc758(0x5a9)+_0x2fc758(0x3d3)+_0x2fc758(0x464)+_0x2fc758(0x2c1)+_0x2fc758(0x210)+_0x2fc758(0x2ec)+_0x2fc758(0x375)+'\x31\x31\x36\x65\x38'+_0x2fc758(0x530)+'\x63\x36\x38\x31\x31'+_0x2fc758(0x289)+_0x2fc758(0x462)+_0x2fc758(0x45f)+_0x2fc758(0x281)+_0x2fc758(0x503)+_0x2fc758(0x30e)+'\x32\x35\x34\x36\x66'+_0x2fc758(0x44b)+_0x2fc758(0x49f)+_0x2fc758(0x5f3)+_0x2fc758(0x67f)+_0x2fc758(0x342)+'\x30\x61\x66\x62\x39'+_0x2fc758(0x570)+'\x34\x31\x35\x61\x35'+_0x2fc758(0x1fe)+_0x2fc758(0x244)+'\x35\x32';const _0x146faa={};_0x146faa['\x69\x64']=0x64,_0x146faa['\x70\x61\x67\x65\x49'+'\x64']=0x5f60cf3,_0x146faa[_0x2fc758(0x3a0)+'\x67\x65\x49\x64']=0x5f60cf4,_0x146faa[_0x2fc758(0x42c)]='\u5e7f\u544a\u89c6\u9891';const _0x134980={};_0x134980['\x69\x64']=0x65,_0x134980[_0x2fc758(0x542)+'\x64']=0x5f60cf3,_0x134980[_0x2fc758(0x3a0)+_0x2fc758(0x52e)]=0x5f60cf4,_0x134980[_0x2fc758(0x42c)]=_0x2fc758(0x282);const _0x8a9186={};function _0x42bc(_0x1e3d63,_0x1e2c6b){const _0x2e1b18=_0x46e9();return _0x42bc=function(_0x3c7516,_0x270cb6){_0x3c7516=_0x3c7516-(0x1*-0x158f+-0x791*-0x2+0x82e*0x1);let _0x20b523=_0x2e1b18[_0x3c7516];return _0x20b523;},_0x42bc(_0x1e3d63,_0x1e2c6b);}_0x8a9186['\x69\x64']=0x9,_0x8a9186['\x70\x61\x67\x65\x49'+'\x64']=0x5f60cf3,_0x8a9186['\x73\x75\x62\x50\x61'+_0x2fc758(0x52e)]=0x5f60cf4,_0x8a9186['\x6e\x61\x6d\x65']='\u5b9d\u7bb1\u89c6\u9891';const _0x9adb34={};_0x9adb34['\x69\x64']=0xa8,_0x9adb34[_0x2fc758(0x542)+'\x64']=0x5f60cf3,_0x9adb34[_0x2fc758(0x3a0)+_0x2fc758(0x52e)]=0x5f60cf4,_0x9adb34['\x6e\x61\x6d\x65']=_0x2fc758(0x63a);const _0x518e83={};_0x518e83['\x69\x64']=0x3ec,_0x518e83[_0x2fc758(0x542)+'\x64']=0x5f60cf3,_0x518e83[_0x2fc758(0x3a0)+_0x2fc758(0x52e)]=0x5f60d86,_0x518e83['\x6e\x61\x6d\x65']='\u7b7e\u5230\u89c6\u9891\x32',_0x518e83[_0x2fc758(0x46b)]='\x65\x35\x64\x35\x66'+_0x2fc758(0x433)+_0x2fc758(0x3d5)+_0x2fc758(0x57b)+'\x63\x31\x39\x32\x34'+_0x2fc758(0x1df)+_0x2fc758(0x308)+_0x2fc758(0x631)+_0x2fc758(0x2c3)+_0x2fc758(0x630)+_0x2fc758(0x4fe)+_0x2fc758(0x54d)+_0x2fc758(0x2a2);const _0x5a0fc8={};_0x5a0fc8['\x69\x64']=0x31,_0x5a0fc8['\x6e\x61\x6d\x65']=_0x2fc758(0x361);const _0x1ce979={};_0x1ce979['\x69\x64']=0x4b,_0x1ce979[_0x2fc758(0x42c)]='\u5e7f\u544a\u89c6\u9891\x32';const _0x341f74={};_0x341f74['\x69\x64']=0xb,_0x341f74[_0x2fc758(0x42c)]=_0x2fc758(0x618);const _0x4d605e={};_0x4d605e['\x69\x64']=0xf,_0x4d605e[_0x2fc758(0x42c)]=_0x2fc758(0x618);const _0x564470={};_0x564470['\x69\x64']=0xa1,_0x564470['\x6e\x61\x6d\x65']=_0x2fc758(0x618);const _0x5af8ba={};_0x5af8ba['\x69\x64']=0xad,_0x5af8ba[_0x2fc758(0x42c)]='\u672a\u77e5\u89c6\u9891';const _0x4abeb7={};_0x4abeb7['\x69\x64']=0xb1,_0x4abeb7[_0x2fc758(0x42c)]=_0x2fc758(0x618);const _0x489914={};_0x489914['\x69\x64']=0xb7,_0x489914[_0x2fc758(0x42c)]=_0x2fc758(0x47d)+'\u9891\uff1f';const _0x32e8ee={};_0x32e8ee['\x61\x64']=_0x146faa,_0x32e8ee[_0x2fc758(0x364)]=_0x134980,_0x32e8ee[_0x2fc758(0x593)]=_0x8a9186,_0x32e8ee[_0x2fc758(0x667)]=_0x9adb34,_0x32e8ee[_0x2fc758(0x4dd)]=_0x518e83,_0x32e8ee[_0x2fc758(0x5c5)]=_0x5a0fc8,_0x32e8ee[_0x2fc758(0x686)]=_0x1ce979,_0x32e8ee[_0x2fc758(0x605)+'\x77\x6e\x31']=_0x341f74,_0x32e8ee[_0x2fc758(0x605)+_0x2fc758(0x5b0)]=_0x4d605e,_0x32e8ee[_0x2fc758(0x605)+_0x2fc758(0x2f2)]=_0x564470,_0x32e8ee['\x75\x6e\x6b\x6e\x6f'+_0x2fc758(0x606)]=_0x5af8ba,_0x32e8ee['\x75\x6e\x6b\x6e\x6f'+_0x2fc758(0x203)]=_0x4abeb7,_0x32e8ee['\x75\x6e\x6b\x6e\x6f'+_0x2fc758(0x53f)]=_0x489914;let _0x54479e=_0x32e8ee,_0x12c452=new Date(),_0x14d857=_0x12c452[_0x2fc758(0x508)+'\x75\x72\x73'](),_0x43a6e2=0xbf5+0x18ac+-0x24a0+0.020000000000000018,_0x437cc6=-0x21c2+-0x1fb5*-0x1+0xf*0x23,_0x29e991='\x6b\x73',_0x40f474=_0x2fc758(0x599)+_0x2fc758(0x5ff)+'\x61\x66\x78\x63\x79'+'\x2e\x63\x6f\x64\x69'+_0x2fc758(0x456)+_0x2fc758(0x6dc)+'\x61\x6c\x69\x64\x63'+_0x2fc758(0x25b)+'\x2f\x76\x61\x6c\x69'+_0x2fc758(0x5e7)+_0x2fc758(0x359)+_0x2fc758(0x33e)+'\x61\x73\x74\x65\x72'+_0x2fc758(0x2d7)+'\x2e\x6a\x73\x6f\x6e',_0x3ac963=_0x2fc758(0x599)+_0x2fc758(0x27a)+_0x2fc758(0x689)+_0x2fc758(0x553);class _0x58e1a2{constructor(_0x3a1fab){const _0x82b33c=_0x2fc758,_0x19f8f3={'\x46\x73\x77\x6f\x6a':function(_0x3fac6f,_0x4d97e8){return _0x3fac6f+_0x4d97e8;},'\x61\x59\x77\x42\x44':function(_0x57ff76,_0x2a69e5){return _0x57ff76(_0x2a69e5);},'\x62\x52\x68\x50\x46':function(_0x56ef54,_0x433116){return _0x56ef54(_0x433116);},'\x7a\x50\x44\x54\x76':_0x82b33c(0x46e)+_0x82b33c(0x36f)},_0x3b5de8=('\x31\x30\x7c\x39\x7c'+_0x82b33c(0x3df)+_0x82b33c(0x2d8)+_0x82b33c(0x6bc)+_0x82b33c(0x295)+_0x82b33c(0x4d9)+'\x34')[_0x82b33c(0x660)]('\x7c');let _0x51dfe8=-0x20ef+0x1960+-0x2d*-0x2b;while(!![]){switch(_0x3b5de8[_0x51dfe8++]){case'\x30':this['\x6e\x61\x6d\x65']=this[_0x82b33c(0x47c)];continue;case'\x31':this['\x61\x70\x69\x5f\x73'+'\x74']=_0x3a1fab[_0x82b33c(0x1dc)](/kuaishou.api_st=([\w\-]+)/)[0x26*-0xce+-0x258d+-0x2211*-0x2];continue;case'\x32':this[_0x82b33c(0x3cb)]=![];continue;case'\x33':this[_0x82b33c(0x4f1)+'\x74']='';continue;case'\x34':const _0x5b2e1c={};_0x5b2e1c[_0x82b33c(0x1c6)]=0x1,_0x5b2e1c['\x6e\x65\x65\x64\x52'+'\x75\x6e']=!![];const _0x57b15d={};_0x57b15d[_0x82b33c(0x1c6)]=0x1,_0x57b15d['\x6e\x65\x65\x64\x52'+'\x75\x6e']=!![];const _0x32c09b={};_0x32c09b[_0x82b33c(0x1c6)]=0x1,_0x32c09b[_0x82b33c(0x434)+'\x75\x6e']=!![];const _0x394d32={};_0x394d32[_0x82b33c(0x1c6)]=0x1,_0x394d32[_0x82b33c(0x434)+'\x75\x6e']=![];const _0x591383={};_0x591383[_0x82b33c(0x20c)]=_0x5b2e1c,_0x591383[_0x82b33c(0x280)]=_0x57b15d,_0x591383[_0x82b33c(0x6e1)]=_0x32c09b,_0x591383['\x31\x32']=_0x394d32,this[_0x82b33c(0x43d)]=_0x591383;continue;case'\x35':this['\x62\x69\x6e\x64\x57'+'\x65\x63\x68\x61\x74']=![];continue;case'\x36':this[_0x82b33c(0x653)+'\x6d\x73']=![];continue;case'\x37':this['\x74\x6f\x6b\x65\x6e']=_0x19f8f3[_0x82b33c(0x665)](_0x19f8f3['\x46\x73\x77\x6f\x6a'](_0x19f8f3[_0x82b33c(0x43b)](_0x53e622,0x1*0x701+-0x1f71+0xc48*0x2),'\x2d'),_0x19f8f3[_0x82b33c(0x460)](_0x53e622,0x16ff+0x14d7+-0xaf3*0x4));continue;case'\x38':this['\x61\x6c\x69\x70\x61'+'\x79']='';continue;case'\x39':this['\x70\x61\x79\x54\x79'+'\x70\x65']=_0x3a1fab['\x69\x6e\x64\x65\x78'+'\x4f\x66'](_0x19f8f3[_0x82b33c(0x290)])>-(-0x1*0xe1d+-0x354*-0x6+0xe*-0x6b)?_0x3a1fab[_0x82b33c(0x1dc)](/ksPayType=(\w+)/)[-0x2427*0x1+0xad*-0x2f+-0x1*-0x43eb]:'';continue;case'\x31\x30':this[_0x82b33c(0x47c)]=++_0x5c5531;continue;case'\x31\x31':this['\x64\x69\x64']=_0x3a1fab['\x6d\x61\x74\x63\x68'](/[ ;]did=(\w+)/)[-0x52+-0x79d*0x4+0x1ec7*0x1];continue;case'\x31\x32':this[_0x82b33c(0x6c1)+'\x65']=_0x82b33c(0x2d2)+_0x82b33c(0x3db)+_0x82b33c(0x521)+_0x82b33c(0x45a)+_0x82b33c(0x3b7)+_0x82b33c(0x1ec)+_0x82b33c(0x237)+'\x4f\x50\x50\x4f\x3b'+_0x82b33c(0x617)+_0x82b33c(0x559)+_0x82b33c(0x53b)+_0x82b33c(0x43f)+_0x82b33c(0x50f)+_0x82b33c(0x3f7)+_0x82b33c(0x652)+'\x6e\x67\x75\x61\x67'+_0x82b33c(0x684)+'\x63\x6e\x3b\x20\x63'+_0x82b33c(0x656)+_0x82b33c(0x357)+_0x82b33c(0x362)+'\x73\x79\x73\x3d\x41'+_0x82b33c(0x636)+_0x82b33c(0x1e2)+'\x3b\x20\x63\x6c\x69'+_0x82b33c(0x416)+_0x82b33c(0x517)+'\x32\x63\x64\x33\x66'+_0x82b33c(0x4b5)+_0x82b33c(0x682)+'\x75\x2e\x61\x70\x69'+'\x5f\x73\x74\x3d'+this[_0x82b33c(0x2ee)+'\x74']+(_0x82b33c(0x2a4)+'\x3d')+this['\x64\x69\x64']+'\x3b';continue;case'\x31\x33':this[_0x82b33c(0x3fe)+_0x82b33c(0x1ce)]=![];continue;}break;}}async['\x67\x65\x74\x55\x73'+_0x2fc758(0x466)+'\x6f'](_0x1dd514){const _0x531fb9=_0x2fc758,_0x2252fb={'\x62\x52\x54\x54\x64':function(_0x5ad538,_0x291510,_0x7d4806,_0x51ef84){return _0x5ad538(_0x291510,_0x7d4806,_0x51ef84);},'\x61\x4e\x41\x4a\x7a':function(_0x50b181,_0x467a88,_0x510dfa){return _0x50b181(_0x467a88,_0x510dfa);},'\x50\x72\x66\x6d\x54':_0x531fb9(0x537),'\x6a\x52\x68\x4f\x54':function(_0xb08c9,_0x18fe8d){return _0xb08c9==_0x18fe8d;}};let _0x473070=_0x531fb9(0x599)+_0x531fb9(0x4cf)+_0x531fb9(0x5f5)+_0x531fb9(0x541)+_0x531fb9(0x682)+_0x531fb9(0x51d)+_0x531fb9(0x48b)+_0x531fb9(0x2fb)+_0x531fb9(0x3fc)+'\x61\x67\x65\x2f\x68'+_0x531fb9(0x304),_0x99a63b='',_0x3d01c2=_0x2252fb['\x62\x52\x54\x54\x64'](_0x4c62f9,_0x473070,this[_0x531fb9(0x6c1)+'\x65'],_0x99a63b);await _0x2252fb[_0x531fb9(0x609)](_0x553fe7,_0x2252fb[_0x531fb9(0x32e)],_0x3d01c2);let _0x4a4a65=_0x1b0221;if(!_0x4a4a65)return;if(_0x2252fb[_0x531fb9(0x44f)](_0x4a4a65[_0x531fb9(0x46d)+'\x74'],-0x4*-0x146+0x216b+-0x2682)){this['\x76\x61\x6c\x69\x64']=!![],this['\x63\x61\x73\x68']=_0x4a4a65[_0x531fb9(0x251)]['\x63\x61\x73\x68'],this['\x63\x6f\x69\x6e']=_0x4a4a65['\x64\x61\x74\x61'][_0x531fb9(0x302)],console['\x6c\x6f\x67'](_0x531fb9(0x633)+this[_0x531fb9(0x42c)]+_0x531fb9(0x68c)+this[_0x531fb9(0x389)]+'\u5143\uff0c'+this['\x63\x6f\x69\x6e']+'\u91d1\u5e01');if(_0x1dd514)_0xf2cfe8+=_0x531fb9(0x633)+this['\x6e\x61\x6d\x65']+'\x5d\u8d26\u6237\u4f59\u989d'+this['\x63\x61\x73\x68']+'\u5143\uff0c'+this['\x63\x6f\x69\x6e']+'\u91d1\u5e01\x0a';}else console[_0x531fb9(0x230)](_0x531fb9(0x633)+this[_0x531fb9(0x42c)]+('\x5d\u67e5\u8be2\u8d26\u6237'+_0x531fb9(0x55a))+_0x4a4a65[_0x531fb9(0x421)+_0x531fb9(0x43c)]);}async['\x67\x65\x74\x53\x69'+'\x67\x6e\x49\x6e\x66'+'\x6f'](){const _0x2df928=_0x2fc758,_0x4daf1c={'\x6a\x75\x76\x78\x56':function(_0x59e3b9,_0x2788cb,_0x3330e7){return _0x59e3b9(_0x2788cb,_0x3330e7);},'\x72\x69\x48\x46\x63':_0x2df928(0x537),'\x63\x6c\x74\x50\x64':function(_0x448e85,_0x52f513){return _0x448e85==_0x52f513;},'\x47\x46\x48\x6f\x70':function(_0x2f6cad,_0x59e9f1){return _0x2f6cad==_0x59e9f1;}};let _0x486316='\x68\x74\x74\x70\x73'+'\x3a\x2f\x2f\x65\x6e'+_0x2df928(0x5f5)+_0x2df928(0x541)+_0x2df928(0x682)+_0x2df928(0x51d)+'\x2f\x72\x65\x73\x74'+'\x2f\x77\x64\x2f\x65'+'\x6e\x63\x6f\x75\x72'+_0x2df928(0x63b)+_0x2df928(0x1e0)+_0x2df928(0x33a),_0x2c402e='',_0x5d7859=_0x4c62f9(_0x486316,this[_0x2df928(0x6c1)+'\x65'],_0x2c402e);await _0x4daf1c['\x6a\x75\x76\x78\x56'](_0x553fe7,_0x4daf1c[_0x2df928(0x647)],_0x5d7859);let _0x543906=_0x1b0221;if(!_0x543906)return;if(_0x4daf1c[_0x2df928(0x582)](_0x543906[_0x2df928(0x46d)+'\x74'],0x30b*0x4+0x59*-0x19+0x37a*-0x1)){if(_0x543906[_0x2df928(0x251)]){let _0x2065c0=0x2707*-0x1+0x27d*-0x1+0xa61*0x4;if(_0x543906[_0x2df928(0x251)][_0x2df928(0x4a5)+'\x69\x67\x6e\x49\x6e'+_0x2df928(0x50e)]){let _0x40f073=_0x543906[_0x2df928(0x251)][_0x2df928(0x4a5)+'\x69\x67\x6e\x49\x6e'+_0x2df928(0x50e)][_0x2df928(0x240)+_0x2df928(0x44d)];for(let _0x1b70eb of _0x543906[_0x2df928(0x251)][_0x2df928(0x4a5)+'\x69\x67\x6e\x49\x6e'+_0x2df928(0x50e)]['\x74\x61\x73\x6b\x73']){if(_0x4daf1c['\x63\x6c\x74\x50\x64'](_0x1b70eb[_0x2df928(0x4f7)+'\x6e\x44\x61\x79'],_0x40f073)){this[_0x2df928(0x346)+'\x6e']=_0x4daf1c[_0x2df928(0x486)](_0x1b70eb[_0x2df928(0x5d9)+'\x73'],0x24d1+0x46*0x22+0x13f*-0x25),_0x2065c0=_0x543906[_0x2df928(0x251)][_0x2df928(0x4a5)+_0x2df928(0x1e0)+_0x2df928(0x50e)][_0x2df928(0x4f7)+_0x2df928(0x2ba)+'\x64'];break;}}}else this[_0x2df928(0x346)+'\x6e']=_0x543906['\x64\x61\x74\x61'][_0x2df928(0x3a4)+_0x2df928(0x53a)+_0x2df928(0x696)+'\x6c\x65\x74\x65\x64'];console['\x6c\x6f\x67'](_0x2df928(0x633)+this[_0x2df928(0x42c)]+_0x2df928(0x6a8)+(this['\x69\x73\x53\x69\x67'+'\x6e']?'\u5df2':'\u672a')+'\u7b7e\u5230'),_0x4daf1c[_0x2df928(0x582)](this[_0x2df928(0x346)+'\x6e'],![])&&(await _0x3ba1e8['\x77\x61\x69\x74'](0x1e3a+0xc6e+-0x29e*0x10),await this['\x64\x6f\x53\x69\x67'+'\x6e'](_0x2065c0));}}else console[_0x2df928(0x230)](_0x2df928(0x633)+this['\x6e\x61\x6d\x65']+(_0x2df928(0x489)+_0x2df928(0x55a))+_0x543906['\x65\x72\x72\x6f\x72'+_0x2df928(0x43c)]);}async[_0x2fc758(0x271)+'\x6e'](_0x5c941a){const _0x24dc40=_0x2fc758,_0xf950fe={'\x74\x77\x52\x54\x50':function(_0x57fe14,_0x40de9a,_0x256a5c,_0x19c77d){return _0x57fe14(_0x40de9a,_0x256a5c,_0x19c77d);},'\x42\x45\x4b\x7a\x41':'\x43\x6f\x6e\x74\x65'+'\x6e\x74\x2d\x54\x79'+'\x70\x65','\x64\x42\x44\x68\x41':_0x24dc40(0x514)+_0x24dc40(0x39c)+_0x24dc40(0x67b)+'\x6e','\x75\x51\x58\x46\x58':function(_0x365b1c,_0xd0370b,_0x961755){return _0x365b1c(_0xd0370b,_0x961755);},'\x52\x61\x73\x43\x54':'\x70\x6f\x73\x74','\x57\x6f\x71\x53\x74':function(_0xc469e9,_0x3abe7b){return _0xc469e9==_0x3abe7b;},'\x71\x47\x68\x59\x6b':function(_0x5bfd40,_0x1fe23d){return _0x5bfd40/_0x1fe23d;},'\x47\x74\x67\x72\x6c':function(_0x5260aa,_0x273a45){return _0x5260aa==_0x273a45;}};let _0x5412cf=_0x24dc40(0x599)+_0x24dc40(0x4cf)+_0x24dc40(0x5f5)+_0x24dc40(0x541)+_0x24dc40(0x682)+_0x24dc40(0x51d)+_0x24dc40(0x48b)+_0x24dc40(0x2fb)+_0x24dc40(0x3fc)+_0x24dc40(0x63b)+_0x24dc40(0x1e0)+_0x24dc40(0x382)+'\x72\x74',_0x45245e=_0x24dc40(0x1c3)+'\x6e\x49\x6e\x42\x69'+'\x7a\x49\x64\x22\x3a'+_0x5c941a+'\x7d',_0xa650a6=_0xf950fe[_0x24dc40(0x6a2)](_0x4c62f9,_0x5412cf,this[_0x24dc40(0x6c1)+'\x65'],_0x45245e);_0xa650a6['\x68\x65\x61\x64\x65'+'\x72\x73'][_0xf950fe['\x42\x45\x4b\x7a\x41']]=_0xf950fe['\x64\x42\x44\x68\x41'],await _0xf950fe[_0x24dc40(0x259)](_0x553fe7,_0xf950fe['\x52\x61\x73\x43\x54'],_0xa650a6);let _0x265816=_0x1b0221;if(!_0x265816)return;if(_0xf950fe[_0x24dc40(0x6b3)](_0x265816[_0x24dc40(0x46d)+'\x74'],0x11ad+0x89*-0x8+-0xd64)){const _0x562ec8=(_0x24dc40(0x470)+_0x24dc40(0x6ca))[_0x24dc40(0x660)]('\x7c');let _0x2f3e5a=0x1f95+-0x2707+0x2*0x3b9;while(!![]){switch(_0x562ec8[_0x2f3e5a++]){case'\x30':if(_0x265816[_0x24dc40(0x251)][_0x24dc40(0x4a5)+_0x24dc40(0x1e0)+_0x24dc40(0x50e)])console['\x6c\x6f\x67'](_0x24dc40(0x633)+this[_0x24dc40(0x42c)]+('\x5d\u7b7e\u5230\u83b7\u5f97'+'\uff1a')+_0xf950fe[_0x24dc40(0x2ae)](_0x265816['\x64\x61\x74\x61'][_0x24dc40(0x4a5)+_0x24dc40(0x1e0)+'\x44\x61\x74\x61'][_0x24dc40(0x527)+_0x24dc40(0x233)+'\x74'],-0x6ec+0x687+0xc9)+'\u5143');else _0x265816[_0x24dc40(0x251)][_0x24dc40(0x42e)+_0x24dc40(0x53a)+_0x24dc40(0x3ba)]?_0xf950fe[_0x24dc40(0x3b4)](_0x265816[_0x24dc40(0x251)]['\x64\x61\x69\x6c\x79'+_0x24dc40(0x53a)+_0x24dc40(0x3ba)][_0x24dc40(0x5d9)+'\x73'],0x385+0x1*-0x1032+0xcae)?console[_0x24dc40(0x230)](_0x24dc40(0x633)+this[_0x24dc40(0x42c)]+'\x5d\u7b7e\u5230\u6210\u529f'):console[_0x24dc40(0x230)](_0x24dc40(0x633)+this[_0x24dc40(0x42c)]+(_0x24dc40(0x246)+'\uff1a')+_0x265816['\x64\x61\x74\x61'][_0x24dc40(0x42e)+_0x24dc40(0x53a)+_0x24dc40(0x3ba)][_0x24dc40(0x6e6)]):console[_0x24dc40(0x230)](_0x24dc40(0x633)+this[_0x24dc40(0x42c)]+('\x5d\u7b7e\u5230\u83b7\u5f97'+'\uff1a')+_0x265816[_0x24dc40(0x251)][_0x24dc40(0x48a)]['\x61\x6d\x6f\x75\x6e'+'\x74']+'\u91d1\u5e01');continue;case'\x31':await _0x3ba1e8['\x77\x61\x69\x74'](0x2e3*-0x1+-0x22fb+-0x61*-0x66);continue;case'\x32':await this[_0x24dc40(0x236)+_0x24dc40(0x369)](_0x54479e[_0x24dc40(0x4dd)]);continue;case'\x33':await _0x3ba1e8[_0x24dc40(0x1d2)](0x1*-0x133b+-0xa8d+-0x1e90*-0x1);continue;case'\x34':await this[_0x24dc40(0x236)+_0x24dc40(0x369)](_0x54479e['\x73\x69\x67\x6e\x31']);continue;}break;}}else console[_0x24dc40(0x230)](_0x24dc40(0x633)+this['\x6e\x61\x6d\x65']+(_0x24dc40(0x246)+'\uff1a')+_0x265816[_0x24dc40(0x421)+_0x24dc40(0x43c)]);}async[_0x2fc758(0x619)+_0x2fc758(0x331)](){const _0x5b1f4d=_0x2fc758,_0xddccea={'\x6d\x6a\x6d\x77\x58':function(_0x5c22cd,_0x58973b){return _0x5c22cd==_0x58973b;},'\x72\x44\x48\x48\x78':function(_0x2a0f29,_0x345807){return _0x2a0f29>_0x345807;},'\x74\x79\x46\x75\x4c':function(_0x3c8350,_0x317b34){return _0x3c8350(_0x317b34);},'\x67\x76\x56\x65\x76':function(_0x4e48a0,_0x3d2f41){return _0x4e48a0>_0x3d2f41;},'\x57\x58\x57\x41\x63':function(_0x174d9e,_0x23a615){return _0x174d9e/_0x23a615;},'\x47\x72\x7a\x71\x63':_0x5b1f4d(0x2c7),'\x61\x59\x66\x4c\x6a':_0x5b1f4d(0x24f)};let _0x42d4ac=_0x5b1f4d(0x599)+'\x3a\x2f\x2f\x65\x6e'+_0x5b1f4d(0x5f5)+_0x5b1f4d(0x541)+_0x5b1f4d(0x682)+_0x5b1f4d(0x51d)+_0x5b1f4d(0x48b)+'\x2f\x77\x64\x2f\x65'+_0x5b1f4d(0x3fc)+_0x5b1f4d(0x3b1)+_0x5b1f4d(0x5dc)+_0x5b1f4d(0x331),_0x433b18='',_0x145608=_0x4c62f9(_0x42d4ac,this[_0x5b1f4d(0x6c1)+'\x65'],_0x433b18);await _0x553fe7('\x67\x65\x74',_0x145608);let _0x5b426d=_0x1b0221;if(!_0x5b426d)return;if(_0xddccea[_0x5b1f4d(0x4d3)](_0x5b426d[_0x5b1f4d(0x46d)+'\x74'],0x235+0x6*0x655+-0x2832)){console[_0x5b1f4d(0x230)](_0x5b1f4d(0x633)+this['\x6e\x61\x6d\x65']+(_0x5b1f4d(0x260)+_0x5b1f4d(0x3f4)));for(let _0x1a3759 of _0x5b426d[_0x5b1f4d(0x251)][_0x5b1f4d(0x42e)+'\x54\x61\x73\x6b\x73'][_0x5b1f4d(0x619)+_0x5b1f4d(0x331)]){for(let _0x1bf38c in _0x425116){if(_0x1a3759[_0x5b1f4d(0x2c0)+'\x64']==_0x425116[_0x1bf38c]){let _0x3e14ce=_0x1a3759[_0x5b1f4d(0x552)+_0x5b1f4d(0x2f1)]['\x6d\x61\x74\x63\x68'](/([\w\/]+)/)[-0x58*-0x4f+-0x1ddc+0x2b5]['\x73\x70\x6c\x69\x74']('\x2f'),_0xaf7ae7='',_0x573fc9=_0xddccea[_0x5b1f4d(0x4d3)](_0x1a3759[_0x5b1f4d(0x5d9)+'\x73'],0xc0d+0x16b3+0x22bb*-0x1)?![]:!![],_0x16213d=this['\x74\x61\x73\x6b'][_0x1a3759[_0x5b1f4d(0x2c0)+'\x64']][_0x5b1f4d(0x1c6)];if(_0xddccea[_0x5b1f4d(0x62b)](_0x3e14ce[_0x5b1f4d(0x2bd)+'\x68'],0x45b*-0x3+0x8*0x4c9+-0x1936)){let _0x3c51d4=_0xddccea['\x74\x79\x46\x75\x4c'](parseInt,_0x3e14ce[0xb*-0xd1+-0x1e*0x89+0x1909]),_0x3c6f7c=_0xddccea[_0x5b1f4d(0x26f)](parseInt,_0x3e14ce[-0x2354+0xc8c+-0x13*-0x133]);_0x16213d=_0xddccea[_0x5b1f4d(0x6d0)](_0x3c6f7c,-0x258e+0x1*0x23e0+0x1ae)?Math[_0x5b1f4d(0x5b7)](_0xddccea[_0x5b1f4d(0x68f)](_0x3c6f7c,_0x152066)):-0x32*0xb7+0x171b+-0xca4*-0x1,_0xaf7ae7=_0x3c51d4+'\x2f'+_0x3c6f7c+'\uff0c';}const _0x14d854={};_0x14d854[_0x5b1f4d(0x1c6)]=_0x16213d,_0x14d854['\x6e\x65\x65\x64\x52'+'\x75\x6e']=_0x573fc9,this[_0x5b1f4d(0x43d)][_0x1a3759[_0x5b1f4d(0x2c0)+'\x64']]=_0x14d854,console[_0x5b1f4d(0x230)]('\u3010'+_0x1a3759['\x74\x69\x74\x6c\x65']+'\u3011\x20'+_0xaf7ae7+(_0x573fc9?_0xddccea[_0x5b1f4d(0x632)]:_0xddccea['\x61\x59\x66\x4c\x6a'])+(_0x5b1f4d(0x57f)+'\u5b8c\u6210')+_0x16213d+_0x5b1f4d(0x34b));continue;}}}}else console[_0x5b1f4d(0x230)](_0x5b1f4d(0x633)+this[_0x5b1f4d(0x42c)]+(_0x5b1f4d(0x224)+_0x5b1f4d(0x574))+_0x5b426d[_0x5b1f4d(0x421)+'\x5f\x6d\x73\x67']);}async['\x74\x61\x73\x6b\x54'+_0x2fc758(0x5da)](_0x4872a0){const _0x58b63d=_0x2fc758,_0x11cb6f={};_0x11cb6f[_0x58b63d(0x2df)]=_0x58b63d(0x537),_0x11cb6f['\x73\x66\x43\x79\x59']=function(_0x2813a8,_0xfd57cd){return _0x2813a8==_0xfd57cd;};const _0x2ab95e=_0x11cb6f;let _0x141437='\x68\x74\x74\x70\x73'+_0x58b63d(0x4cf)+_0x58b63d(0x5f5)+_0x58b63d(0x541)+_0x58b63d(0x682)+'\x75\x2e\x63\x6f\x6d'+_0x58b63d(0x48b)+_0x58b63d(0x2fb)+_0x58b63d(0x3fc)+_0x58b63d(0x3b1)+_0x58b63d(0x35f)+_0x58b63d(0x1c1)+'\x61\x73\x6b\x49\x64'+'\x3d'+_0x4872a0,_0x56999d='',_0x2fac3c=_0x4c62f9(_0x141437,this[_0x58b63d(0x6c1)+'\x65'],_0x56999d);await _0x553fe7(_0x2ab95e[_0x58b63d(0x2df)],_0x2fac3c);let _0x53d4c8=_0x1b0221;if(!_0x53d4c8)return;if(_0x2ab95e['\x73\x66\x43\x79\x59'](_0x53d4c8['\x72\x65\x73\x75\x6c'+'\x74'],0x802+0x1*-0xb43+0x342)){}else console[_0x58b63d(0x230)](_0x58b63d(0x633)+this['\x6e\x61\x6d\x65']+(_0x58b63d(0x655)+'\x5b')+_0x4872a0+_0x58b63d(0x350)+_0x53d4c8[_0x58b63d(0x421)+'\x5f\x6d\x73\x67']);}async[_0x2fc758(0x5c1)+_0x2fc758(0x376)](_0x581635){const _0x43a1e9=_0x2fc758,_0x2428f7={'\x66\x43\x4d\x78\x63':function(_0x2520e1,_0x4d709a,_0x3fda28,_0x2defae){return _0x2520e1(_0x4d709a,_0x3fda28,_0x2defae);},'\x61\x59\x56\x7a\x4f':function(_0x1bec25,_0x16d5d5,_0x20604b){return _0x1bec25(_0x16d5d5,_0x20604b);},'\x63\x49\x7a\x43\x4f':_0x43a1e9(0x537),'\x61\x69\x66\x44\x72':function(_0x47c2b0,_0x39b22e){return _0x47c2b0==_0x39b22e;}};let _0x90c23d=_0x43a1e9(0x599)+_0x43a1e9(0x4cf)+_0x43a1e9(0x5f5)+'\x67\x65\x2e\x6b\x75'+'\x61\x69\x73\x68\x6f'+_0x43a1e9(0x51d)+_0x43a1e9(0x48b)+'\x2f\x77\x64\x2f\x65'+'\x6e\x63\x6f\x75\x72'+_0x43a1e9(0x3b1)+_0x43a1e9(0x2e4)+'\x65\x77\x61\x72\x64'+'\x3f\x74\x61\x73\x6b'+_0x43a1e9(0x687)+_0x581635,_0x37226f='',_0x4f75f3=_0x2428f7[_0x43a1e9(0x60b)](_0x4c62f9,_0x90c23d,this[_0x43a1e9(0x6c1)+'\x65'],_0x37226f);await _0x2428f7[_0x43a1e9(0x442)](_0x553fe7,_0x2428f7['\x63\x49\x7a\x43\x4f'],_0x4f75f3);let _0x41d290=_0x1b0221;if(!_0x41d290)return;_0x2428f7['\x61\x69\x66\x44\x72'](_0x41d290[_0x43a1e9(0x46d)+'\x74'],-0x6*-0x12d+-0x964+0x257)?console[_0x43a1e9(0x230)](_0x43a1e9(0x633)+this[_0x43a1e9(0x42c)]+(_0x43a1e9(0x69a)+'\x5b')+_0x581635+'\x5d\u5956\u52b1\u6210\u529f'):console[_0x43a1e9(0x230)]('\u8d26\u53f7\x5b'+this[_0x43a1e9(0x42c)]+('\x5d\u9886\u53d6\u4efb\u52a1'+'\x5b')+_0x581635+('\x5d\u5956\u52b1\u5931\u8d25'+'\uff1a')+_0x41d290[_0x43a1e9(0x421)+'\x5f\x6d\x73\x67']);}async[_0x2fc758(0x5d8)+'\x75\x72\x65\x42\x6f'+_0x2fc758(0x31e)](_0x51873=!![]){const _0xfa1f4e=_0x2fc758,_0x941654={'\x6e\x42\x5a\x6a\x4e':function(_0x2d5547,_0x66d264,_0x661792,_0x1e2298){return _0x2d5547(_0x66d264,_0x661792,_0x1e2298);},'\x6f\x7a\x79\x7a\x4f':function(_0x140af9,_0x3efb4a,_0x27af8e){return _0x140af9(_0x3efb4a,_0x27af8e);},'\x6c\x65\x4f\x72\x44':_0xfa1f4e(0x537),'\x4e\x66\x48\x6d\x44':function(_0x10c0ee,_0x171b27){return _0x10c0ee==_0x171b27;}};let _0xedbf44=_0xfa1f4e(0x599)+'\x3a\x2f\x2f\x65\x6e'+_0xfa1f4e(0x5f5)+_0xfa1f4e(0x541)+_0xfa1f4e(0x682)+_0xfa1f4e(0x51d)+_0xfa1f4e(0x48b)+_0xfa1f4e(0x2fb)+_0xfa1f4e(0x3fc)+_0xfa1f4e(0x3b1)+_0xfa1f4e(0x2ad)+_0xfa1f4e(0x492)+_0xfa1f4e(0x33a),_0x2c769f='',_0x20a588=_0x941654[_0xfa1f4e(0x4fc)](_0x4c62f9,_0xedbf44,this[_0xfa1f4e(0x6c1)+'\x65'],_0x2c769f);await _0x941654[_0xfa1f4e(0x43e)](_0x553fe7,_0x941654[_0xfa1f4e(0x506)],_0x20a588);let _0x452c99=_0x1b0221;if(!_0x452c99)return;if(_0x941654[_0xfa1f4e(0x41d)](_0x452c99[_0xfa1f4e(0x46d)+'\x74'],0x1bb8+0x816+-0x23cd)){if(_0x452c99[_0xfa1f4e(0x251)]){if(_0x941654[_0xfa1f4e(0x41d)](_0x452c99[_0xfa1f4e(0x251)]['\x73\x74\x61\x74\x75'+'\x73'],0x2*-0xca6+-0x18d9+-0x1*-0x3229))console[_0xfa1f4e(0x230)]('\u8d26\u53f7\x5b'+this[_0xfa1f4e(0x42c)]+(_0xfa1f4e(0x558)+'\u7bb1\u6b21\u6570\u5df2\u7528'+'\u5b8c\uff0c\u8bf7\u660e\u5929'+'\u518d\u6765'));else _0x941654[_0xfa1f4e(0x41d)](_0x452c99[_0xfa1f4e(0x251)][_0xfa1f4e(0x5d9)+'\x73'],-0x1da4+-0x1*-0xfa3+0xe04)?(await _0x3ba1e8['\x77\x61\x69\x74'](-0x41f+-0x899+0x36*0x40),await this[_0xfa1f4e(0x47b)+'\x6f\x78'](_0x452c99['\x64\x61\x74\x61']['\x74\x6f\x6b\x65\x6e'])):console[_0xfa1f4e(0x230)](_0xfa1f4e(0x633)+this[_0xfa1f4e(0x42c)]+(_0xfa1f4e(0x639)+_0xfa1f4e(0x446))+_0x452c99[_0xfa1f4e(0x251)]['\x74\x72\x65\x61\x73'+'\x75\x72\x65\x43\x75'+_0xfa1f4e(0x645)+'\x54\x61\x73\x6b\x52'+'\x65\x6d\x61\x69\x6e'+_0xfa1f4e(0x675)+'\x64\x73']+'\u79d2');}else console['\x6c\x6f\x67']('\u8d26\u53f7\x5b'+this[_0xfa1f4e(0x42c)]+(_0xfa1f4e(0x453)+_0xfa1f4e(0x440)+_0xfa1f4e(0x66e)));}else console[_0xfa1f4e(0x230)]('\u8d26\u53f7\x5b'+this[_0xfa1f4e(0x42c)]+('\x5d\u67e5\u8be2\u5b9d\u7bb1'+_0xfa1f4e(0x648))+_0x452c99[_0xfa1f4e(0x421)+_0xfa1f4e(0x43c)]);}async[_0x2fc758(0x47b)+'\x6f\x78'](_0x317490){const _0x4edff=_0x2fc758,_0x24bef1={'\x59\x47\x5a\x6c\x76':function(_0x27b720,_0x506798,_0x30d462,_0x5d1f4b){return _0x27b720(_0x506798,_0x30d462,_0x5d1f4b);},'\x69\x4b\x61\x6d\x61':_0x4edff(0x65f)+'\x6e\x74\x2d\x54\x79'+'\x70\x65','\x43\x57\x55\x44\x71':'\x61\x70\x70\x6c\x69'+_0x4edff(0x39c)+_0x4edff(0x67b)+'\x6e','\x49\x63\x48\x79\x4c':function(_0x52f1f7,_0x344017,_0x43e80e){return _0x52f1f7(_0x344017,_0x43e80e);},'\x74\x57\x56\x73\x6f':function(_0x1da844,_0x35f105){return _0x1da844==_0x35f105;},'\x47\x4c\x67\x6c\x4d':_0x4edff(0x242)+'\x7c\x33\x7c\x30'};let _0x3b759f=_0x4edff(0x599)+_0x4edff(0x4cf)+_0x4edff(0x5f5)+_0x4edff(0x541)+_0x4edff(0x682)+'\x75\x2e\x63\x6f\x6d'+_0x4edff(0x48b)+_0x4edff(0x2fb)+_0x4edff(0x3fc)+_0x4edff(0x3b1)+_0x4edff(0x2ad)+'\x72\x65\x42\x6f\x78'+_0x4edff(0x382)+'\x72\x74',_0x10335a=_0x4edff(0x6bb)+_0x4edff(0x487)+'\x6e\x22\x3a\x22'+_0x317490+'\x22\x7d',_0x5d243a=_0x24bef1['\x59\x47\x5a\x6c\x76'](_0x4c62f9,_0x3b759f,this[_0x4edff(0x6c1)+'\x65'],_0x10335a);_0x5d243a[_0x4edff(0x4a9)+'\x72\x73'][_0x24bef1[_0x4edff(0x568)]]=_0x24bef1[_0x4edff(0x41c)],await _0x24bef1[_0x4edff(0x6b1)](_0x553fe7,_0x4edff(0x3d9),_0x5d243a);let _0x2fc85a=_0x1b0221;if(!_0x2fc85a)return;if(_0x24bef1[_0x4edff(0x325)](_0x2fc85a['\x72\x65\x73\x75\x6c'+'\x74'],-0xdcf+0x54b+-0x2d7*-0x3)){const _0xa8291a=_0x24bef1[_0x4edff(0x563)][_0x4edff(0x660)]('\x7c');let _0x565abd=0x9ad*-0x4+-0x1aed+0x41a1;while(!![]){switch(_0xa8291a[_0x565abd++]){case'\x30':await this[_0x4edff(0x5d8)+_0x4edff(0x5ab)+_0x4edff(0x31e)](![]);continue;case'\x31':await _0x3ba1e8[_0x4edff(0x1d2)](0x15f5+0x26e*-0x4+-0xb75);continue;case'\x32':await this[_0x4edff(0x236)+_0x4edff(0x369)](_0x54479e['\x62\x6f\x78']);continue;case'\x33':await _0x3ba1e8[_0x4edff(0x1d2)](-0xc*0x20f+-0x1e4f*0x1+-0x45*-0xcf);continue;case'\x34':console[_0x4edff(0x230)]('\u8d26\u53f7\x5b'+this[_0x4edff(0x42c)]+(_0x4edff(0x29d)+'\u5f97')+_0x2fc85a[_0x4edff(0x251)]['\x72\x65\x77\x61\x72'+_0x4edff(0x233)+'\x74']+'\u91d1\u5e01');continue;}break;}}else console['\x6c\x6f\x67'](_0x4edff(0x633)+this[_0x4edff(0x42c)]+(_0x4edff(0x68d)+'\u8d25\uff1a')+_0x2fc85a['\x65\x72\x72\x6f\x72'+_0x4edff(0x43c)]);}async['\x6b\x73\x67\x6a'](_0x25f6b5){const _0x22d911=_0x2fc758,_0x375f5f={'\x69\x68\x5a\x68\x53':function(_0x48c4a6,_0x515a21){return _0x48c4a6+_0x515a21;},'\x4c\x74\x5a\x77\x67':function(_0xb89766,_0x1fd06f){return _0xb89766+_0x1fd06f;},'\x74\x4b\x43\x43\x50':function(_0x167292,_0x5f5cf0,_0x468530,_0x12fc29){return _0x167292(_0x5f5cf0,_0x468530,_0x12fc29);},'\x4b\x52\x4f\x46\x58':function(_0x1253ab,_0x570621,_0x5ba1c0){return _0x1253ab(_0x570621,_0x5ba1c0);},'\x4a\x67\x54\x70\x6d':'\x70\x6f\x73\x74'};let _0x36671d=_0x375f5f[_0x22d911(0x691)](_0x375f5f[_0x22d911(0x452)](_0x22d911(0x60d)+_0x22d911(0x636)+'\x44\x5f',_0x53e622(-0x18c0+-0x257*-0x6+0xac6)),'\x3b'),_0x3a119a=this['\x63\x6f\x6f\x6b\x69'+'\x65'][_0x22d911(0x4dc)+'\x63\x65'](/did=ANDROID_\w+;/,_0x36671d),_0x53fe40=_0x22d911(0x599)+'\x3a\x2f\x2f\x61\x70'+_0x22d911(0x45d)+_0x22d911(0x550)+'\x68\x6f\x75\x2e\x63'+_0x22d911(0x39f)+_0x22d911(0x64f)+_0x22d911(0x527)+_0x22d911(0x4d0)+_0x22d911(0x3f3)+_0x22d911(0x2ac)+_0x22d911(0x473)+_0x22d911(0x3b5),_0x58d223=_0x22d911(0x1c8)+_0x22d911(0x241)+'\x3d'+_0x25f6b5+(_0x22d911(0x2bf)+_0x22d911(0x3de)+_0x22d911(0x64d)+_0x22d911(0x1e3)),_0x36f064=_0x375f5f[_0x22d911(0x26d)](_0x4c62f9,_0x53fe40,_0x3a119a,_0x58d223);await _0x375f5f[_0x22d911(0x6b0)](_0x553fe7,_0x375f5f[_0x22d911(0x6cb)],_0x36f064);let _0x3b9839=_0x1b0221;if(!_0x3b9839)return;_0x3b9839[_0x22d911(0x46d)+'\x74']==0x103f*0x1+-0x1f18+0x1*0xeda?console[_0x22d911(0x230)](_0x22d911(0x633)+this[_0x22d911(0x42c)]+_0x22d911(0x546)+_0x3b9839['\x64\x61\x74\x61'][_0x22d911(0x5a1)+'\x74']+'\u91d1\u5e01'):console[_0x22d911(0x230)](_0x22d911(0x633)+this[_0x22d911(0x42c)]+(_0x22d911(0x406)+'\uff1a')+_0x3b9839[_0x22d911(0x421)+_0x22d911(0x43c)]);}async[_0x2fc758(0x236)+'\x61\x72\x61\x6d'](_0x5e737f){const _0x180e9c=_0x2fc758,_0x483ef4={'\x72\x45\x43\x67\x70':function(_0x14762b,_0x4d9422,_0x5adf1c,_0x1ea98a){return _0x14762b(_0x4d9422,_0x5adf1c,_0x1ea98a);},'\x71\x4f\x43\x42\x41':function(_0x4feb34,_0x1a18d2,_0x492bcf){return _0x4feb34(_0x1a18d2,_0x492bcf);},'\x6f\x54\x73\x69\x57':_0x180e9c(0x3d9),'\x70\x71\x77\x6e\x77':function(_0xf041f6,_0x3bb665){return _0xf041f6==_0x3bb665;},'\x44\x61\x6a\x65\x61':function(_0x1288d8,_0x178f00){return _0x1288d8>_0x178f00;}};let _0x295a88=_0x180e9c(0x599)+_0x180e9c(0x2ff)+_0x180e9c(0x45d)+_0x180e9c(0x550)+_0x180e9c(0x221)+_0x180e9c(0x39f)+_0x180e9c(0x2a7)+'\x76\x31\x2f\x72\x65'+'\x77\x61\x72\x64\x2f'+'\x61\x64\x3f\x6b\x70'+_0x180e9c(0x217)+'\x52\x4f\x49\x44\x5f'+_0x180e9c(0x390)+_0x180e9c(0x29a)+_0x180e9c(0x5f6)+_0x180e9c(0x3eb),_0x56e039=_0x180e9c(0x4ca)+_0x180e9c(0x2e2)+_0x180e9c(0x20b)+_0x180e9c(0x328)+_0x180e9c(0x31c)+_0x180e9c(0x4b0)+_0x180e9c(0x425)+_0x180e9c(0x2b4)+'\x67\x6a\x41\x77\x25'+'\x32\x42\x74\x44\x7a'+'\x31\x6d\x5a\x56\x57'+'\x65\x74\x41\x70\x48'+_0x180e9c(0x270)+_0x180e9c(0x42a)+_0x180e9c(0x388)+_0x180e9c(0x393)+_0x180e9c(0x520)+_0x180e9c(0x579)+_0x180e9c(0x1e4)+'\x4d\x7a\x53\x72\x35'+_0x180e9c(0x482)+_0x180e9c(0x3e0)+_0x180e9c(0x56c)+'\x73\x6c\x4f\x6f\x30'+_0x180e9c(0x301)+'\x57\x61\x6f\x47\x58'+_0x180e9c(0x34a)+_0x180e9c(0x560)+_0x180e9c(0x5b9)+_0x180e9c(0x635)+_0x180e9c(0x4aa)+_0x180e9c(0x36e)+_0x180e9c(0x5e0)+_0x180e9c(0x554)+_0x180e9c(0x312)+_0x180e9c(0x253)+_0x180e9c(0x548)+'\x6c\x54\x4b\x68\x6d'+_0x180e9c(0x5be)+_0x180e9c(0x1f1)+'\x69\x76\x47\x74\x63'+'\x50\x36\x6f\x37\x64'+_0x180e9c(0x206)+'\x6e\x33\x4c\x33\x61'+_0x180e9c(0x4d1)+_0x180e9c(0x277)+_0x180e9c(0x42b)+'\x67\x36\x68\x74\x39'+'\x31\x4c\x77\x6b\x30'+_0x180e9c(0x5d1)+_0x180e9c(0x445)+_0x180e9c(0x583)+_0x180e9c(0x26c)+_0x180e9c(0x4cc)+'\x42\x30\x67\x6e\x78'+_0x180e9c(0x676)+_0x180e9c(0x4c2)+_0x180e9c(0x3c4)+'\x48\x6b\x37\x69\x77'+'\x64\x36\x5a\x56\x37'+_0x180e9c(0x36c)+_0x180e9c(0x5df)+'\x47\x41\x25\x32\x42'+'\x65\x46\x53\x71\x41'+'\x39\x52\x68\x30\x66'+_0x180e9c(0x69c)+'\x55\x38\x4b\x4a\x78'+_0x180e9c(0x24e)+_0x180e9c(0x3ad)+_0x180e9c(0x315)+_0x180e9c(0x5e5)+'\x44\x55\x70\x43\x6b'+'\x62\x30\x48\x6d\x57'+_0x180e9c(0x365)+'\x76\x36\x32\x67\x71'+_0x180e9c(0x65b)+'\x65\x76\x79\x33\x54'+_0x180e9c(0x2ab)+_0x180e9c(0x5a8)+_0x180e9c(0x699)+_0x180e9c(0x329)+_0x180e9c(0x58d)+_0x180e9c(0x2b6)+_0x180e9c(0x3a8)+'\x66\x67\x6c\x68\x6f'+_0x180e9c(0x347)+'\x51\x61\x71\x4c\x53'+'\x72\x77\x58\x64\x33'+_0x180e9c(0x455)+'\x6b\x4d\x71\x30\x31'+_0x180e9c(0x267)+_0x180e9c(0x5bf)+_0x180e9c(0x6e9)+_0x180e9c(0x621)+_0x180e9c(0x52b)+_0x180e9c(0x27e)+_0x180e9c(0x1e8)+_0x180e9c(0x505)+_0x180e9c(0x4d2)+_0x180e9c(0x62f)+_0x180e9c(0x2a6)+_0x180e9c(0x591)+_0x180e9c(0x511)+_0x180e9c(0x3ee)+'\x61\x25\x32\x46\x34'+_0x180e9c(0x2b8)+'\x32\x42\x43\x59\x74'+_0x180e9c(0x38a)+_0x180e9c(0x2c5)+_0x180e9c(0x5ef)+_0x180e9c(0x2af)+_0x180e9c(0x2f5)+_0x180e9c(0x47f)+_0x180e9c(0x4ab)+_0x180e9c(0x4bc)+_0x180e9c(0x39e)+_0x180e9c(0x698)+_0x180e9c(0x688)+_0x180e9c(0x657)+_0x180e9c(0x296)+_0x180e9c(0x604)+_0x180e9c(0x441)+_0x180e9c(0x3bb)+_0x180e9c(0x3b9)+_0x180e9c(0x5ad)+'\x32\x42\x4f\x30\x51'+_0x180e9c(0x49b)+_0x180e9c(0x5d7)+'\x31\x51\x71\x74\x6d'+_0x180e9c(0x1ee)+_0x180e9c(0x24b)+_0x180e9c(0x447)+'\x62\x6c\x4a\x6b\x31'+_0x180e9c(0x22a)+_0x180e9c(0x2f0)+_0x180e9c(0x2ce)+_0x180e9c(0x66b)+'\x32\x42\x4d\x7a\x74'+'\x48\x33\x4f\x6a\x36'+_0x180e9c(0x575)+_0x180e9c(0x31f)+'\x78\x25\x32\x42\x44'+_0x180e9c(0x58c)+_0x180e9c(0x1d6)+_0x180e9c(0x335)+'\x6d\x72\x47\x70\x77'+_0x180e9c(0x69d)+_0x180e9c(0x4b7)+'\x6d\x44\x62\x74\x25'+'\x32\x46\x68\x65\x31'+_0x180e9c(0x2a1)+_0x180e9c(0x25f)+_0x180e9c(0x5b2)+_0x180e9c(0x476)+'\x50\x61\x45\x4b\x62'+'\x75\x53\x6b\x4d\x34'+_0x180e9c(0x3e7)+_0x180e9c(0x1fc)+_0x180e9c(0x4c7)+'\x69\x31\x79\x59\x34'+'\x74\x58\x30\x32\x36'+'\x59\x75\x62\x79\x51'+_0x180e9c(0x22c)+'\x53\x76\x71\x33\x6f'+_0x180e9c(0x27d)+_0x180e9c(0x46c)+_0x180e9c(0x457)+_0x180e9c(0x32b)+_0x180e9c(0x2d3)+_0x180e9c(0x417)+'\x6d\x39\x6d\x25\x32'+_0x180e9c(0x5fc)+_0x180e9c(0x4ed)+_0x180e9c(0x380)+_0x180e9c(0x316)+'\x66\x68\x69\x54\x63'+_0x180e9c(0x400)+_0x180e9c(0x3bd)+_0x180e9c(0x4f6)+_0x180e9c(0x274)+_0x180e9c(0x547)+_0x180e9c(0x40b)+'\x4e\x31\x6c\x42\x58'+'\x79\x43\x32\x64\x48'+_0x180e9c(0x3a5)+_0x180e9c(0x566)+_0x180e9c(0x4ea)+_0x180e9c(0x41b)+'\x62\x45\x6a\x51\x41'+_0x180e9c(0x4bb)+_0x180e9c(0x22f)+_0x180e9c(0x477)+_0x180e9c(0x5e3)+_0x180e9c(0x38f)+'\x55\x68\x50\x65\x4f'+_0x180e9c(0x3c3)+_0x180e9c(0x21a)+'\x6c\x67\x34\x37\x66'+_0x180e9c(0x1d7)+'\x67\x6e\x3d\x35\x61'+(_0x180e9c(0x429)+_0x180e9c(0x2d6)+_0x180e9c(0x4c1)+'\x32\x36\x39\x33\x65'+_0x180e9c(0x216)+_0x180e9c(0x67c)+'\x38\x30\x35\x66\x34'+_0x180e9c(0x481)+_0x180e9c(0x569)+_0x180e9c(0x6e5)+_0x180e9c(0x218)+_0x180e9c(0x611)+'\x36\x61'),_0xc0d42a=_0x483ef4[_0x180e9c(0x48e)](_0x4c62f9,_0x295a88,this[_0x180e9c(0x6c1)+'\x65'],_0x56e039);await _0x483ef4[_0x180e9c(0x4af)](_0x553fe7,_0x483ef4['\x6f\x54\x73\x69\x57'],_0xc0d42a);let _0x57883e=_0x1b0221;if(!_0x57883e)return;_0x483ef4[_0x180e9c(0x5c8)](_0x57883e[_0x180e9c(0x46d)+'\x74'],-0x58*-0x71+0xcce*-0x2+-0xd3b)?_0x57883e[_0x180e9c(0x305)+_0x180e9c(0x234)]&&_0x57883e[_0x180e9c(0x305)+_0x180e9c(0x234)]['\x6c\x65\x6e\x67\x74'+'\x68']>-0x1a3*-0x17+0x2*0x1107+-0x47b3*0x1&&_0x57883e['\x69\x6d\x70\x41\x64'+_0x180e9c(0x234)][0x34a+0x20ef*0x1+0x21*-0x119][_0x180e9c(0x449)+'\x6f']&&_0x483ef4[_0x180e9c(0x5db)](_0x57883e[_0x180e9c(0x305)+_0x180e9c(0x234)][0x209f+0x1aea+-0x3b89][_0x180e9c(0x449)+'\x6f'][_0x180e9c(0x2bd)+'\x68'],-0x1594+-0x6*0x585+-0x1*-0x36b2)&&_0x57883e['\x69\x6d\x70\x41\x64'+'\x49\x6e\x66\x6f'][-0x2a3+-0x218+-0x4bb*-0x1]['\x61\x64\x49\x6e\x66'+'\x6f'][0x1d*0x7f+0x24f2+0x11*-0x305][_0x180e9c(0x37c)+'\x65\x49\x6e\x66\x6f']&&(await _0x3ba1e8['\x77\x61\x69\x74'](0x18*0x2d+0x138b+-0x9f*0x25),await this['\x6b\x73\x41\x64\x52'+'\x65\x77\x61\x72\x64'](_0x57883e[_0x180e9c(0x543)],_0x57883e[_0x180e9c(0x305)+_0x180e9c(0x234)][0x5ec+-0x12d*0x9+0x1*0x4a9][_0x180e9c(0x449)+'\x6f'][0xad9*0x1+-0x44f*-0x2+-0x1377]['\x61\x64\x42\x61\x73'+'\x65\x49\x6e\x66\x6f']['\x63\x72\x65\x61\x74'+_0x180e9c(0x353)],_0x5e737f)):console['\x6c\x6f\x67']('\u8d26\u53f7\x5b'+this[_0x180e9c(0x42c)]+_0x180e9c(0x28b)+_0x5e737f[_0x180e9c(0x42c)]+_0x180e9c(0x6e3)+_0x57883e[_0x180e9c(0x421)+_0x180e9c(0x43c)]);}async[_0x2fc758(0x483)+_0x2fc758(0x376)](_0x570f6e,_0xd88719,_0x2cce04){const _0x471f0d=_0x2fc758,_0x144c26={};_0x144c26[_0x471f0d(0x36b)]=function(_0x3ee57b,_0x5bc2d7){return _0x3ee57b+_0x5bc2d7;},_0x144c26[_0x471f0d(0x6ac)]=function(_0xc7a027,_0x558d65){return _0xc7a027*_0x558d65;},_0x144c26[_0x471f0d(0x68a)]=function(_0x216a7a,_0x558a05){return _0x216a7a-_0x558a05;},_0x144c26['\x6c\x63\x5a\x72\x4c']='\x70\x6f\x73\x74',_0x144c26[_0x471f0d(0x4a4)]=function(_0x2b4d41,_0x4d0d38){return _0x2b4d41==_0x4d0d38;};const _0x358572=_0x144c26;let _0x502056=_0x2cce04[_0x471f0d(0x46b)]?_0x2cce04[_0x471f0d(0x46b)]:_0xec9f77,_0x4ab817=new Date()['\x67\x65\x74\x54\x69'+'\x6d\x65'](),_0x3d0549=_0x358572[_0x471f0d(0x36b)](Math[_0x471f0d(0x35b)](_0x358572[_0x471f0d(0x6ac)](Math['\x72\x61\x6e\x64\x6f'+'\x6d'](),-0x8d*-0x18b+-0x8f9c+0x2b3d*0x1)),0x88ad+0x137e7*0x1+-0x110cc),_0x52b090=_0x358572[_0x471f0d(0x68a)](_0x4ab817,_0x3d0549),_0x3b944a=_0x471f0d(0x599)+'\x3a\x2f\x2f\x61\x70'+_0x471f0d(0x45d)+_0x471f0d(0x550)+_0x471f0d(0x221)+_0x471f0d(0x39f)+_0x471f0d(0x64f)+_0x471f0d(0x283)+'\x73\x6b\x2f\x72\x65'+'\x70\x6f\x72\x74',_0x1f9eca=_0x471f0d(0x1fb)+_0x471f0d(0x262)+_0x471f0d(0x6af)+_0x471f0d(0x3f6)+'\x3a'+_0x2cce04['\x69\x64']+('\x2c\x22\x65\x6e\x64'+_0x471f0d(0x3fb)+'\x3a')+_0x4ab817+(_0x471f0d(0x4f2)+_0x471f0d(0x5b5)+_0x471f0d(0x2ed))+_0x502056+(_0x471f0d(0x55f)+_0x471f0d(0x493)+_0x471f0d(0x48d)+_0x471f0d(0x405)+_0x471f0d(0x1c9)+_0x471f0d(0x35e)+_0x471f0d(0x30b)+_0x471f0d(0x5de)+_0x471f0d(0x6d9)+_0x471f0d(0x408))+_0xd88719+(_0x471f0d(0x4f2)+_0x471f0d(0x500)+'\x3a\x22\x22\x2c\x22'+_0x471f0d(0x543)+'\x22\x3a')+_0x570f6e+(_0x471f0d(0x42d)+_0x471f0d(0x23b)+_0x471f0d(0x320)+_0x471f0d(0x485)+_0x471f0d(0x394))+_0x2cce04['\x70\x61\x67\x65\x49'+'\x64']+(_0x471f0d(0x5cf)+_0x471f0d(0x29b)+'\x37\x34\x2c\x22\x73'+_0x471f0d(0x498)+_0x471f0d(0x265))+_0x52b090+(_0x471f0d(0x499)+'\x50\x61\x67\x65\x49'+_0x471f0d(0x392))+_0x2cce04[_0x471f0d(0x3a0)+_0x471f0d(0x52e)]+'\x7d',_0x5600f3=_0x4c62f9(_0x3b944a,this[_0x471f0d(0x6c1)+'\x65'],_0x1f9eca);await _0x553fe7(_0x358572[_0x471f0d(0x54b)],_0x5600f3);let _0x456f60=_0x1b0221;if(!_0x456f60)return;_0x358572[_0x471f0d(0x4a4)](_0x456f60[_0x471f0d(0x46d)+'\x74'],0xf0b*-0x1+-0x4*-0x13+-0x76*-0x20)?console[_0x471f0d(0x230)](_0x471f0d(0x633)+this[_0x471f0d(0x42c)]+'\x5d\u770b'+_0x2cce04[_0x471f0d(0x42c)]+'\u83b7\u5f97'+_0x456f60[_0x471f0d(0x251)][_0x471f0d(0x6a3)+'\x6f\x75\x6e\x74']+'\u91d1\u5e01'):console['\x6c\x6f\x67'](_0x471f0d(0x633)+this[_0x471f0d(0x42c)]+'\x5d\u770b'+_0x2cce04[_0x471f0d(0x42c)]+'\u5931\u8d25\uff1a'+_0x456f60[_0x471f0d(0x421)+_0x471f0d(0x43c)]);}async[_0x2fc758(0x292)+_0x2fc758(0x510)](){const _0x8d9b4a=_0x2fc758,_0x40a320={'\x77\x69\x6d\x6b\x6d':function(_0x57e3c1,_0x556bd7,_0x42c728){return _0x57e3c1(_0x556bd7,_0x42c728);},'\x47\x76\x68\x71\x46':'\x70\x6f\x73\x74','\x64\x7a\x45\x62\x45':function(_0x1816f6,_0x3bdca4){return _0x1816f6==_0x3bdca4;},'\x69\x62\x65\x4a\x6d':_0x8d9b4a(0x5b1)+'\x53\x53','\x79\x54\x51\x68\x51':_0x8d9b4a(0x37e)+'\u5b9d','\x64\x6e\x72\x69\x50':_0x8d9b4a(0x24d),'\x45\x64\x45\x77\x43':function(_0xd8f324,_0x53c0a9){return _0xd8f324==_0x53c0a9;}};let _0x593636=_0x8d9b4a(0x599)+_0x8d9b4a(0x479)+_0x8d9b4a(0x467)+_0x8d9b4a(0x29c)+_0x8d9b4a(0x64b)+_0x8d9b4a(0x344)+_0x8d9b4a(0x341)+_0x8d9b4a(0x66f)+_0x8d9b4a(0x4f4)+_0x8d9b4a(0x5a3)+_0x8d9b4a(0x6d8)+_0x8d9b4a(0x616)+'\x6f',_0x51c517=_0x8d9b4a(0x6dd)+'\x6e\x74\x5f\x67\x72'+'\x6f\x75\x70\x5f\x6b'+_0x8d9b4a(0x643)+_0x8d9b4a(0x4a8)+_0x8d9b4a(0x544)+_0x8d9b4a(0x1d1)+_0x8d9b4a(0x418)+_0x8d9b4a(0x494)+_0x8d9b4a(0x3c2),_0x527ec7=_0x4c62f9(_0x593636,this[_0x8d9b4a(0x6c1)+'\x65'],_0x51c517);await _0x40a320[_0x8d9b4a(0x3d0)](_0x553fe7,_0x40a320[_0x8d9b4a(0x585)],_0x527ec7);let _0x12795b=_0x1b0221;if(!_0x12795b)return;if(_0x40a320[_0x8d9b4a(0x248)](_0x12795b['\x72\x65\x73\x75\x6c'+'\x74'],_0x40a320['\x69\x62\x65\x4a\x6d'])){let _0x2910d5=_0x40a320[_0x8d9b4a(0x2cf)],_0x5b3694=_0x40a320[_0x8d9b4a(0x59b)];_0x12795b['\x61\x6c\x69\x70\x61'+'\x79\x5f\x62\x69\x6e'+'\x64']==!![]&&(this[_0x8d9b4a(0x3fe)+_0x8d9b4a(0x1ce)]=!![],this[_0x8d9b4a(0x31d)+'\x79']=_0x12795b[_0x8d9b4a(0x31d)+'\x79\x5f\x6e\x69\x63'+_0x8d9b4a(0x45c)+'\x65'],_0x2910d5=_0x8d9b4a(0x3fa)+'\u5b9d\x5b'+_0x12795b[_0x8d9b4a(0x31d)+'\x79\x5f\x6e\x69\x63'+'\x6b\x5f\x6e\x61\x6d'+'\x65']+'\x5d'),_0x40a320['\x45\x64\x45\x77\x43'](_0x12795b['\x77\x65\x63\x68\x61'+_0x8d9b4a(0x55d)+'\x64'],!![])&&(this['\x62\x69\x6e\x64\x57'+'\x65\x63\x68\x61\x74']=!![],this['\x77\x65\x63\x68\x61'+'\x74']=_0x12795b[_0x8d9b4a(0x4f1)+_0x8d9b4a(0x60f)+_0x8d9b4a(0x45c)+'\x65'],_0x5b3694=_0x8d9b4a(0x51a)+'\x5b'+_0x12795b['\x77\x65\x63\x68\x61'+_0x8d9b4a(0x60f)+_0x8d9b4a(0x45c)+'\x65']+'\x5d'),console['\x6c\x6f\x67'](_0x8d9b4a(0x633)+this[_0x8d9b4a(0x42c)]+'\x5d'+_0x5b3694+'\uff0c'+_0x2910d5);}else console[_0x8d9b4a(0x230)](_0x8d9b4a(0x633)+this[_0x8d9b4a(0x42c)]+(_0x8d9b4a(0x345)+_0x8d9b4a(0x4fb)+'\u51b5\u5931\u8d25\uff1a')+_0x12795b[_0x8d9b4a(0x421)+_0x8d9b4a(0x43c)]);}async[_0x2fc758(0x6dd)+_0x2fc758(0x6b6)+'\x6f'](){const _0x43c511=_0x2fc758,_0x26ebe1={'\x67\x57\x4a\x64\x4e':function(_0x457361,_0xacde4d,_0x4ded22,_0x246cda){return _0x457361(_0xacde4d,_0x4ded22,_0x246cda);},'\x76\x4b\x6f\x6d\x46':function(_0x58ee4e,_0x28d976,_0x43d89b){return _0x58ee4e(_0x28d976,_0x43d89b);},'\x6d\x42\x47\x79\x4b':function(_0x1918f6,_0x157411){return _0x1918f6==_0x157411;},'\x45\x6d\x6e\x71\x68':_0x43c511(0x5b1)+'\x53\x53'};let _0x36b5c4=_0x43c511(0x599)+'\x3a\x2f\x2f\x77\x77'+_0x43c511(0x467)+_0x43c511(0x29c)+'\x70\x61\x79\x2e\x63'+'\x6f\x6d\x2f\x70\x61'+_0x43c511(0x341)+_0x43c511(0x66f)+_0x43c511(0x642)+'\x74\x68\x64\x72\x61'+'\x77\x2f\x61\x63\x63'+_0x43c511(0x59d)+'\x69\x6e\x66\x6f',_0x1b78e7='\x61\x63\x63\x6f\x75'+'\x6e\x74\x5f\x67\x72'+_0x43c511(0x535)+_0x43c511(0x643)+_0x43c511(0x4a8)+_0x43c511(0x544)+'\x53\x48\x26\x70\x72'+_0x43c511(0x5a3)+'\x72\x73\x3d',_0x35136b=_0x26ebe1[_0x43c511(0x379)](_0x4c62f9,_0x36b5c4,this[_0x43c511(0x6c1)+'\x65'],_0x1b78e7);await _0x26ebe1[_0x43c511(0x63f)](_0x553fe7,_0x43c511(0x3d9),_0x35136b);let _0x3b153d=_0x1b0221;if(!_0x3b153d)return;_0x26ebe1[_0x43c511(0x5cd)](_0x3b153d[_0x43c511(0x46d)+'\x74'],_0x26ebe1[_0x43c511(0x264)])?this['\x6e\x65\x65\x64\x53'+'\x6d\x73']=_0x3b153d[_0x43c511(0x6d7)+_0x43c511(0x437)+_0x43c511(0x6a7)+'\x65']:console[_0x43c511(0x230)](_0x43c511(0x633)+this[_0x43c511(0x42c)]+(_0x43c511(0x603)+_0x43c511(0x2f9)+'\u8d25\uff1a')+_0x3b153d[_0x43c511(0x421)+_0x43c511(0x43c)]);}async[_0x2fc758(0x3e6)+_0x2fc758(0x28a)+'\x64'](_0x294513){const _0x3cc5d2=_0x2fc758,_0x31dc87={'\x50\x43\x4c\x4c\x42':_0x3cc5d2(0x275)+'\x59','\x4c\x63\x68\x4e\x54':'\x57\x45\x43\x48\x41'+'\x54','\x4f\x51\x62\x54\x65':function(_0x4e92a4,_0x46d0c2){return _0x4e92a4==_0x46d0c2;},'\x6d\x7a\x6c\x5a\x44':_0x3cc5d2(0x215),'\x74\x79\x5a\x41\x53':function(_0x538304,_0x84931){return _0x538304==_0x84931;},'\x49\x4b\x41\x42\x65':function(_0x2704b3,_0xf0e85c){return _0x2704b3==_0xf0e85c;},'\x77\x76\x4a\x74\x43':function(_0x4e6eb2,_0xaa5161){return _0x4e6eb2>=_0xaa5161;},'\x51\x73\x77\x76\x78':function(_0xce03ec,_0x426496){return _0xce03ec(_0x426496);},'\x51\x49\x78\x69\x77':function(_0x4fe914,_0x4f0e58){return _0x4fe914/_0x4f0e58;},'\x50\x47\x57\x61\x77':function(_0x338c03,_0x4c7dea){return _0x338c03*_0x4c7dea;},'\x52\x42\x4b\x55\x46':function(_0x28eed6,_0x23248d){return _0x28eed6(_0x23248d);},'\x55\x47\x54\x54\x63':function(_0x2af8c0,_0x2dd698){return _0x2af8c0(_0x2dd698);},'\x79\x61\x78\x66\x75':function(_0x3cccac,_0x598f7f){return _0x3cccac*_0x598f7f;},'\x56\x56\x63\x54\x61':function(_0x273692,_0x5b3af3,_0x5ee061){return _0x273692(_0x5b3af3,_0x5ee061);},'\x70\x61\x66\x41\x76':_0x3cc5d2(0x3d9),'\x61\x4b\x71\x41\x77':_0x3cc5d2(0x5b1)+'\x53\x53','\x6b\x70\x49\x52\x66':function(_0x506569,_0x3205bc){return _0x506569(_0x3205bc);}};if(!this[_0x3cc5d2(0x31d)+'\x79']&&!this[_0x3cc5d2(0x4f1)+'\x74']){console['\x6c\x6f\x67'](_0x3cc5d2(0x633)+this['\x6e\x61\x6d\x65']+('\x5d\u672a\u7ed1\u5b9a\u63d0'+_0x3cc5d2(0x58a)+_0x3cc5d2(0x56d)));return;}let _0x30eca4=this[_0x3cc5d2(0x31d)+'\x79']?_0x31dc87[_0x3cc5d2(0x5a2)]:_0x31dc87['\x4c\x63\x68\x4e\x54'],_0x2135db=_0x31dc87[_0x3cc5d2(0x2e1)](_0x30eca4,_0x3cc5d2(0x275)+'\x59')?_0x31dc87[_0x3cc5d2(0x6b8)]:'\u5fae\u4fe1',_0x1b7e60=_0x31dc87[_0x3cc5d2(0x53c)](_0x30eca4,_0x31dc87['\x50\x43\x4c\x4c\x42'])?this[_0x3cc5d2(0x31d)+'\x79']:this[_0x3cc5d2(0x4f1)+'\x74'];if(_0x31dc87[_0x3cc5d2(0x55b)](_0xc17e17,0x3*0x446+-0x1a56+-0x1*-0xd85)&&_0x31dc87[_0x3cc5d2(0x674)](_0x31dc87[_0x3cc5d2(0x258)](parseFloat,this['\x63\x61\x73\x68']),0x210c+-0x2*-0xd0d+-0x3b26*0x1+0.3))_0x294513=_0x31dc87[_0x3cc5d2(0x431)](Math['\x66\x6c\x6f\x6f\x72'](_0x31dc87[_0x3cc5d2(0x38d)](_0x31dc87[_0x3cc5d2(0x634)](parseFloat,this[_0x3cc5d2(0x389)]),-0x66f+-0x2398+0x59*0x79)),-0x1*0x998+-0xa9*-0x17+0xcb*-0x7),_0x294513>-0x8ed+-0xcac*-0x3+-0x1ce5&&(_0x294513=0x1287+0x263b+-0x3890),console['\x6c\x6f\x67'](_0x3cc5d2(0x633)+this['\x6e\x61\x6d\x65']+(_0x3cc5d2(0x475)+'\u5316\u63d0\u73b0\uff0c\u63d0'+'\u73b0')+_0x294513+'\u5143');else{if(_0x31dc87[_0x3cc5d2(0x678)](parseFloat,this[_0x3cc5d2(0x389)])<_0x294513){console[_0x3cc5d2(0x230)](_0x3cc5d2(0x633)+this[_0x3cc5d2(0x42c)]+(_0x3cc5d2(0x68c)+'\u4e0d\u8db3')+_0x294513+(_0x3cc5d2(0x3af)+'\u63d0\u73b0'));return;}}let _0x10b113=_0x3cc5d2(0x599)+'\x3a\x2f\x2f\x77\x77'+_0x3cc5d2(0x467)+'\x69\x73\x68\x6f\x75'+_0x3cc5d2(0x64b)+_0x3cc5d2(0x344)+_0x3cc5d2(0x341)+'\x6f\x75\x6e\x74\x2f'+_0x3cc5d2(0x642)+_0x3cc5d2(0x2d4)+_0x3cc5d2(0x6c0)+'\x6c\x79',_0x1343e3=_0x3cc5d2(0x6dd)+_0x3cc5d2(0x497)+_0x3cc5d2(0x535)+'\x65\x79\x3d\x49\x4e'+_0x3cc5d2(0x4a8)+'\x56\x45\x5f\x43\x41'+'\x53\x48\x26\x6d\x6f'+'\x62\x69\x6c\x65\x5f'+_0x3cc5d2(0x4bd)+_0x3cc5d2(0x5af)+_0x31dc87[_0x3cc5d2(0x2cd)](_0x294513,0x76*0x2c+-0x2*0x30d+0x1*-0xdca)+('\x26\x70\x72\x6f\x76'+'\x69\x64\x65\x72\x3d')+_0x30eca4+(_0x3cc5d2(0x5c2)+_0x3cc5d2(0x685)+'\x3d')+_0x294513*(-0x69*0x17+0x325+0x6ae)+(_0x3cc5d2(0x2b5)+'\x69\x73\x73\x69\x6f'+_0x3cc5d2(0x5fd)+'\x3d\x30\x26\x74\x68'+'\x69\x72\x64\x5f\x61'+'\x63\x63\x6f\x75\x6e'+'\x74\x3d')+_0x30eca4+(_0x3cc5d2(0x243)+_0x3cc5d2(0x567)+_0x3cc5d2(0x293)+_0x3cc5d2(0x436)+_0x3cc5d2(0x697)+_0x3cc5d2(0x21b)+_0x3cc5d2(0x55c)+_0x3cc5d2(0x6d2)+'\x64\x3d'),_0x19cfe7=_0x4c62f9(_0x10b113,this[_0x3cc5d2(0x6c1)+'\x65'],_0x1343e3);await _0x31dc87[_0x3cc5d2(0x4df)](_0x553fe7,_0x31dc87[_0x3cc5d2(0x5ae)],_0x19cfe7);let _0x35bda0=_0x1b0221;if(!_0x35bda0)return;_0x31dc87[_0x3cc5d2(0x55b)](_0x35bda0[_0x3cc5d2(0x46d)+'\x74'],_0x31dc87[_0x3cc5d2(0x310)])?_0x31dc87[_0x3cc5d2(0x258)](_0xebcfd0,_0x3cc5d2(0x633)+this[_0x3cc5d2(0x42c)]+_0x3cc5d2(0x681)+_0x294513+'\u5143\u5230'+_0x2135db+'\x5b'+_0x1b7e60+_0x3cc5d2(0x438)):_0x31dc87[_0x3cc5d2(0x6d4)](_0xebcfd0,_0x3cc5d2(0x633)+this['\x6e\x61\x6d\x65']+_0x3cc5d2(0x681)+_0x294513+'\u5143\u5230'+_0x2135db+'\x5b'+_0x1b7e60+_0x3cc5d2(0x350)+_0x35bda0[_0x3cc5d2(0x238)]);}async['\x77\x69\x74\x68\x64'+_0x2fc758(0x3ce)](_0x1541a3){const _0x33b3fa=_0x2fc758,_0x204ee5={'\x41\x50\x76\x47\x59':_0x33b3fa(0x275)+'\x59','\x42\x6a\x6d\x75\x6e':function(_0xe5042b,_0x28e88b){return _0xe5042b==_0x28e88b;},'\x51\x43\x79\x45\x6e':function(_0x4c826b,_0xaa9630){return _0x4c826b==_0xaa9630;},'\x57\x51\x48\x4c\x65':function(_0xee9835,_0x2bd03d,_0x42aeeb,_0x379b11){return _0xee9835(_0x2bd03d,_0x42aeeb,_0x379b11);},'\x59\x43\x4d\x51\x63':_0x33b3fa(0x65f)+_0x33b3fa(0x6c5)+'\x70\x65','\x43\x78\x77\x4c\x52':_0x33b3fa(0x514)+'\x63\x61\x74\x69\x6f'+'\x6e\x2f\x6a\x73\x6f'+'\x6e','\x4b\x62\x58\x7a\x41':function(_0xa62603,_0x47788a,_0x41fcd1){return _0xa62603(_0x47788a,_0x41fcd1);},'\x45\x73\x74\x51\x44':_0x33b3fa(0x3d9),'\x70\x43\x45\x78\x78':function(_0xd6446,_0x813e92){return _0xd6446(_0x813e92);},'\x58\x41\x59\x4c\x7a':function(_0x2e5448,_0x50e5cf){return _0x2e5448/_0x50e5cf;}};if(!this[_0x33b3fa(0x3fe)+_0x33b3fa(0x1ce)]&&!this[_0x33b3fa(0x3f8)+_0x33b3fa(0x3d7)]){_0xebcfd0(_0x33b3fa(0x633)+this[_0x33b3fa(0x42c)]+(_0x33b3fa(0x3b3)+'\u73b0\u8d26\u53f7\uff0c\u4e0d'+_0x33b3fa(0x56d)));return;}let _0x59e2b9=this[_0x33b3fa(0x3f8)+_0x33b3fa(0x3d7)]?_0x33b3fa(0x338)+'\x54':_0x204ee5[_0x33b3fa(0x339)];this[_0x33b3fa(0x490)+'\x70\x65']&&(_0x59e2b9=this[_0x33b3fa(0x490)+'\x70\x65'],console['\x6c\x6f\x67'](_0x33b3fa(0x633)+this[_0x33b3fa(0x42c)]+(_0x33b3fa(0x2cb)+'\u4e86\u63d0\u73b0\u6e20\u9053'+'\uff1a')+this['\x70\x61\x79\x54\x79'+'\x70\x65']));let _0x209076=_0x204ee5[_0x33b3fa(0x3a3)](_0x59e2b9,_0x204ee5[_0x33b3fa(0x339)])?_0x33b3fa(0x215):'\u5fae\u4fe1',_0x205a5f=_0x204ee5[_0x33b3fa(0x651)](_0x59e2b9,_0x204ee5[_0x33b3fa(0x339)])?this[_0x33b3fa(0x31d)+'\x79']:this['\x77\x65\x63\x68\x61'+'\x74'],_0x17b1f3=_0x33b3fa(0x599)+_0x33b3fa(0x4cf)+_0x33b3fa(0x5f5)+_0x33b3fa(0x541)+_0x33b3fa(0x682)+_0x33b3fa(0x51d)+_0x33b3fa(0x48b)+_0x33b3fa(0x2fb)+_0x33b3fa(0x3fc)+_0x33b3fa(0x2e0)+_0x33b3fa(0x386)+_0x33b3fa(0x564)+_0x33b3fa(0x28d)+'\x2f\x65\x78\x74\x65'+_0x33b3fa(0x556)+_0x33b3fa(0x2fe),_0x3b2e17=_0x33b3fa(0x2eb)+'\x6e\x6e\x65\x6c\x22'+'\x3a\x22'+_0x59e2b9+(_0x33b3fa(0x474)+_0x33b3fa(0x63d)+'\x3a')+_0x1541a3+'\x7d',_0x323187='\x6b\x75\x61\x69\x73'+'\x68\x6f\x75\x2e\x61'+_0x33b3fa(0x629)+'\x3d'+this['\x61\x70\x69\x5f\x73'+'\x74']+'\x3b',_0x5ae081=_0x204ee5['\x57\x51\x48\x4c\x65'](_0x4c62f9,_0x17b1f3,_0x323187,_0x3b2e17);_0x5ae081[_0x33b3fa(0x4a9)+'\x72\x73'][_0x204ee5[_0x33b3fa(0x311)]]=_0x204ee5[_0x33b3fa(0x6de)],await _0x204ee5[_0x33b3fa(0x628)](_0x553fe7,_0x204ee5[_0x33b3fa(0x6bf)],_0x5ae081);let _0x461efa=_0x1b0221;if(!_0x461efa)return;_0x204ee5[_0x33b3fa(0x651)](_0x461efa['\x72\x65\x73\x75\x6c'+'\x74'],0x2088+0x29*-0xe9+-0x4ca*-0x1)?_0x204ee5[_0x33b3fa(0x40e)](_0xebcfd0,'\u8d26\u53f7'+this[_0x33b3fa(0x47c)]+'\x5b'+this[_0x33b3fa(0x42c)]+_0x33b3fa(0x681)+_0x1541a3/(0x23*0xe3+-0x10c9*0x2+-0x1*-0x2ed)+'\u5143\u5230'+_0x209076+'\x5b'+_0x205a5f+'\x5d\u6210\u529f'):_0xebcfd0('\u8d26\u53f7'+this['\x69\x6e\x64\x65\x78']+'\x5b'+this[_0x33b3fa(0x42c)]+'\x5d\u63d0\u73b0'+_0x204ee5[_0x33b3fa(0x1d3)](_0x1541a3,0x22a5+0x1fc*-0x8+0x3ad*-0x5)+'\u5143\u5230'+_0x209076+'\x5b'+_0x205a5f+_0x33b3fa(0x350)+_0x461efa[_0x33b3fa(0x421)+_0x33b3fa(0x43c)]);}async[_0x2fc758(0x3e6)+_0x2fc758(0x2c2)+'\x65\x72\x76\x69\x65'+'\x77'](){const _0x9b10bb=_0x2fc758,_0x34c74f={'\x75\x5a\x51\x45\x55':function(_0x2997b1,_0x557a54){return _0x2997b1-_0x557a54;},'\x47\x76\x50\x78\x48':function(_0x3bb9d7,_0xd9e9f6,_0x33a511,_0x20a413){return _0x3bb9d7(_0xd9e9f6,_0x33a511,_0x20a413);},'\x62\x58\x78\x46\x4c':function(_0x2c8b15,_0xee2e67,_0x23ddab){return _0x2c8b15(_0xee2e67,_0x23ddab);},'\x78\x53\x78\x52\x61':'\x67\x65\x74','\x73\x5a\x4d\x58\x69':function(_0x4a8c00,_0x27f8a3){return _0x4a8c00==_0x27f8a3;},'\x79\x66\x4d\x72\x64':function(_0x3a6f85,_0x20131c){return _0x3a6f85(_0x20131c);},'\x58\x4e\x50\x70\x4d':function(_0x8625a7,_0x355f1c){return _0x8625a7<_0x355f1c;},'\x4a\x55\x65\x42\x44':function(_0x5e16bd,_0x2d5696){return _0x5e16bd(_0x2d5696);},'\x57\x45\x69\x7a\x69':function(_0x38b0a6,_0x511eb9){return _0x38b0a6>_0x511eb9;},'\x74\x45\x4f\x43\x48':function(_0x10724f,_0x39e8ec){return _0x10724f(_0x39e8ec);},'\x43\x73\x74\x70\x49':function(_0x52b87c,_0x10b247){return _0x52b87c/_0x10b247;},'\x68\x51\x65\x75\x4c':function(_0x156127,_0x50da73){return _0x156127>=_0x50da73;},'\x4c\x46\x56\x61\x43':function(_0x116c05,_0x3c7ab1){return _0x116c05(_0x3c7ab1);},'\x71\x44\x73\x6c\x6c':function(_0x22f4dc,_0x19844b){return _0x22f4dc/_0x19844b;},'\x72\x4f\x75\x6c\x63':function(_0x2ba9e3,_0x19ccd6){return _0x2ba9e3*_0x19ccd6;},'\x77\x4c\x70\x71\x52':function(_0xaf883d,_0x16a25){return _0xaf883d(_0x16a25);}};let _0x56abd4=_0x9b10bb(0x599)+_0x9b10bb(0x4cf)+_0x9b10bb(0x5f5)+'\x67\x65\x2e\x6b\x75'+_0x9b10bb(0x682)+_0x9b10bb(0x51d)+_0x9b10bb(0x48b)+'\x2f\x77\x64\x2f\x65'+_0x9b10bb(0x3fc)+'\x61\x67\x65\x2f\x61'+'\x63\x63\x6f\x75\x6e'+_0x9b10bb(0x564)+_0x9b10bb(0x28d)+_0x9b10bb(0x59a)+_0x9b10bb(0x556)+_0x9b10bb(0x69f),_0x25cafe='',_0x2d5ac0=_0x34c74f[_0x9b10bb(0x516)](_0x4c62f9,_0x56abd4,this[_0x9b10bb(0x6c1)+'\x65'],_0x25cafe);await _0x34c74f[_0x9b10bb(0x610)](_0x553fe7,_0x34c74f[_0x9b10bb(0x4a1)],_0x2d5ac0);let _0x1cd792=_0x1b0221;if(!_0x1cd792)return;if(_0x34c74f['\x73\x5a\x4d\x58\x69'](_0x1cd792[_0x9b10bb(0x46d)+'\x74'],0xaa4*-0x1+0xff*0x8+0x1*0x2ad)){if(_0x34c74f[_0x9b10bb(0x533)](_0x1cd792[_0x9b10bb(0x251)][_0x9b10bb(0x6dd)+'\x6e\x74'][_0x9b10bb(0x4e6)],!![])){console['\x6c\x6f\x67'](_0x9b10bb(0x633)+this[_0x9b10bb(0x42c)]+(_0x9b10bb(0x3cf)+'\u73b0'));return;}let _0x2a3b95=_0x34c74f['\x79\x66\x4d\x72\x64'](parseInt,_0x1cd792['\x64\x61\x74\x61'][_0x9b10bb(0x6dd)+'\x6e\x74'][_0x9b10bb(0x32d)+_0x9b10bb(0x287)+_0x9b10bb(0x2fc)+_0x9b10bb(0x51f)]);if(_0xc17e17==0x5*0x1f3+0x13c3+0x437*-0x7)_0x34c74f[_0x9b10bb(0x3be)](_0x2a3b95,-0x227b+0x1092+0x1207)?_0x34c74f[_0x9b10bb(0x683)](_0xebcfd0,_0x9b10bb(0x633)+this[_0x9b10bb(0x42c)]+('\x5d\u4f59\u989d\u4e0d\u8db3'+'\x30\x2e\x33\u5143\uff0c'+_0x9b10bb(0x6cc))):(_0x2a3b95=_0x34c74f[_0x9b10bb(0x401)](_0x2a3b95,0x9*0x2c7+-0x21cb*-0x1+0x3ed*-0xa)?0x1b4e+-0x1c59+0x1493:_0x2a3b95,_0x34c74f[_0x9b10bb(0x561)](_0xebcfd0,_0x9b10bb(0x633)+this['\x6e\x61\x6d\x65']+(_0x9b10bb(0x475)+_0x9b10bb(0x649))+_0x34c74f[_0x9b10bb(0x529)](_0x2a3b95,-0x1857+-0x2f*-0xb3+-0x822)+'\u5143'),await _0x3ba1e8[_0x9b10bb(0x1d2)](0xc9*-0xb+-0x9*-0x221+-0x9be),await this[_0x9b10bb(0x3e6)+_0x9b10bb(0x3ce)](_0x2a3b95));else{if(!_0x2eb5c1){if(_0x1cd792['\x64\x61\x74\x61'][_0x9b10bb(0x3e6)+_0x9b10bb(0x3ce)]&&_0x34c74f['\x57\x45\x69\x7a\x69'](_0x1cd792[_0x9b10bb(0x251)][_0x9b10bb(0x3e6)+_0x9b10bb(0x3ce)][_0x9b10bb(0x2bd)+'\x68'],0xca*0x31+-0x80c+-0x1e9e)){let _0x2f3988=[];for(let _0x53576b of _0x1cd792[_0x9b10bb(0x251)][_0x9b10bb(0x3e6)+_0x9b10bb(0x3ce)]['\x73\x6f\x72\x74'](function(_0x409933,_0x2b4fee){const _0x11aea0=_0x9b10bb;return _0x34c74f['\x75\x5a\x51\x45\x55'](_0x2b4fee[_0x11aea0(0x32d)+'\x6d\x6f\x75\x6e\x74'],_0x409933[_0x11aea0(0x32d)+'\x6d\x6f\x75\x6e\x74']);})){if(_0x34c74f[_0x9b10bb(0x557)](_0x2a3b95,_0x34c74f[_0x9b10bb(0x1f6)](parseInt,_0x53576b[_0x9b10bb(0x32d)+_0x9b10bb(0x39a)]))){_0x34c74f[_0x9b10bb(0x561)](_0xebcfd0,'\u8d26\u53f7\x5b'+this[_0x9b10bb(0x42c)]+_0x9b10bb(0x2f3)+_0x53576b[_0x9b10bb(0x32d)+_0x9b10bb(0x39a)]/(-0x1aad+0xf4*-0x9+-0x19*-0x16d)+'\u5143'),await _0x3ba1e8['\x77\x61\x69\x74'](-0x316+-0x1788+-0x15*-0x14e),await this[_0x9b10bb(0x3e6)+_0x9b10bb(0x3ce)](_0x53576b[_0x9b10bb(0x32d)+_0x9b10bb(0x39a)]);return;}_0x2f3988[_0x9b10bb(0x3dd)](_0x53576b[_0x9b10bb(0x32d)+_0x9b10bb(0x39a)]/(0x95*-0x41+0x1b11+-0x3*-0x3b8));}_0xebcfd0('\u8d26\u53f7\x5b'+this['\x6e\x61\x6d\x65']+(_0x9b10bb(0x207)+'\uff0c\u53ef\u63d0\u73b0\u989d'+'\u5ea6\uff1a')+_0x2f3988['\x6a\x6f\x69\x6e']('\x2c'));}else{let _0x32a062=-0x76f+-0xc2*-0xa+-0xa3*-0x1;_0x34c74f['\x68\x51\x65\x75\x4c'](_0x2a3b95,_0x32a062)?(_0xebcfd0(_0x9b10bb(0x633)+this[_0x9b10bb(0x42c)]+(_0x9b10bb(0x56b)+_0x9b10bb(0x202)+_0x9b10bb(0x432))+_0x32a062/(-0x37e+-0x2543*0x1+0x2925)+'\u5143'),await _0x3ba1e8[_0x9b10bb(0x1d2)](-0x3b*0x5b+-0x121a+0x27db),await this[_0x9b10bb(0x3e6)+_0x9b10bb(0x3ce)](_0x32a062)):_0x34c74f[_0x9b10bb(0x3b8)](_0xebcfd0,_0x9b10bb(0x633)+this['\x6e\x61\x6d\x65']+(_0x9b10bb(0x56b)+'\u5230\u63d0\u73b0\u5217\u8868'+_0x9b10bb(0x23c))+_0x34c74f[_0x9b10bb(0x6b2)](_0x32a062,0xcf+-0x25b7+0x1c*0x155)+_0x9b10bb(0x3a1));}}else _0x34c74f[_0x9b10bb(0x557)](_0x2a3b95,_0x34c74f['\x72\x4f\x75\x6c\x63'](_0x34c74f[_0x9b10bb(0x3b8)](parseFloat,_0x2eb5c1),0x78b+-0x7*-0x236+0x1*-0x16a1))?(_0x34c74f[_0x9b10bb(0x561)](_0xebcfd0,_0x9b10bb(0x633)+this[_0x9b10bb(0x42c)]+_0x9b10bb(0x2f3)+_0x2eb5c1+'\u5143'),await _0x3ba1e8['\x77\x61\x69\x74'](0xd07+0x1414+-0x2053),await this[_0x9b10bb(0x3e6)+_0x9b10bb(0x3ce)](_0x34c74f['\x72\x4f\x75\x6c\x63'](_0x34c74f[_0x9b10bb(0x4e8)](parseFloat,_0x2eb5c1),0x75f+-0x1875+-0x117a*-0x1))):_0xebcfd0('\u8d26\u53f7\x5b'+this['\x6e\x61\x6d\x65']+_0x9b10bb(0x207)+_0x2eb5c1+'\u5143\uff0c\u4e0d\u63d0\u73b0');}}else console[_0x9b10bb(0x230)](_0x9b10bb(0x633)+this[_0x9b10bb(0x42c)]+(_0x9b10bb(0x345)+_0x9b10bb(0x574))+_0x1cd792[_0x9b10bb(0x421)+_0x9b10bb(0x43c)]);}async[_0x2fc758(0x5ed)+'\x63\x6b\x6e\x61\x6d'+'\x65'](){const _0x41df99=_0x2fc758,_0x13cea6={};_0x13cea6[_0x41df99(0x6c8)]='\x67\x65\x74',_0x13cea6[_0x41df99(0x465)]=function(_0x363720,_0x2c1cd0){return _0x363720==_0x2c1cd0;};const _0x28832a=_0x13cea6;let _0x2cb6c4=_0x41df99(0x599)+_0x41df99(0x228)+_0x41df99(0x25c)+'\x2e\x6b\x75\x61\x69'+_0x41df99(0x67a)+'\x63\x6f\x6d\x2f\x72'+_0x41df99(0x59e)+_0x41df99(0x332)+'\x74\x65\x72\x2f\x71'+_0x41df99(0x52a)+_0x41df99(0x366)+_0x41df99(0x588)+_0x41df99(0x201)+_0x41df99(0x2c4),_0x57f316='',_0x29ca3b=_0x4c62f9(_0x2cb6c4,this[_0x41df99(0x6c1)+'\x65'],_0x57f316);await _0x553fe7(_0x28832a['\x6a\x68\x59\x63\x6e'],_0x29ca3b);let _0x1b315f=_0x1b0221;if(!_0x1b315f)return;_0x28832a['\x65\x4c\x66\x58\x6f'](_0x1b315f['\x72\x65\x73\x75\x6c'+'\x74'],-0x4d*-0x9+0x2145+-0x23f9)?this[_0x41df99(0x42c)]=_0x1b315f[_0x41df99(0x251)][_0x41df99(0x1fa)+_0x41df99(0x5bc)]:console[_0x41df99(0x230)](_0x41df99(0x633)+this[_0x41df99(0x42c)]+('\x5d\u83b7\u53d6\u6635\u79f0'+_0x41df99(0x4ff))+_0x1b315f[_0x41df99(0x421)+_0x41df99(0x43c)]);}async[_0x2fc758(0x26b)+'\x6e\x76\x69\x74\x65'](_0x270c32){const _0x34410b=_0x2fc758,_0x4b9c65={'\x67\x64\x5a\x71\x67':function(_0x37fc77,_0x13c78e,_0x49aace,_0x4d362d){return _0x37fc77(_0x13c78e,_0x49aace,_0x4d362d);},'\x6b\x63\x53\x45\x43':function(_0x583cf0,_0x5170be,_0x17cf79){return _0x583cf0(_0x5170be,_0x17cf79);}};let _0xd0c534=_0x34410b(0x599)+_0x34410b(0x228)+'\x6d\x65\x74\x65\x72'+_0x34410b(0x54f)+_0x34410b(0x67a)+'\x63\x6f\x6d\x2f\x72'+_0x34410b(0x59e)+_0x34410b(0x332)+'\x74\x65\x72\x2f\x69'+_0x34410b(0x337)+_0x34410b(0x538)+'\x6f\x76\x65\x72\x76'+'\x69\x65\x77\x3f\x73'+_0x34410b(0x1cd)+_0x34410b(0x5c7)+'\x64\x65\x26\x72\x65'+_0x34410b(0x46f)+_0x34410b(0x539)+'\x74',_0x1dfe8b='',_0x12f683=_0x4b9c65[_0x34410b(0x515)](_0x4c62f9,_0xd0c534,this[_0x34410b(0x6c1)+'\x65'],_0x1dfe8b);_0x12f683[_0x34410b(0x4a9)+'\x72\x73']['\x52\x65\x66\x65\x72'+'\x65\x72']=_0x34410b(0x599)+_0x34410b(0x228)+'\x6d\x65\x74\x65\x72'+_0x34410b(0x54f)+_0x34410b(0x67a)+_0x34410b(0x30d)+_0x34410b(0x37d)+_0x34410b(0x672)+_0x34410b(0x414)+_0x34410b(0x33f)+'\x3f'+_0x270c32,await _0x4b9c65[_0x34410b(0x1ea)](_0x553fe7,_0x34410b(0x537),_0x12f683);let _0x404bea=_0x1b0221;if(!_0x404bea)return;}async[_0x2fc758(0x6db)+_0x2fc758(0x3b6)](_0x3be810){const _0x28f6ef=_0x2fc758,_0x1c4801={'\x75\x44\x51\x75\x52':function(_0x247b3d,_0x467bab,_0xccf49b,_0x2e820e){return _0x247b3d(_0x467bab,_0xccf49b,_0x2e820e);},'\x74\x46\x6a\x56\x7a':function(_0x266709,_0x5495c8,_0x41949f){return _0x266709(_0x5495c8,_0x41949f);},'\x62\x6c\x57\x63\x57':_0x28f6ef(0x3d9)};let _0x312c3e='\x68\x74\x74\x70\x73'+_0x28f6ef(0x2ff)+_0x28f6ef(0x536)+_0x28f6ef(0x29c)+'\x7a\x74\x2e\x63\x6f'+_0x28f6ef(0x49c)+_0x28f6ef(0x48f)+'\x73\x68\x61\x72\x65'+'\x2f\x73\x68\x6f\x77'+_0x28f6ef(0x2b3),_0x310ee9=_0x28f6ef(0x5a7)+_0x28f6ef(0x5f0)+_0x28f6ef(0x6e0)+_0x28f6ef(0x208)+'\x6f\x6e\x3d\x31\x2e'+'\x31\x34\x2e\x30\x2e'+_0x28f6ef(0x6b5)+_0x28f6ef(0x60c)+_0x28f6ef(0x4ec)+_0x28f6ef(0x612)+_0x28f6ef(0x5fa)+_0x28f6ef(0x3ac)+_0x28f6ef(0x28f)+_0x28f6ef(0x4d4)+_0x28f6ef(0x51c)+'\x32\x46\x6b\x69\x63'+_0x28f6ef(0x596)+_0x28f6ef(0x226)+_0x28f6ef(0x5dd)+_0x28f6ef(0x1f5)+_0x28f6ef(0x5a4)+'\x25\x32\x46\x66\x25'+'\x32\x46\x59\x33\x72'+'\x44\x62\x70\x71\x6f'+_0x28f6ef(0x3e9)+_0x28f6ef(0x4e3)+_0x28f6ef(0x5e6)+'\x6c\x61\x75\x6e\x63'+_0x28f6ef(0x4b9)+_0x28f6ef(0x3b2)+_0x28f6ef(0x5f8)+_0x28f6ef(0x57e)+_0x28f6ef(0x637)+_0x28f6ef(0x25e)+_0x28f6ef(0x623)+_0x28f6ef(0x63c)+_0x28f6ef(0x358)+'\x72\x63\x65\x25\x32'+'\x32\x25\x33\x41\x25'+'\x32\x32\x75\x73\x65'+_0x28f6ef(0x324)+_0x28f6ef(0x294)+_0x28f6ef(0x6ab)+'\x44',_0x4a35d4=_0x1c4801['\x75\x44\x51\x75\x52'](_0x4c62f9,_0x312c3e,this['\x63\x6f\x6f\x6b\x69'+'\x65'],_0x310ee9);await _0x1c4801[_0x28f6ef(0x67d)](_0x553fe7,_0x1c4801[_0x28f6ef(0x21f)],_0x4a35d4);let _0x4cb155=_0x1b0221;if(!_0x4cb155)return;if(_0x4cb155['\x72\x65\x73\x75\x6c'+'\x74']==-0x495+0x357+0x13f)await _0x3ba1e8[_0x28f6ef(0x1d2)](0x11b8+-0x11*0xa7+-0x5d9),await this[_0x28f6ef(0x26b)+_0x28f6ef(0x33f)](_0x3be810);else{}}async[_0x2fc758(0x367)+_0x2fc758(0x450)+'\x61\x6d'](_0x23abaa){const _0xf8b7ab=_0x2fc758,_0x3ba5cf={'\x63\x56\x74\x7a\x5a':function(_0x5412b,_0x5ef62f,_0x4e2e45,_0x48d8e8){return _0x5412b(_0x5ef62f,_0x4e2e45,_0x48d8e8);},'\x64\x43\x65\x78\x5a':function(_0x3da3a0,_0x2aebbd,_0x11c0a9){return _0x3da3a0(_0x2aebbd,_0x11c0a9);},'\x6c\x7a\x64\x6f\x62':_0xf8b7ab(0x3d9),'\x6b\x56\x47\x4e\x64':function(_0x26e768,_0x529d9c){return _0x26e768>_0x529d9c;}};let _0x584ea6=_0xf8b7ab(0x599)+_0xf8b7ab(0x2ff)+_0xf8b7ab(0x45d)+_0xf8b7ab(0x550)+_0xf8b7ab(0x221)+_0xf8b7ab(0x39f)+_0xf8b7ab(0x2a7)+_0xf8b7ab(0x587)+'\x77\x61\x72\x64\x2f'+_0xf8b7ab(0x49e)+'\x66\x3d\x41\x4e\x44'+'\x52\x4f\x49\x44\x5f'+'\x50\x48\x4f\x4e\x45'+_0xf8b7ab(0x29a)+'\x4e\x45\x42\x55\x4c'+'\x41',_0x593994=_0xf8b7ab(0x4ca)+_0xf8b7ab(0x2e2)+_0xf8b7ab(0x20b)+_0xf8b7ab(0x328)+_0xf8b7ab(0x31c)+_0xf8b7ab(0x4b0)+'\x6c\x68\x65\x51\x73'+_0xf8b7ab(0x20f)+_0xf8b7ab(0x415)+_0xf8b7ab(0x211)+_0xf8b7ab(0x385)+_0xf8b7ab(0x3f1)+'\x64\x4a\x59\x25\x32'+'\x42\x33\x69\x56\x35'+_0xf8b7ab(0x388)+_0xf8b7ab(0x393)+_0xf8b7ab(0x520)+_0xf8b7ab(0x579)+_0xf8b7ab(0x1e4)+'\x4d\x7a\x53\x72\x35'+_0xf8b7ab(0x482)+_0xf8b7ab(0x3e0)+_0xf8b7ab(0x56c)+_0xf8b7ab(0x4e7)+_0xf8b7ab(0x301)+'\x57\x61\x6f\x47\x58'+_0xf8b7ab(0x34a)+_0xf8b7ab(0x560)+_0xf8b7ab(0x5b9)+_0xf8b7ab(0x635)+_0xf8b7ab(0x4aa)+_0xf8b7ab(0x36e)+_0xf8b7ab(0x5e0)+_0xf8b7ab(0x554)+_0xf8b7ab(0x312)+_0xf8b7ab(0x253)+'\x41\x31\x62\x5a\x4f'+'\x6c\x54\x4b\x68\x6d'+'\x6f\x41\x6f\x6b\x66'+'\x70\x57\x70\x49\x46'+_0xf8b7ab(0x586)+_0xf8b7ab(0x5d4)+_0xf8b7ab(0x206)+_0xf8b7ab(0x595)+_0xf8b7ab(0x4d1)+'\x68\x4f\x6d\x48\x41'+_0xf8b7ab(0x42b)+_0xf8b7ab(0x602)+'\x31\x4c\x77\x6b\x30'+'\x65\x51\x38\x71\x5a'+_0xf8b7ab(0x445)+_0xf8b7ab(0x583)+_0xf8b7ab(0x26c)+'\x7a\x57\x6b\x74\x79'+_0xf8b7ab(0x573)+'\x57\x44\x25\x32\x42'+'\x53\x34\x52\x33\x7a'+'\x54\x35\x50\x65\x6b'+'\x48\x6b\x37\x69\x77'+_0xf8b7ab(0x650)+_0xf8b7ab(0x36c)+'\x38\x4f\x30\x46\x61'+'\x47\x41\x25\x32\x42'+_0xf8b7ab(0x3a6)+_0xf8b7ab(0x531)+_0xf8b7ab(0x69c)+'\x55\x38\x4b\x4a\x78'+'\x37\x4d\x42\x59\x59'+_0xf8b7ab(0x3ad)+_0xf8b7ab(0x315)+_0xf8b7ab(0x5e5)+'\x44\x55\x70\x43\x6b'+'\x62\x30\x48\x6d\x57'+'\x42\x35\x37\x67\x66'+'\x76\x36\x32\x67\x71'+'\x77\x59\x36\x44\x6c'+'\x65\x76\x79\x33\x54'+_0xf8b7ab(0x2ab)+'\x73\x4c\x62\x47\x67'+_0xf8b7ab(0x699)+_0xf8b7ab(0x329)+_0xf8b7ab(0x58d)+_0xf8b7ab(0x2b6)+_0xf8b7ab(0x3a8)+_0xf8b7ab(0x5d2)+_0xf8b7ab(0x347)+_0xf8b7ab(0x65c)+_0xf8b7ab(0x5b6)+_0xf8b7ab(0x455)+_0xf8b7ab(0x54a)+_0xf8b7ab(0x267)+_0xf8b7ab(0x5bf)+_0xf8b7ab(0x6e9)+'\x59\x79\x52\x67\x7a'+_0xf8b7ab(0x52b)+_0xf8b7ab(0x27e)+_0xf8b7ab(0x1e8)+_0xf8b7ab(0x505)+'\x47\x56\x51\x53\x78'+_0xf8b7ab(0x62f)+_0xf8b7ab(0x2a6)+_0xf8b7ab(0x591)+_0xf8b7ab(0x511)+_0xf8b7ab(0x3ee)+'\x61\x25\x32\x46\x34'+_0xf8b7ab(0x2b8)+_0xf8b7ab(0x1e9)+'\x34\x51\x31\x58\x6f'+_0xf8b7ab(0x2c5)+'\x50\x69\x55\x74\x34'+_0xf8b7ab(0x2af)+_0xf8b7ab(0x2f5)+_0xf8b7ab(0x47f)+_0xf8b7ab(0x4ab)+_0xf8b7ab(0x4bc)+_0xf8b7ab(0x39e)+_0xf8b7ab(0x698)+'\x31\x54\x36\x6a\x56'+_0xf8b7ab(0x657)+_0xf8b7ab(0x296)+_0xf8b7ab(0x604)+'\x6d\x62\x66\x62\x32'+_0xf8b7ab(0x3bb)+_0xf8b7ab(0x3b9)+_0xf8b7ab(0x5ad)+_0xf8b7ab(0x32f)+_0xf8b7ab(0x49b)+_0xf8b7ab(0x5d7)+_0xf8b7ab(0x33c)+_0xf8b7ab(0x1ee)+_0xf8b7ab(0x24b)+_0xf8b7ab(0x447)+_0xf8b7ab(0x54e)+_0xf8b7ab(0x22a)+'\x73\x63\x59\x53\x31'+'\x42\x25\x32\x46\x46'+'\x4f\x55\x4b\x53\x25'+_0xf8b7ab(0x2e5)+_0xf8b7ab(0x2fa)+_0xf8b7ab(0x575)+'\x48\x4e\x57\x43\x59'+_0xf8b7ab(0x4ef)+_0xf8b7ab(0x58c)+'\x70\x4f\x69\x75\x78'+_0xf8b7ab(0x335)+_0xf8b7ab(0x3aa)+_0xf8b7ab(0x69d)+_0xf8b7ab(0x4b7)+_0xf8b7ab(0x2f7)+'\x32\x46\x68\x65\x31'+_0xf8b7ab(0x2a1)+_0xf8b7ab(0x25f)+_0xf8b7ab(0x5b2)+_0xf8b7ab(0x476)+_0xf8b7ab(0x422)+'\x75\x53\x6b\x4d\x34'+_0xf8b7ab(0x3e7)+_0xf8b7ab(0x1fc)+'\x42\x76\x25\x32\x46'+_0xf8b7ab(0x349)+_0xf8b7ab(0x2e8)+_0xf8b7ab(0x2e3)+_0xf8b7ab(0x22c)+'\x53\x76\x71\x33\x6f'+_0xf8b7ab(0x27d)+'\x59\x4b\x48\x71\x36'+_0xf8b7ab(0x245)+_0xf8b7ab(0x6a1)+'\x42\x46\x41\x55\x54'+_0xf8b7ab(0x61c)+_0xf8b7ab(0x28c)+_0xf8b7ab(0x399)+_0xf8b7ab(0x395)+_0xf8b7ab(0x3f0)+'\x65\x6b\x72\x66\x68'+_0xf8b7ab(0x407)+'\x78\x4e\x32\x73\x5a'+_0xf8b7ab(0x5f1)+_0xf8b7ab(0x3e2)+_0xf8b7ab(0x6cf)+_0xf8b7ab(0x5d5)+_0xf8b7ab(0x2aa)+'\x6c\x42\x58\x79\x43'+_0xf8b7ab(0x227)+_0xf8b7ab(0x6ea)+'\x39\x51\x74\x42\x39'+_0xf8b7ab(0x1db)+_0xf8b7ab(0x1f4)+_0xf8b7ab(0x4cb)+_0xf8b7ab(0x507)+'\x34\x25\x32\x42\x50'+_0xf8b7ab(0x581)+_0xf8b7ab(0x2b1)+_0xf8b7ab(0x34d)+_0xf8b7ab(0x6e2)+_0xf8b7ab(0x249)+_0xf8b7ab(0x495)+_0xf8b7ab(0x52f)+_0xf8b7ab(0x4f5)+_0xf8b7ab(0x2e6)+(_0xf8b7ab(0x463)+_0xf8b7ab(0x670)+_0xf8b7ab(0x61b)+_0xf8b7ab(0x222)+_0xf8b7ab(0x4e1)+_0xf8b7ab(0x2a8)+_0xf8b7ab(0x299)+_0xf8b7ab(0x20a)+_0xf8b7ab(0x1ef)+_0xf8b7ab(0x4ce)+_0xf8b7ab(0x52c)+'\x30\x32\x62\x33\x65'),_0x29c00e=_0x3ba5cf['\x63\x56\x74\x7a\x5a'](_0x4c62f9,_0x584ea6,this[_0xf8b7ab(0x6c1)+'\x65'],_0x593994);await _0x3ba5cf[_0xf8b7ab(0x5aa)](_0x553fe7,_0x3ba5cf['\x6c\x7a\x64\x6f\x62'],_0x29c00e);let _0x1db843=_0x1b0221;if(!_0x1db843)return;_0x1db843[_0xf8b7ab(0x46d)+'\x74']==-0x1105*-0x1+0x232*0xb+-0x1495*0x2?_0x1db843[_0xf8b7ab(0x305)+_0xf8b7ab(0x234)]&&_0x3ba5cf['\x6b\x56\x47\x4e\x64'](_0x1db843[_0xf8b7ab(0x305)+'\x49\x6e\x66\x6f'][_0xf8b7ab(0x2bd)+'\x68'],0x1345+0x3b*0x79+0x18*-0x1f7)&&_0x1db843[_0xf8b7ab(0x305)+_0xf8b7ab(0x234)][-0xedb*0x1+-0x1*-0x205b+0x23*-0x80]['\x61\x64\x49\x6e\x66'+'\x6f']&&_0x3ba5cf['\x6b\x56\x47\x4e\x64'](_0x1db843['\x69\x6d\x70\x41\x64'+'\x49\x6e\x66\x6f'][-0x12*-0xca+0x1*0x4eb+-0x59*0x37]['\x61\x64\x49\x6e\x66'+'\x6f'][_0xf8b7ab(0x2bd)+'\x68'],-0x1879+-0x2060*-0x1+-0x7e7)&&_0x1db843[_0xf8b7ab(0x305)+'\x49\x6e\x66\x6f'][0x8fd*-0x1+0xf1*-0x1a+0x2177][_0xf8b7ab(0x449)+'\x6f'][0x13fa+0xd43*-0x2+0x68c]['\x61\x64\x42\x61\x73'+_0xf8b7ab(0x5eb)]&&(await _0x3ba1e8['\x77\x61\x69\x74'](-0x3cb*-0x3+0x11f6*0x1+-0x1c8f),await this[_0xf8b7ab(0x367)+'\x41\x64\x52\x65\x77'+_0xf8b7ab(0x578)](_0x1db843[_0xf8b7ab(0x543)],_0x1db843[_0xf8b7ab(0x305)+_0xf8b7ab(0x234)][0x2412+-0x28a+-0x2188][_0xf8b7ab(0x449)+'\x6f'][0x5a8+-0x1c43+0x3*0x789][_0xf8b7ab(0x37c)+_0xf8b7ab(0x5eb)][_0xf8b7ab(0x4b8)+_0xf8b7ab(0x353)],_0x23abaa)):console['\x6c\x6f\x67']('\u8d26\u53f7\x5b'+this[_0xf8b7ab(0x42c)]+_0xf8b7ab(0x28b)+_0x23abaa[_0xf8b7ab(0x42c)]+_0xf8b7ab(0x6e3)+_0x1db843['\x65\x72\x72\x6f\x72'+_0xf8b7ab(0x43c)]);}async[_0x2fc758(0x367)+_0x2fc758(0x562)+_0x2fc758(0x578)](_0x121fac,_0x286a35,_0x294913){const _0xee5cbc=_0x2fc758,_0x1f4c6e={'\x49\x6c\x70\x78\x47':function(_0x43426b,_0x22307e){return _0x43426b+_0x22307e;},'\x6a\x43\x56\x4a\x51':function(_0x3afc33,_0x2ae387){return _0x3afc33-_0x2ae387;},'\x71\x58\x63\x72\x56':function(_0xd3e41f,_0x13abf3,_0x2fec80,_0x35b7dd){return _0xd3e41f(_0x13abf3,_0x2fec80,_0x35b7dd);},'\x71\x79\x6c\x4c\x48':function(_0x535b0a,_0x5c1bdc,_0x395c69){return _0x535b0a(_0x5c1bdc,_0x395c69);},'\x65\x43\x48\x4f\x65':'\x70\x6f\x73\x74','\x54\x5a\x45\x70\x51':function(_0x276d08,_0x4025f5){return _0x276d08==_0x4025f5;}};let _0x5e4396=new Date()[_0xee5cbc(0x624)+'\x6d\x65'](),_0x2cd56e=_0x1f4c6e[_0xee5cbc(0x2de)](Math[_0xee5cbc(0x35b)](Math['\x72\x61\x6e\x64\x6f'+'\x6d']()*(-0xa436+-0x67e0+0x18146)),0x15d63+-0x1541e+0xa683),_0x497012=_0x1f4c6e[_0xee5cbc(0x4c0)](_0x5e4396,_0x2cd56e),_0x298cd1=_0xee5cbc(0x599)+_0xee5cbc(0x2ff)+'\x69\x32\x2e\x65\x2e'+'\x6b\x75\x61\x69\x73'+_0xee5cbc(0x221)+_0xee5cbc(0x39f)+_0xee5cbc(0x64f)+_0xee5cbc(0x283)+'\x73\x6b\x2f\x72\x65'+_0xee5cbc(0x49d),_0x8a52a6=_0xee5cbc(0x1fb)+_0xee5cbc(0x262)+_0xee5cbc(0x6af)+_0xee5cbc(0x3f6)+'\x3a'+_0x294913[_0xee5cbc(0x374)+_0xee5cbc(0x480)]+(_0xee5cbc(0x6ce)+'\x54\x69\x6d\x65\x22'+'\x3a')+_0x5e4396+(_0xee5cbc(0x4f2)+_0xee5cbc(0x5b5)+'\x73\x22\x3a\x22')+_0x294913[_0xee5cbc(0x38b)+'\x72\x61\x6d\x73']+('\x22\x2c\x22\x6d\x65'+_0xee5cbc(0x493)+_0xee5cbc(0x48d)+_0xee5cbc(0x405)+_0xee5cbc(0x1c9)+_0xee5cbc(0x35e)+_0xee5cbc(0x30b)+'\x7b\x22\x63\x72\x65'+_0xee5cbc(0x6d9)+'\x49\x64\x22\x3a')+_0x286a35+(_0xee5cbc(0x4f2)+_0xee5cbc(0x500)+'\x3a\x22\x22\x2c\x22'+'\x6c\x6c\x73\x69\x64'+'\x22\x3a')+_0x121fac+('\x2c\x22\x74\x61\x73'+_0xee5cbc(0x23b)+_0xee5cbc(0x320)+_0xee5cbc(0x485)+_0xee5cbc(0x394))+_0x294913['\x70\x61\x67\x65\x49'+'\x64']+(_0xee5cbc(0x5cf)+_0xee5cbc(0x408))+_0x294913['\x70\x6f\x73\x49\x64']+(_0xee5cbc(0x33b)+_0xee5cbc(0x461)+_0xee5cbc(0x540))+_0x497012+(_0xee5cbc(0x499)+'\x50\x61\x67\x65\x49'+_0xee5cbc(0x392))+_0x294913['\x73\x75\x62\x50\x61'+_0xee5cbc(0x52e)]+'\x7d',_0x337e87=_0x1f4c6e[_0xee5cbc(0x384)](_0x4c62f9,_0x298cd1,this[_0xee5cbc(0x6c1)+'\x65'],_0x8a52a6);await _0x1f4c6e['\x71\x79\x6c\x4c\x48'](_0x553fe7,_0x1f4c6e['\x65\x43\x48\x4f\x65'],_0x337e87);let _0x538f82=_0x1b0221;if(!_0x538f82)return;_0x1f4c6e[_0xee5cbc(0x3ec)](_0x538f82[_0xee5cbc(0x46d)+'\x74'],-0xe94+0xdcb+-0x2*-0x65)?console[_0xee5cbc(0x230)]('\u8d26\u53f7\x5b'+this[_0xee5cbc(0x42c)]+'\x5d\u770b'+_0x294913[_0xee5cbc(0x42c)]+'\u83b7\u5f97'+_0x538f82[_0xee5cbc(0x251)][_0xee5cbc(0x6a3)+_0xee5cbc(0x51f)]+'\u91d1\u5e01'):console[_0xee5cbc(0x230)](_0xee5cbc(0x633)+this[_0xee5cbc(0x42c)]+'\x5d\u770b'+_0x294913[_0xee5cbc(0x42c)]+_0xee5cbc(0x4ff)+_0x538f82[_0xee5cbc(0x421)+_0xee5cbc(0x43c)]);}async[_0x2fc758(0x626)+_0x2fc758(0x4d5)+_0x2fc758(0x471)+'\x66\x6f'](){const _0x470622=_0x2fc758,_0x1801d5={'\x66\x51\x4a\x53\x72':function(_0x47b590,_0x2a9385,_0x4b98c6,_0x8dd924){return _0x47b590(_0x2a9385,_0x4b98c6,_0x8dd924);},'\x55\x50\x57\x6d\x6e':function(_0x268846,_0x1274a2,_0x2113be){return _0x268846(_0x1274a2,_0x2113be);},'\x56\x7a\x52\x58\x65':function(_0x39fcf2,_0x92bb21){return _0x39fcf2*_0x92bb21;},'\x4a\x7a\x53\x44\x42':function(_0x4e0634,_0x5a65bf){return _0x4e0634*_0x5a65bf;},'\x4f\x64\x51\x65\x48':function(_0x50645b,_0x3f4b47){return _0x50645b+_0x3f4b47;},'\x4a\x54\x71\x50\x77':function(_0x473193,_0xafc84a){return _0x473193<_0xafc84a;},'\x48\x57\x59\x4d\x48':function(_0x22a9d2,_0x4e47f8){return _0x22a9d2/_0x4e47f8;}};let _0x467de1=_0x470622(0x599)+'\x3a\x2f\x2f\x61\x63'+_0x470622(0x4ae)+_0x470622(0x6b7)+_0x470622(0x2a0)+_0x470622(0x4b6)+'\x6d\x2f\x72\x65\x73'+_0x470622(0x615)+_0x470622(0x662)+_0x470622(0x435)+_0x470622(0x527)+_0x470622(0x4c8)+'\x6f',_0x3ebf1c='',_0x114dba=_0x1801d5[_0x470622(0x65e)](_0x4c62f9,_0x467de1,this[_0x470622(0x6c1)+'\x65'],_0x3ebf1c);await _0x1801d5[_0x470622(0x2dd)](_0x553fe7,_0x470622(0x537),_0x114dba);let _0x2dfc75=_0x1b0221;if(!_0x2dfc75)return;if(_0x2dfc75[_0x470622(0x46d)+'\x74']==-0x62+-0x22a6+-0x1*-0x2309){if(_0x2dfc75[_0x470622(0x251)]){let _0x2cc25e=new Date()[_0x470622(0x624)+'\x6d\x65'](),_0x13649c=_0x2dfc75[_0x470622(0x251)]['\x6c\x61\x73\x74\x54'+_0x470622(0x5e1)+_0x470622(0x363)],_0x27b41a=_0x1801d5[_0x470622(0x348)](_0x1801d5[_0x470622(0x23a)](_0x2dfc75[_0x470622(0x251)][_0x470622(0x644)+_0x470622(0x34e)+_0x470622(0x284)],0x213*0x11+-0xe8a*0x1+0x5*-0x419),-0x67*0x48+-0x1935+0x1*0x3a15),_0x4a98d8=_0x1801d5['\x4f\x64\x51\x65\x48'](_0x13649c,_0x27b41a);_0x1801d5[_0x470622(0x419)](_0x2cc25e,_0x4a98d8)?console[_0x470622(0x230)](_0x470622(0x633)+this['\x6e\x61\x6d\x65']+(_0x470622(0x318)+_0x470622(0x30c)+'\u8fd8\u6709')+_0x1801d5[_0x470622(0x5cc)](_0x4a98d8-_0x2cc25e,0x1336+0xf43+-0x1*0x1e91)+'\u79d2'):(await _0x3ba1e8['\x77\x61\x69\x74'](-0x244b+-0xbc0*-0x2+0xd93),await this[_0x470622(0x626)+'\x72\x61\x77\x54\x69'+'\x6d\x65\x72\x52\x65'+_0x470622(0x3b5)](_0x2dfc75['\x64\x61\x74\x61'][_0x470622(0x5bd)+'\x75\x6d']));}else console[_0x470622(0x230)](_0x470622(0x633)+this[_0x470622(0x42c)]+(_0x470622(0x4e2)+_0x470622(0x343)+'\u5df2\u7528\u5b8c'));}else console[_0x470622(0x230)](_0x470622(0x633)+this[_0x470622(0x42c)]+(_0x470622(0x30f)+_0x470622(0x300)+_0x470622(0x27c))+_0x2dfc75[_0x470622(0x421)+_0x470622(0x43c)]);}async[_0x2fc758(0x626)+_0x2fc758(0x4d5)+_0x2fc758(0x66d)+'\x77\x61\x72\x64'](_0x4ed6b2){const _0x21b82c=_0x2fc758,_0x2f7551={'\x6e\x61\x73\x55\x6b':function(_0x44c662,_0x48ec58,_0x4783c7,_0x48abd7){return _0x44c662(_0x48ec58,_0x4783c7,_0x48abd7);},'\x51\x67\x58\x75\x4d':function(_0x82d346,_0x1f042d,_0x4cb05c){return _0x82d346(_0x1f042d,_0x4cb05c);}};let _0x48aa24=_0x21b82c(0x599)+_0x21b82c(0x26e)+_0x21b82c(0x4ae)+'\x79\x2e\x65\x2e\x6b'+_0x21b82c(0x2a0)+_0x21b82c(0x4b6)+_0x21b82c(0x49c)+'\x74\x2f\x72\x2f\x67'+'\x61\x6d\x65\x2f\x74'+_0x21b82c(0x435)+_0x21b82c(0x527)+'\x64',_0x34342f='',_0x55b79e=_0x2f7551['\x6e\x61\x73\x55\x6b'](_0x4c62f9,_0x48aa24,this[_0x21b82c(0x6c1)+'\x65'],_0x34342f);await _0x2f7551['\x51\x67\x58\x75\x4d'](_0x553fe7,_0x21b82c(0x3d9),_0x55b79e);let _0x29e91e=_0x1b0221;if(!_0x29e91e)return;_0x29e91e['\x72\x65\x73\x75\x6c'+'\x74']==0x2b*0x53+0x1617+-0x1*0x2407?console['\x6c\x6f\x67'](_0x21b82c(0x633)+this[_0x21b82c(0x42c)]+(_0x21b82c(0x532)+_0x21b82c(0x300)+'\u83b7\u5f97')+_0x4ed6b2+'\u91d1\u5e01'):console[_0x21b82c(0x230)](_0x21b82c(0x633)+this[_0x21b82c(0x42c)]+(_0x21b82c(0x532)+_0x21b82c(0x300)+'\u5931\u8d25\uff1a')+_0x29e91e[_0x21b82c(0x421)+'\x5f\x6d\x73\x67']);}}!(async()=>{const _0x46ed55=_0x2fc758,_0x3ae55a={'\x73\x51\x51\x6c\x7a':'\x75\x6e\x64\x65\x66'+'\x69\x6e\x65\x64','\x49\x42\x70\x6a\x72':function(_0x3f13f3){return _0x3f13f3();},'\x6b\x50\x59\x57\x52':function(_0x27c6ea,_0x5db434){return _0x27c6ea==_0x5db434;},'\x45\x66\x44\x77\x6e':function(_0x5884e2){return _0x5884e2();},'\x48\x47\x64\x6f\x58':_0x46ed55(0x3e1)+_0x46ed55(0x3e1)+_0x46ed55(0x3e1)+'\x3d\x3d\x3d\x3d\x3d'+_0x46ed55(0x3e1)+_0x46ed55(0x351),'\x65\x44\x4e\x50\x51':function(_0x55d1e3,_0xb00c37){return _0x55d1e3<_0xb00c37;},'\x58\x53\x4b\x71\x6e':function(_0x208ce4,_0x403750){return _0x208ce4==_0x403750;},'\x42\x43\x6f\x78\x6d':function(_0x4bfb0a){return _0x4bfb0a();},'\x48\x69\x56\x63\x65':function(_0x5f401,_0x394b56){return _0x5f401==_0x394b56;},'\x53\x42\x6b\x50\x64':function(_0x4e6b58){return _0x4e6b58();},'\x59\x56\x4a\x74\x69':function(_0x1406c1,_0x4f3e07){return _0x1406c1>_0x4f3e07;}};if(typeof $request!==_0x3ae55a[_0x46ed55(0x607)])await _0x3ae55a[_0x46ed55(0x690)](_0x55fd23);else{await _0x3ae55a[_0x46ed55(0x2d9)](_0x21d45f);if(!await _0x3ae55a[_0x46ed55(0x2d9)](_0x5c8b6b))return;console[_0x46ed55(0x230)](_0x3ae55a[_0x46ed55(0x314)]),console[_0x46ed55(0x230)](_0x46ed55(0x5c0)+_0x46ed55(0x3e1)+_0x46ed55(0x3e1)+_0x46ed55(0x4fd)+'\x3d\x3d\x3d\x3d\x3d'+_0x46ed55(0x3e1)+_0x46ed55(0x351));for(let _0x103727 of _0x5b586){await _0x103727['\x67\x65\x74\x4e\x69'+'\x63\x6b\x6e\x61\x6d'+'\x65'](),await _0x3ba1e8['\x77\x61\x69\x74'](-0x359*0x5+-0x26da+-0x1*-0x385f),await _0x103727[_0x46ed55(0x1f0)+_0x46ed55(0x466)+'\x6f'](![]),await _0x3ba1e8[_0x46ed55(0x1d2)](-0xfd8+0x1671+-0x1*0x5d1);}let _0x375d1f=_0x5b586['\x66\x69\x6c\x74\x65'+'\x72'](_0x1d4ef8=>_0x1d4ef8[_0x46ed55(0x3cb)]==!![]);if(_0x3ae55a['\x6b\x50\x59\x57\x52'](_0x375d1f[_0x46ed55(0x2bd)+'\x68'],0x183d+-0x31d*-0x1+-0x185*0x12))return;for(let _0xb1ffbd of _0x375d1f){console['\x6c\x6f\x67'](_0x46ed55(0x5c0)+_0x46ed55(0x3e1)+_0x46ed55(0x220)+'\x5b'+_0xb1ffbd[_0x46ed55(0x42c)]+(_0x46ed55(0x398)+_0x46ed55(0x3e1)+_0x46ed55(0x351))),await _0xb1ffbd[_0x46ed55(0x39d)+_0x46ed55(0x5bb)+'\x6f'](),await _0x3ba1e8[_0x46ed55(0x1d2)](0x301*-0x5+0x56c*0x1+0xa61),await _0xb1ffbd[_0x46ed55(0x619)+'\x69\x73\x74'](),await _0x3ba1e8[_0x46ed55(0x1d2)](0x2456+-0x2596+-0x68*-0x5),await _0xb1ffbd[_0x46ed55(0x5d8)+_0x46ed55(0x5ab)+_0x46ed55(0x31e)](),await _0x3ba1e8['\x77\x61\x69\x74'](-0x17f7+-0x9ff+0x22be);if(_0xb1ffbd['\x74\x61\x73\x6b'][_0x425116[_0x46ed55(0x354)]]['\x6e\x65\x65\x64\x52'+'\x75\x6e']){await _0xb1ffbd['\x74\x61\x73\x6b\x54'+'\x61\x6b\x65'](_0x425116[_0x46ed55(0x354)]),await _0x3ba1e8[_0x46ed55(0x1d2)](-0x16bc+-0x2*0x538+-0x6a*-0x52);for(let _0x917c2b=-0x1*-0x975+-0x10f1+0x1df*0x4;_0x3ae55a['\x65\x44\x4e\x50\x51'](_0x917c2b,_0xb1ffbd['\x74\x61\x73\x6b'][_0x425116[_0x46ed55(0x354)]]['\x6e\x75\x6d']);_0x917c2b++){await _0xb1ffbd['\x64\x6f\x53\x69\x67'+'\x6e'](-0x52c+0x83*0x2e+-0x1258),await _0x3ba1e8[_0x46ed55(0x1d2)](-0x8fc+-0xc5*-0xd+-0x1*0x3d);}}if(_0xb1ffbd[_0x46ed55(0x43d)][_0x425116['\x67\x6a']]['\x6e\x65\x65\x64\x52'+'\x75\x6e']){await _0xb1ffbd[_0x46ed55(0x309)+_0x46ed55(0x5da)](_0x425116['\x67\x6a']),await _0x3ba1e8[_0x46ed55(0x1d2)](-0x16ad+-0x24e5+0x3c5a);for(let _0x50d87c=-0xe3e*-0x2+0x2bd*0x6+0x1*-0x2cea;_0x50d87c<_0xb1ffbd[_0x46ed55(0x43d)][_0x425116['\x67\x6a']][_0x46ed55(0x1c6)];_0x50d87c++){await _0xb1ffbd['\x6b\x73\x67\x6a'](_0x425116['\x67\x6a']),await _0x3ba1e8[_0x46ed55(0x1d2)](-0x18d9*-0x1+0x3*0x47f+0x5ef*-0x6);}}if(_0xb1ffbd[_0x46ed55(0x43d)][_0x425116['\x61\x64']][_0x46ed55(0x434)+'\x75\x6e']){await _0xb1ffbd[_0x46ed55(0x309)+_0x46ed55(0x5da)](_0x425116['\x61\x64']),await _0x3ba1e8[_0x46ed55(0x1d2)](-0x1552+0x1*0xdb2+-0x10d*-0x8);for(let _0x2a4050=-0x2*0xd78+0xdf*-0x3+0x1d8d;_0x3ae55a[_0x46ed55(0x44a)](_0x2a4050,_0xb1ffbd[_0x46ed55(0x43d)][_0x425116['\x61\x64']][_0x46ed55(0x1c6)]);_0x2a4050++){await _0xb1ffbd[_0x46ed55(0x236)+_0x46ed55(0x369)](_0x54479e['\x61\x64']),await _0x3ba1e8['\x77\x61\x69\x74'](-0xb03+-0x5*-0x13c+0x793);}}if(_0xb1ffbd[_0x46ed55(0x43d)][_0x425116[_0x46ed55(0x364)]][_0x46ed55(0x434)+'\x75\x6e']){await _0xb1ffbd[_0x46ed55(0x309)+_0x46ed55(0x5da)](_0x425116[_0x46ed55(0x364)]),await _0x3ba1e8[_0x46ed55(0x1d2)](0x6*0x42+0x4*-0x887+0x2158);for(let _0x3bf2a0=0x2576+-0x417*0x3+-0x1*0x1931;_0x3ae55a[_0x46ed55(0x44a)](_0x3bf2a0,_0xb1ffbd[_0x46ed55(0x43d)][_0x425116[_0x46ed55(0x364)]][_0x46ed55(0x1c6)]);_0x3bf2a0++){await _0xb1ffbd[_0x46ed55(0x236)+_0x46ed55(0x369)](_0x54479e[_0x46ed55(0x364)]),await _0x3ba1e8[_0x46ed55(0x1d2)](0x4b6+0x260b+-0x2805);}}}console[_0x46ed55(0x230)](_0x46ed55(0x5c0)+'\x3d\x3d\x3d\x3d\x3d'+'\x3d\x3d\x3d\x3d\x3d'+_0x46ed55(0x65d)+_0x46ed55(0x5d6)+_0x46ed55(0x3e1)+_0x46ed55(0x3e1));for(let _0x2ab381 of _0x375d1f){await _0x2ab381[_0x46ed55(0x1f0)+_0x46ed55(0x466)+'\x6f'](!![]),await _0x3ba1e8[_0x46ed55(0x1d2)](-0xe9f+0xa*-0x3c3+-0x793*-0x7),await _0x2ab381['\x62\x69\x6e\x64\x49'+_0x46ed55(0x510)](),await _0x3ba1e8[_0x46ed55(0x1d2)](-0xb*-0x2f5+0x559+-0x2518);}console[_0x46ed55(0x230)](_0x46ed55(0x5c0)+_0x46ed55(0x3e1)+_0x46ed55(0x3e1)+_0x46ed55(0x32a)+_0x46ed55(0x5d6)+'\x3d\x3d\x3d\x3d\x3d'+_0x46ed55(0x3e1));let _0x505e9a='\u6309\u63d0\u73b0\u5217\u8868'+'\u81ea\u52a8\u63d0\u73b0';if(_0x2eb5c1)_0x505e9a=_0x46ed55(0x21e)+_0x2eb5c1+'\u5143';if(_0xc17e17)_0x505e9a=_0x46ed55(0x53e);if(_0x3ae55a['\x58\x53\x4b\x71\x6e'](_0x14d857,_0xa3917b)){console[_0x46ed55(0x230)](_0x46ed55(0x61f)+_0x46ed55(0x6c3)+_0x505e9a);for(let _0x5ec347 of _0x375d1f){await _0x5ec347[_0x46ed55(0x3e6)+_0x46ed55(0x2c2)+'\x65\x72\x76\x69\x65'+'\x77'](),await _0x3ba1e8[_0x46ed55(0x1d2)](0xa3d*-0x2+-0x21a0+-0x57d*-0xa);}}else console['\x6c\x6f\x67'](_0x46ed55(0x5d0)+_0x46ed55(0x1ed)+'\u4e3a'+_0xa3917b+'\u70b9'+_0x505e9a);if(_0x3ae55a['\x6b\x50\x59\x57\x52'](_0xe984ce,0x2570+0xc9a*-0x1+0x635*-0x4))await _0x3ae55a[_0x46ed55(0x1c4)](_0xf3b68c);else{if(_0x3ae55a[_0x46ed55(0x46a)](_0xe984ce,0x244+-0x1659+0x1416)){if(_0x3ae55a['\x48\x69\x56\x63\x65'](_0x14d857,_0xa3917b))await _0x3ae55a['\x53\x42\x6b\x50\x64'](_0xf3b68c);}}if(_0x3ae55a[_0x46ed55(0x1da)](_0x2c2403[_0x46ed55(0x2bd)+'\x68'],-0x256b+0xb8d*0x1+0x19de))for(let _0x74f77b of _0x375d1f){for(let _0x5b5b60 of _0x2c2403){await _0x74f77b[_0x46ed55(0x6db)+_0x46ed55(0x3b6)](_0x5b5b60),await _0x3ba1e8['\x77\x61\x69\x74'](-0x233+-0x2020+-0x331*-0xb);}}}})()[_0x2fc758(0x4a3)](_0x40b2f6=>_0x3ba1e8[_0x2fc758(0x608)+'\x72'](_0x40b2f6))[_0x2fc758(0x4d6)+'\x6c\x79'](()=>_0x3ba1e8[_0x2fc758(0x1ff)]());async function _0x55fd23(){const _0x54cf3f=_0x2fc758,_0x3625e1={};_0x3625e1[_0x54cf3f(0x4cd)]=function(_0x505c7e,_0x1e7b8d){return _0x505c7e>_0x1e7b8d;},_0x3625e1['\x74\x4b\x6d\x67\x6e']=function(_0x3ef5a2,_0x56a8f1){return _0x3ef5a2+_0x56a8f1;},_0x3625e1[_0x54cf3f(0x372)]=function(_0x37e91c,_0x3c06e0){return _0x37e91c+_0x3c06e0;},_0x3625e1[_0x54cf3f(0x23f)]=function(_0x67611d,_0x3f062e){return _0x67611d==_0x3f062e;},_0x3625e1[_0x54cf3f(0x45b)]=function(_0x4ebc3f,_0x314ec5){return _0x4ebc3f+_0x314ec5;},_0x3625e1['\x44\x41\x76\x6c\x44']=_0x54cf3f(0x5ec)+_0x54cf3f(0x3d8),_0x3625e1[_0x54cf3f(0x250)]=function(_0x289a83,_0xce4b21){return _0x289a83+_0xce4b21;},_0x3625e1['\x54\x56\x48\x53\x58']=function(_0x43718b,_0x4642f6){return _0x43718b>_0x4642f6;},_0x3625e1['\x42\x4e\x62\x6f\x67']=function(_0x200dfa,_0x573ac6){return _0x200dfa==_0x573ac6;},_0x3625e1[_0x54cf3f(0x659)]=function(_0x43bdca,_0x1830fc){return _0x43bdca+_0x1830fc;},_0x3625e1[_0x54cf3f(0x56f)]=function(_0x1d4f13,_0x3119f3){return _0x1d4f13+_0x3119f3;};const _0xd5878a=_0x3625e1;if(_0xd5878a[_0x54cf3f(0x4cd)]($request[_0x54cf3f(0x1eb)][_0x54cf3f(0x47c)+'\x4f\x66'](_0x54cf3f(0x6da)+_0x54cf3f(0x3f5)+_0x54cf3f(0x2ea)+_0x54cf3f(0x3e5)+_0x54cf3f(0x69f)),-(-0x1a56*0x1+0x1*0x1c83+-0x22c))){let _0x453f1a=_0xd5878a[_0x54cf3f(0x355)]($request['\x68\x65\x61\x64\x65'+'\x72\x73'][_0x54cf3f(0x3ab)+'\x65'][_0x54cf3f(0x1dc)](/(kuaishou.api_st=[\w\-]+)/)[-0x21da+-0x17*0x12a+0xbb*0x53],'\x3b'),_0x5eb6b0=$request['\x68\x65\x61\x64\x65'+'\x72\x73'][_0x54cf3f(0x3ab)+'\x65'][_0x54cf3f(0x1dc)](/[ ;](did=[\w\-]+)/)[0x36e*-0x2+-0x45a+0xb37]+'\x3b',_0x3d077d=_0xd5878a[_0x54cf3f(0x372)](_0x453f1a+'\x20',_0x5eb6b0);_0x1a1c58?_0xd5878a[_0x54cf3f(0x23f)](_0x1a1c58[_0x54cf3f(0x47c)+'\x4f\x66'](_0x453f1a),-(0x1*-0x5bf+-0x14*0x142+0x1ee8))&&(_0x1a1c58=_0xd5878a[_0x54cf3f(0x355)](_0xd5878a[_0x54cf3f(0x45b)](_0x1a1c58,'\x0a'),_0x3d077d),_0x3ba1e8[_0x54cf3f(0x3d1)+'\x74\x61'](_0x1a1c58,_0xd5878a['\x44\x41\x76\x6c\x44']),ckList=_0x1a1c58[_0x54cf3f(0x660)]('\x0a'),_0x3ba1e8['\x6d\x73\x67'](_0xd5878a[_0x54cf3f(0x250)](_0x92317c,_0x54cf3f(0x2a5)+ckList[_0x54cf3f(0x2bd)+'\x68']+(_0x54cf3f(0x231)+'\x3a\x20')+_0x3d077d))):(_0x3ba1e8[_0x54cf3f(0x3d1)+'\x74\x61'](_0x3d077d,'\x6b\x73\x43\x6f\x6f'+_0x54cf3f(0x3d8)),_0x3ba1e8[_0x54cf3f(0x238)](_0xd5878a[_0x54cf3f(0x372)](_0x92317c,_0x54cf3f(0x523)+_0x54cf3f(0x231)+'\x3a\x20'+_0x3d077d)));}if(_0xd5878a['\x54\x56\x48\x53\x58']($request[_0x54cf3f(0x1eb)][_0x54cf3f(0x47c)+'\x4f\x66'](_0x54cf3f(0x638)+_0x54cf3f(0x1dd)+_0x54cf3f(0x6ba)+_0x54cf3f(0x2b7)+_0x54cf3f(0x5f7)+'\x77'),-(-0x22c*-0x1+-0x252c+0x67*0x57))){let _0x526fdc=_0xd5878a[_0x54cf3f(0x372)]($request[_0x54cf3f(0x1eb)]['\x6d\x61\x74\x63\x68'](/(kuaishou.api_st=[\w\-]+)/)[0x10f5+0x472*-0x4+0xd4],'\x3b'),_0x36862e=_0xd5878a[_0x54cf3f(0x355)]($request[_0x54cf3f(0x1eb)][_0x54cf3f(0x1dc)](/[\?&](did=[\w\-]+)/)[0x255a+0x248*0x7+-0x3551],'\x3b'),_0x574ef6=_0xd5878a['\x78\x57\x56\x66\x70'](_0x526fdc,'\x20')+_0x36862e;_0x1a1c58?_0xd5878a[_0x54cf3f(0x214)](_0x1a1c58[_0x54cf3f(0x47c)+'\x4f\x66'](_0x526fdc),-(0x711*-0x4+0xd9a*-0x1+-0xdf5*-0x3))&&(_0x1a1c58=_0xd5878a[_0x54cf3f(0x659)](_0x1a1c58,'\x0a')+_0x574ef6,_0x3ba1e8['\x73\x65\x74\x64\x61'+'\x74\x61'](_0x1a1c58,_0xd5878a[_0x54cf3f(0x62d)]),ckList=_0x1a1c58[_0x54cf3f(0x660)]('\x0a'),_0x3ba1e8[_0x54cf3f(0x238)](_0xd5878a[_0x54cf3f(0x56f)](_0x92317c,_0x54cf3f(0x2a5)+ckList[_0x54cf3f(0x2bd)+'\x68']+(_0x54cf3f(0x231)+'\x3a\x20')+_0x574ef6))):(_0x3ba1e8[_0x54cf3f(0x3d1)+'\x74\x61'](_0x574ef6,_0xd5878a[_0x54cf3f(0x62d)]),_0x3ba1e8[_0x54cf3f(0x238)](_0xd5878a[_0x54cf3f(0x659)](_0x92317c,_0x54cf3f(0x523)+_0x54cf3f(0x231)+'\x3a\x20'+_0x574ef6)));}}async function _0x5c8b6b(){const _0x1174fc=_0x2fc758,_0x45a062={};_0x45a062[_0x1174fc(0x671)]=function(_0x223956,_0x3690b8){return _0x223956>_0x3690b8;},_0x45a062[_0x1174fc(0x4c5)]=_0x1174fc(0x4b4);const _0x1d5dab=_0x45a062;if(_0x1a1c58){let _0x157001=_0x2fab55[-0xdf1+0x1d*0x52+0x4a7];for(let _0x17f37b of _0x2fab55){if(_0x1d5dab['\x75\x6f\x43\x4d\x47'](_0x1a1c58['\x69\x6e\x64\x65\x78'+'\x4f\x66'](_0x17f37b),-(0x2*-0x5b3+0x44*-0x57+0x1f*0x11d))){_0x157001=_0x17f37b;break;}}for(let _0x3820d0 of _0x1a1c58[_0x1174fc(0x660)](_0x157001)){if(_0x3820d0)_0x5b586['\x70\x75\x73\x68'](new _0x58e1a2(_0x3820d0));}_0x1d8cbf=_0x5b586[_0x1174fc(0x2bd)+'\x68'];}else{console[_0x1174fc(0x230)](_0x1d5dab[_0x1174fc(0x4c5)]);return;}return console[_0x1174fc(0x230)](_0x1174fc(0x1cc)+_0x1d8cbf+'\u4e2a\u8d26\u53f7'),!![];}async function _0xf3b68c(){const _0x2d1322=_0x2fc758,_0x2e860a={'\x64\x4f\x73\x5a\x71':function(_0x2840a6,_0x3fb29b){return _0x2840a6+_0x3fb29b;},'\x74\x6f\x56\x46\x77':_0x2d1322(0x31a)+'\x0a','\x69\x52\x78\x43\x46':function(_0x4e3798,_0x2fe017){return _0x4e3798>_0x2fe017;},'\x65\x65\x71\x66\x54':function(_0x269582,_0x4ec809){return _0x269582(_0x4ec809);}};if(!_0xf2cfe8)return;notifyBody=_0x2e860a[_0x2d1322(0x5e9)](_0x92317c,_0x2e860a[_0x2d1322(0x68e)])+_0xf2cfe8;if(_0x2e860a['\x69\x52\x78\x43\x46'](_0xe984ce,-0x2510*0x1+-0x1239+0x3749)){_0x3ba1e8[_0x2d1322(0x238)](notifyBody);if(_0x3ba1e8[_0x2d1322(0x3d6)+'\x65']()){var _0x5b3a85=_0x2e860a[_0x2d1322(0x60e)](require,_0x2d1322(0x256)+_0x2d1322(0x2f8)+'\x66\x79');await _0x5b3a85[_0x2d1322(0x4e9)+_0x2d1322(0x235)](_0x3ba1e8['\x6e\x61\x6d\x65'],notifyBody);}}else console[_0x2d1322(0x230)](notifyBody);}function _0xebcfd0(_0x243feb){const _0x9baf81=_0x2fc758;console[_0x9baf81(0x230)](_0x243feb),_0xf2cfe8+=_0x243feb,_0xf2cfe8+='\x0a';}async function _0x3fbb32(_0x16042e){const _0x18322b=_0x2fc758,_0x512ee1={'\x43\x4e\x61\x67\x79':_0x18322b(0x5c0)+_0x18322b(0x3e1)+'\x3d\x3d\x3d\x3d\x20'+_0x18322b(0x502)+'\x65\x61\x72\x20\u901a'+_0x18322b(0x247)+'\x3d\x3d\x3d\x3d\x3d'+'\x3d\x3d\x3d\x3d\x3d'+'\x0a','\x76\x45\x6b\x4c\x6b':function(_0x4ca34a,_0x4561d5){return _0x4ca34a(_0x4561d5);},'\x4a\x43\x44\x4a\x50':function(_0x4f8696,_0x31d2a1,_0x457b4a){return _0x4f8696(_0x31d2a1,_0x457b4a);},'\x74\x6b\x4c\x48\x67':_0x18322b(0x537),'\x72\x59\x74\x69\x4d':function(_0x3164d5,_0x90614d){return _0x3164d5==_0x90614d;}};if(!PushDearKey)return;if(!_0x16042e)return;console[_0x18322b(0x230)](_0x512ee1[_0x18322b(0x3ca)]),console[_0x18322b( | 0x16042e);let _0xed177c={'\x75\x72\x6c':_0x18322b(0x599)+'\x3a\x2f\x2f\x61\x70'+_0x18322b(0x2be)+_0x18322b(0x6a4)+_0x18322b(0x30a)+_0x18322b(0x297)+_0x18322b(0x37b)+_0x18322b(0x4a0)+'\x75\x73\x68\x6b\x65'+'\x79\x3d'+PushDearKey+('\x26\x74\x65\x78\x74'+'\x3d')+_0x512ee1[_0x18322b(0x65a)](encodeURIComponent,_0x16042e),'\x68\x65\x61\x64\x65\x72\x73':{}};await _0x512ee1['\x4a\x43\x44\x4a\x50'](_0x553fe7,_0x512ee1[_0x18322b(0x513)],_0xed177c);let _0x1eade5=_0x1b0221,_0x3a6f82=_0x512ee1[_0x18322b(0x50c)](_0x1eade5[_0x18322b(0x620)+'\x6e\x74'][_0x18322b(0x46d)+'\x74'],![])?'\u5931\u8d25':'\u6210\u529f';console['\x6c\x6f\x67'](_0x18322b(0x5c0)+_0x18322b(0x3e1)+_0x18322b(0x35a)+'\x68\x44\x65\x61\x72'+_0x18322b(0x594)+_0x3a6f82+(_0x18322b(0x5d6)+'\x3d\x3d\x3d\x3d\x3d'+'\x3d\x0a'));}async function _0x675773(){const _0x4c7a87=_0x2fc758,_0x21100e={'\x71\x6d\x4f\x6f\x58':function(_0x58858d,_0x4f6a56,_0x27c93b){return _0x58858d(_0x4f6a56,_0x27c93b);},'\x71\x49\x48\x76\x78':_0x4c7a87(0x537),'\x45\x6c\x44\x64\x70':function(_0x1d6aea,_0x170f44){return _0x1d6aea==_0x170f44;},'\x75\x76\x44\x6d\x6e':function(_0x153e63,_0x4d901b){return _0x153e63>=_0x4d901b;}},_0x63ba16={};_0x63ba16[_0x4c7a87(0x1eb)]=_0x40f474,_0x63ba16['\x68\x65\x61\x64\x65'+'\x72\x73']='';let _0x4c59aa=_0x63ba16;await _0x21100e[_0x4c7a87(0x2e9)](_0x553fe7,_0x21100e[_0x4c7a87(0x4a2)],_0x4c59aa);let _0x39b69d=_0x1b0221;if(!_0x39b69d)return;if(_0x39b69d[_0x29e991]){let _0x1b8ee1=_0x39b69d[_0x29e991];if(_0x21100e[_0x4c7a87(0x213)](_0x1b8ee1[_0x4c7a87(0x5d9)+'\x73'],-0x1928+0x9*-0x155+0x2525)){if(_0x21100e[_0x4c7a87(0x2d5)](_0x43a6e2,_0x1b8ee1['\x76\x65\x72\x73\x69'+'\x6f\x6e'])){const _0x112657=(_0x4c7a87(0x5b4)+_0x4c7a87(0x528))[_0x4c7a87(0x660)]('\x7c');let _0x4b83b0=0x1226*0x1+0x11ea+0x1208*-0x2;while(!![]){switch(_0x112657[_0x4b83b0++]){case'\x30':console[_0x4c7a87(0x230)]('\u73b0\u5728\u8fd0\u884c\u7684'+_0x4c7a87(0x412)+'\uff1a'+_0x43a6e2+(_0x4c7a87(0x24c)+_0x4c7a87(0x444))+_0x1b8ee1['\x6c\x61\x74\x65\x73'+_0x4c7a87(0x285)+_0x4c7a87(0x5a0)]);continue;case'\x31':_0x437cc6=!![];continue;case'\x32':console['\x6c\x6f\x67'](_0x1b8ee1['\x75\x70\x64\x61\x74'+_0x4c7a87(0x6b4)]);continue;case'\x33':_0x3ac963=_0x4c7a87(0x599)+_0x4c7a87(0x5ff)+'\x61\x66\x78\x63\x79'+_0x4c7a87(0x4bf)+_0x4c7a87(0x456)+'\x74\x2f\x70\x2f\x76'+_0x4c7a87(0x20e)+_0x4c7a87(0x25b)+_0x4c7a87(0x204)+_0x4c7a87(0x5e7)+_0x4c7a87(0x359)+'\x72\x61\x77\x2f\x6d'+_0x4c7a87(0x2cc)+'\x2f'+_0x29e991+_0x4c7a87(0x396);continue;case'\x34':console[_0x4c7a87(0x230)](_0x1b8ee1[_0x4c7a87(0x238)][_0x1b8ee1[_0x4c7a87(0x5d9)+'\x73']]);continue;}break;}}else console[_0x4c7a87(0x230)](_0x1b8ee1[_0x4c7a87(0x6a9)+_0x4c7a87(0x3bf)]);}else console[_0x4c7a87(0x230)](_0x1b8ee1['\x6d\x73\x67'][_0x1b8ee1[_0x4c7a87(0x5d9)+'\x73']]);}else console[_0x4c7a87(0x230)](_0x39b69d[_0x4c7a87(0x421)+_0x4c7a87(0x27b)]);}async function _0x21d45f(){const _0x1482e7=_0x2fc758,_0xf12541={'\x66\x6e\x71\x6a\x70':function(_0x1f4fe2,_0x595560,_0x181e57){return _0x1f4fe2(_0x595560,_0x181e57);},'\x63\x53\x75\x6d\x46':'\x67\x65\x74'};let _0x2b550d='';const _0x1d5c16={};_0x1d5c16['\x75\x72\x6c']=_0x3ac963,_0x1d5c16[_0x1482e7(0x4a9)+'\x72\x73']='';let _0x43d7d3=_0x1d5c16;await _0xf12541[_0x1482e7(0x2bb)](_0x553fe7,_0xf12541[_0x1482e7(0x584)],_0x43d7d3);let _0x105ab7=_0x1b0221;if(!_0x105ab7)return _0x2b550d;for(let _0x2e5faf of _0x105ab7[_0x1482e7(0x580)+'\x65']){if(_0x2e5faf)_0x2c2403['\x70\x75\x73\x68'](_0x2e5faf);}return _0x2b550d;}function _0x4c62f9(_0x2c86a8,_0x6bc39f,_0x3adefd=''){const _0x39c21d=_0x2fc758,_0x3c6193={};_0x3c6193[_0x39c21d(0x484)]='\x43\x6f\x6e\x74\x65'+_0x39c21d(0x6c5)+'\x70\x65',_0x3c6193[_0x39c21d(0x360)]=_0x39c21d(0x514)+_0x39c21d(0x39c)+_0x39c21d(0x6d6)+_0x39c21d(0x1c2)+_0x39c21d(0x3cd)+_0x39c21d(0x695)+_0x39c21d(0x5fe),_0x3c6193['\x57\x41\x41\x58\x4e']=_0x39c21d(0x65f)+_0x39c21d(0x200)+_0x39c21d(0x66a);const _0x199196=_0x3c6193;let _0x393b7a=_0x2c86a8['\x72\x65\x70\x6c\x61'+'\x63\x65']('\x2f\x2f','\x2f')[_0x39c21d(0x660)]('\x2f')[-0x14+0xbba+-0xba5];const _0xd6668c={};_0xd6668c['\x48\x6f\x73\x74']=_0x393b7a,_0xd6668c['\x43\x6f\x6f\x6b\x69'+'\x65']=_0x6bc39f;const _0x2d659e={};_0x2d659e['\x75\x72\x6c']=_0x2c86a8,_0x2d659e[_0x39c21d(0x4a9)+'\x72\x73']=_0xd6668c;let _0x269abb=_0x2d659e;return _0x3adefd&&(_0x269abb[_0x39c21d(0x5e4)]=_0x3adefd,_0x269abb[_0x39c21d(0x4a9)+'\x72\x73'][_0x199196['\x6f\x4e\x59\x6b\x58']]=_0x199196[_0x39c21d(0x360)],_0x269abb['\x68\x65\x61\x64\x65'+'\x72\x73'][_0x199196[_0x39c21d(0x56e)]]=_0x269abb[_0x39c21d(0x5e4)]?_0x269abb[_0x39c21d(0x5e4)][_0x39c21d(0x2bd)+'\x68']:0xccd+-0x5*0x1d2+-0x1*0x3b3),_0x269abb;}async function _0x553fe7(_0x17eeed,_0x320d9b){const _0x51cc6e={'\x77\x70\x51\x49\x51':function(_0x2b1467,_0x4dea11){return _0x2b1467(_0x4dea11);}};return _0x1b0221=null,new Promise(_0x2bbbdd=>{const _0x5a3a0c={'\x71\x6a\x49\x48\x48':function(_0x67c88c,_0x2aca4f){const _0x2f19a5=_0x42bc;return _0x51cc6e[_0x2f19a5(0x40d)](_0x67c88c,_0x2aca4f);},'\x50\x61\x58\x5a\x63':function(_0x38f056){return _0x38f056();}};_0x3ba1e8[_0x17eeed](_0x320d9b,async(_0x1164ba,_0x266d4a,_0x484fe5)=>{const _0x585a97=_0x42bc;try{if(_0x1164ba)console[_0x585a97(0x230)](_0x17eeed+_0x585a97(0x66c)),console[_0x585a97(0x230)](JSON[_0x585a97(0x3dc)+'\x67\x69\x66\x79'](_0x1164ba)),_0x3ba1e8[_0x585a97(0x608)+'\x72'](_0x1164ba);else{if(_0x5a3a0c[_0x585a97(0x576)](_0xc3223b,_0x484fe5)){_0x1b0221=JSON[_0x585a97(0x2a3)](_0x484fe5);if(_0x5791a4)console[_0x585a97(0x230)](_0x1b0221);}}}catch(_0x440a7d){_0x3ba1e8['\x6c\x6f\x67\x45\x72'+'\x72'](_0x440a7d,_0x266d4a);}finally{_0x5a3a0c[_0x585a97(0x2c6)](_0x2bbbdd);}});});}function _0x46e9(){const _0x2dd9f0=['\x55\x6e\x76\x70\x70','\x4b\x62\x58\x7a\x41','\x70\x69\x5f\x73\x74','\x2f\x76\x31\x2f\x73','\x72\x44\x48\x48\x78','\x57\x41\x49\x6c\x56','\x44\x41\x76\x6c\x44','\x35\x62\x35\x64\x62','\x51\x79\x69\x70\x79','\x64\x31\x35\x63\x63','\x33\x38\x63\x30\x37','\x47\x72\x7a\x71\x63','\u8d26\u53f7\x5b','\x52\x42\x4b\x55\x46','\x62\x76\x48\x69\x6c','\x4e\x44\x52\x4f\x49','\x54\x72\x61\x6e\x73','\x6b\x73\x61\x70\x70','\x5d\u5f00\u5b9d\u7bb1\u51b7','\u7b7e\u5230\u89c6\u9891\x31','\x61\x67\x65\x2f\x73','\x3d\x25\x37\x42\x25','\x6f\x75\x6e\x74\x22','\x39\x31\x34\x36\x34\x79\x6d\x57\x45\x49\x79','\x76\x4b\x6f\x6d\x46','\x67\x69\x66\x79','\x70\x6a\x70\x50\x6f','\x68\x35\x2f\x77\x69','\x65\x79\x3d\x49\x4e','\x6d\x69\x6e\x75\x74','\x72\x72\x65\x6e\x74','\x76\x74\x4d\x48\x7a','\x72\x69\x48\x46\x63','\u72b6\u6001\u5931\u8d25\uff1a','\u5316\u63d0\u73b0','\x75\x71\x6b\x67\x56','\x70\x61\x79\x2e\x63','\x7c\x30\x7c\x31\x7c','\x79\x3d\x33\x63\x32','\x69\x73\x4c\x6f\x6f','\x73\x74\x2f\x72\x2f','\x64\x36\x5a\x56\x37','\x51\x43\x79\x45\x6e','\x37\x3b\x20\x6c\x61','\x6e\x65\x65\x64\x53','\x6e\x75\x74\x65\x73','\x5d\u5f00\u59cb\u4efb\u52a1','\x6f\x75\x6e\x74\x72','\x38\x5a\x6b\x4f\x30','\x42\x49\x56\x71\x56','\x72\x45\x46\x6b\x75','\x76\x45\x6b\x4c\x6b','\x77\x59\x36\x44\x6c','\x51\x61\x71\x4c\x53','\x20\u8d26\u6237\u60c5\u51b5','\x66\x51\x4a\x53\x72','\x43\x6f\x6e\x74\x65','\x73\x70\x6c\x69\x74','\x6b\x42\x50\x4e\x71','\x61\x6d\x65\x2f\x74','\x48\x65\x41\x71\x44','\x74\x51\x70\x4f\x7a','\x46\x73\x77\x6f\x6a','\x6c\x6f\x67\x73','\x73\x69\x67\x6e\x31','\x64\x52\x65\x77\x72','\x40\x63\x68\x61\x76','\x6e\x67\x74\x68','\x4f\x55\x4b\x53\x25','\u8bf7\u6c42\u5931\u8d25','\x6d\x65\x72\x52\x65','\u8fd4\u56de\u4e3a\u7a7a','\x6f\x75\x6e\x74\x2f','\x34\x64\x34\x65\x61','\x75\x6f\x43\x4d\x47','\x6e\x2f\x69\x6e\x6b','\x6e\x69\x43\x6c\x41','\x77\x76\x4a\x74\x43','\x53\x65\x63\x6f\x6e','\x57\x44\x25\x32\x42','\x5f\x65\x6e\x63\x6f','\x55\x47\x54\x54\x63','\x4b\x55\x52\x41\x6d','\x73\x68\x6f\x75\x2e','\x6e\x2f\x6a\x73\x6f','\x63\x32\x36\x32\x37','\x74\x46\x6a\x56\x7a','\x69\x6e\x67','\x63\x35\x62\x63\x30','\x56\x63\x69\x53\x52','\x5d\u63d0\u73b0','\x61\x69\x73\x68\x6f','\x4a\x55\x65\x42\x44','\x65\x3d\x7a\x68\x2d','\x6c\x5f\x66\x65\x6e','\x61\x64\x32','\x49\x64\x3d','\x31\x54\x36\x6a\x56','\x37\x2e\x30\x2e\x30','\x6a\x67\x72\x56\x7a','\x42\x49\x71\x74\x4c','\x5d\u8d26\u6237\u4f59\u989d','\x5d\u5f00\u5b9d\u7bb1\u5931','\x74\x6f\x56\x46\x77','\x57\x58\x57\x41\x63','\x49\x42\x70\x6a\x72','\x69\x68\x5a\x68\x53','\x5a\x75\x5a\x6c\x79','\x58\x2d\x53\x75\x72','\x37\x39\x38\x38\x37','\x6c\x65\x6e\x63\x6f','\x6e\x43\x6f\x6d\x70','\x3d\x26\x73\x65\x73','\x75\x4f\x74\x76\x64','\x4a\x48\x59\x76\x51','\x5d\u9886\u53d6\u4efb\u52a1','\x6c\x6f\x64\x61\x73','\x4a\x33\x25\x32\x42','\x77\x47\x76\x72\x46','\x4b\x4c\x4d\x4e\x4f','\x69\x6e\x66\x6f','\x79\x43\x4b\x66\x4c','\x68\x59\x46\x38\x74','\x74\x77\x52\x54\x50','\x6e\x65\x6f\x41\x6d','\x73\x68\x64\x65\x65','\x6b\x73\x41\x67\x67','\x63\x6f\x6e\x63\x61','\x65\x5f\x63\x6f\x64','\x5d\u4eca\u5929','\x76\x65\x72\x73\x69','\x5a\x61\x62\x63\x64','\x25\x32\x32\x25\x37','\x74\x73\x4b\x61\x55','\x37\x7c\x32\x7c\x38','\x4e\x68\x43\x66\x7a','\x75\x73\x69\x6e\x65','\x4b\x52\x4f\x46\x58','\x49\x63\x48\x79\x4c','\x71\x44\x73\x6c\x6c','\x57\x6f\x71\x53\x74','\x65\x4d\x73\x67','\x34\x26\x6b\x70\x66','\x6e\x74\x49\x6e\x66','\x79\x2e\x65\x2e\x6b','\x6d\x7a\x6c\x5a\x44','\x62\x7a\x6b\x4e\x54','\x6e\x74\x2f\x70\x61','\x7b\x22\x74\x61\x73','\x30\x7c\x32\x7c\x31','\x62\x69\x57\x53\x41','\x37\x7c\x34\x7c\x36','\x45\x73\x74\x51\x44','\x77\x2f\x61\x70\x70','\x63\x6f\x6f\x6b\x69','\x66\x65\x74\x63\x68','\u73b0\u5728\u8bbe\u7f6e\u4e3a','\x6c\x6f\x67\x53\x65','\x6e\x74\x2d\x54\x79','\x48\x4f\x64\x78\x69','\x61\x74\x61','\x6a\x68\x59\x63\x6e','\x63\x67\x4c\x6d\x4a','\x7c\x33\x7c\x32','\x4a\x67\x54\x70\x6d','\u4e0d\u63d0\u73b0','\x6b\x73\x4e\x6f\x74','\x2c\x22\x65\x6e\x64','\x74\x4e\x63\x4a\x5a','\x67\x76\x56\x65\x76','\x63\x6b\x74\x6f\x75','\x61\x6e\x6b\x5f\x69','\x59\x54\x56\x74\x73','\x6b\x70\x49\x52\x66','\x69\x70\x2d\x53\x63','\x6e\x2f\x78\x2d\x77','\x6e\x65\x65\x64\x5f','\x72\x2f\x62\x69\x6e','\x61\x74\x69\x76\x65','\x61\x70\x70\x73\x75','\x68\x65\x6c\x70\x53','\x74\x2f\x70\x2f\x76','\x61\x63\x63\x6f\x75','\x43\x78\x77\x4c\x52','\x63\x72\x69\x70\x74','\x74\x26\x73\x64\x6b','\x32\x30\x33','\x50\x65\x4f\x33\x55','\u53c2\u6570\u5931\u8d25\uff1a','\x49\x48\x66\x63\x46','\x34\x31\x39\x32\x66','\x74\x6f\x61\x73\x74','\x41\x71\x6c\x72\x49','\x44\x73\x69\x46\x4d','\x46\x77\x71\x38\x35','\x39\x34\x4c\x4d\x53','\x61\x6b\x65\x3f\x74','\x77\x77\x2d\x66\x6f','\x7b\x22\x73\x69\x67','\x42\x43\x6f\x78\x6d','\x4e\x6f\x4c\x78\x67','\x6e\x75\x6d','\x65\x44\x4d\x63\x7a','\x61\x63\x74\x69\x76','\x6f\x22\x2c\x22\x6e','\x52\x78\x52\x58\x72','\x61\x31\x64\x64\x65','\u5171\u627e\u5230','\x6f\x75\x72\x63\x65','\x6c\x69\x70\x61\x79','\x6d\x65\x64\x69\x61','\x65\x6f\x65\x67\x4d','\x53\x48\x26\x62\x69','\x77\x61\x69\x74','\x58\x41\x59\x4c\x7a','\x64\x6d\x51\x67\x53','\x63\x72\x6f\x6e','\x70\x4f\x69\x75\x78','\x77\x56\x26\x73\x69','\x47\x45\x54','\x75\x72\x73','\x59\x56\x4a\x74\x69','\x50\x37\x5a\x31\x67','\x6d\x61\x74\x63\x68','\x2f\x63\x6c\x69\x65','\x54\x48\x71\x67\x43','\x39\x66\x34\x32\x37','\x69\x67\x6e\x49\x6e','\x42\x61\x4e\x4b\x79','\x44\x5f\x35\x2e\x31','\x63\x64\x33\x66\x33','\x32\x46\x38\x49\x62','\x55\x6a\x6a\x50\x54','\x69\x6e\x67\x2f\x65','\x67\x65\x74\x4d\x69','\x66\x57\x65\x6e\x52','\x32\x42\x43\x59\x74','\x6b\x63\x53\x45\x43','\x75\x72\x6c','\x5f\x50\x48\x4f\x4e','\uff0c\u73b0\u5728\u8bbe\u7f6e','\x4c\x34\x7a\x48\x68','\x33\x63\x34\x62\x66','\x67\x65\x74\x55\x73','\x70\x57\x70\x49\x46','\x6f\x70\x74\x73','\x6b\x73\x43\x61\x73','\x78\x4a\x58\x62\x45','\x67\x77\x33\x67\x38','\x79\x66\x4d\x72\x64','\x58\x49\x4f\x79\x4d','\x6b\x50\x59\x57\x52','\x36\x57\x67\x4d\x77\x44\x6a','\x6e\x69\x63\x6b\x4e','\x62\x69\x7a\x53\x74','\x56\x4f\x76\x25\x32','\x47\x46\x45\x55\x6a','\x37\x62\x65\x37\x33','\x64\x6f\x6e\x65','\x6e\x74\x2d\x4c\x65','\x56\x49\x54\x45\x5f','\u5230\u63d0\u73b0\u5217\u8868','\x77\x6e\x39','\x2f\x76\x61\x6c\x69','\x63\x48\x42\x79\x54','\x53\x54\x4e\x4a\x64','\x5d\u4f59\u989d\u4e0d\u8db3','\x56\x65\x72\x73\x69','\x67\x68\x7a\x68\x6b','\x32\x34\x38\x66\x37','\x54\x75\x7a\x65\x54','\x31\x30\x30','\x4f\x67\x69\x78\x69','\x61\x6c\x69\x64\x63','\x4e\x51\x58\x70\x6a','\x35\x37\x33\x61\x37','\x32\x42\x74\x44\x7a','\x6f\x74\x45\x6e\x76','\x45\x6c\x44\x64\x70','\x42\x4e\x62\x6f\x67','\u652f\u4ed8\u5b9d','\x36\x61\x62\x33\x31','\x66\x3d\x41\x4e\x44','\x30\x61\x31\x38\x35','\x50\x55\x54','\x48\x31\x6d\x38\x4c','\x73\x69\x6f\x6e\x5f','\x74\x6b\x53\x45\x4d','\x70\x75\x74','\u81ea\u52a8\u63d0\u73b0','\x62\x6c\x57\x63\x57','\x3d\x3d\x20\u8d26\u53f7','\x68\x6f\x75\x2e\x63','\x64\x36\x61\x33\x65','\x69\x6e\x69\x74\x47','\x5d\u67e5\u8be2\u4efb\u52a1','\x32\x7c\x30\x7c\x35','\x6f\x2e\x73\x78\x33','\x32\x64\x48\x64\x61','\x3a\x2f\x2f\x64\x65','\x70\x61\x72\x61\x74','\x25\x32\x42\x77\x44','\x67\x65\x74\x76\x61','\x67\x36\x6a\x39\x6f','\x46\x69\x6c\x65\x53','\x48\x69\x57\x69\x68','\x6e\x6a\x72\x7a\x58','\x6c\x6f\x67','\u4e2a\x63\x6b\u6210\u529f','\x63\x68\x61\x72\x43','\x64\x43\x6f\x75\x6e','\x49\x6e\x66\x6f','\x6f\x74\x69\x66\x79','\x6b\x73\x41\x64\x50','\x45\x3b\x20\x63\x3d','\x6d\x73\x67','\x31\x30\x36\x31\x31\x33\x31\x5a\x6e\x4a\x63\x65\x6b','\x4a\x7a\x53\x44\x42','\x6b\x54\x79\x70\x65','\uff0c\u4f59\u989d\u4e0d\u8db3','\x65\x78\x70\x6f\x72','\x7c\x32\x7c\x31','\x4c\x5a\x78\x47\x75','\x63\x75\x72\x72\x65','\x69\x74\x79\x49\x64','\x34\x7c\x31\x7c\x32','\x26\x61\x74\x74\x61','\x31\x31\x65\x64\x64','\x74\x73\x46\x32\x75','\x5d\u7b7e\u5230\u5931\u8d25','\u77e5\x20\x3d\x3d\x3d','\x64\x7a\x45\x62\x45','\x68\x44\x71\x48\x31','\x72\x65\x64\x69\x72','\x75\x73\x46\x6b\x59','\uff0c\u6700\u65b0\u811a\u672c','\u672a\u7ed1\u5b9a\u5fae\u4fe1','\x37\x4d\x42\x59\x59','\u5df2\u5b8c\u6210','\x54\x77\x6a\x6f\x6f','\x64\x61\x74\x61','\x73\x6c\x69\x63\x65','\x48\x6f\x4d\x31\x62','\x76\x54\x73\x4c\x41','\x2c\x20\u9519\u8bef\x21','\x2e\x2f\x73\x65\x6e','\x7a\x4b\x50\x63\x4a','\x51\x73\x77\x76\x78','\x75\x51\x58\x46\x58','\x42\x64\x72\x52\x51','\x6f\x64\x65\x2f\x64','\x6d\x65\x74\x65\x72','\x32\x36\x38\x35\x36\x39\x34\x69\x54\x5a\x7a\x43\x6c','\x69\x65\x6e\x74\x50','\x32\x76\x44\x72\x71','\x5d\u4efb\u52a1\u5b8c\u6210','\x4a\x54\x6b\x57\x62','\x72\x3d\x7b\x22\x62','\x4d\x49\x55\x77\x6c','\x45\x6d\x6e\x71\x68','\x69\x6d\x65\x22\x3a','\x4b\x56\x52\x6a\x66','\x76\x67\x46\x69\x54','\x68\x74\x74\x70','\x67\x65\x2d\x53\x6b','\x45\x58\x79\x57\x4e','\x68\x65\x6c\x70\x49','\x4f\x70\x57\x4c\x79','\x74\x4b\x43\x43\x50','\x3a\x2f\x2f\x61\x63','\x74\x79\x46\x75\x4c','\x64\x4a\x59\x25\x32','\x64\x6f\x53\x69\x67','\x5f\x75\x74\x66\x38','\x6f\x64\x65\x41\x74','\x4f\x38\x74\x4e\x63','\x41\x4c\x49\x50\x41','\x73\x43\x6f\x64\x65','\x68\x4f\x6d\x48\x41','\x6e\x57\x64\x53\x4c','\x52\x55\x4f\x42\x73','\x3a\x2f\x2f\x31\x32','\x4d\x73\x67','\u60c5\u51b5\u5931\u8d25\uff1a','\x45\x77\x4c\x4d\x54','\x61\x66\x25\x32\x46','\x38\x39\x2b\x2f\x3d','\x31\x30\x31','\x31\x66\x32\x61\x38','\u76f4\u64ad\u89c6\u9891','\x61\x64\x2f\x74\x61','\x65\x72\x76\x61\x6c','\x74\x56\x65\x72\x73','\x73\x74\x61\x72\x74','\x76\x61\x69\x6c\x61','\x38\x35\x31\x33\x30\x34\x33\x73\x75\x79\x67\x6e\x61','\x38\x31\x36\x62\x38','\x72\x61\x77\x4f\x6c','\x5d\u83b7\u53d6','\x61\x70\x68\x57\x37','\x68\x64\x72\x61\x77','\x49\x6e\x64\x50\x58','\x67\x65\x3d\x68\x74','\x7a\x50\x44\x54\x76','\x72\x7a\x74\x62\x75','\x62\x69\x6e\x64\x49','\x69\x7a\x5f\x63\x6f','\x41\x6c\x62\x75\x6d','\x33\x7c\x38\x7c\x35','\x67\x47\x73\x65\x45','\x2f\x6d\x65\x73\x73','\x54\x59\x49\x51\x68','\x30\x39\x31\x31\x36','\x26\x6b\x70\x6e\x3d','\x49\x64\x22\x3a\x37','\x69\x73\x68\x6f\x75','\x5d\u5f00\u5b9d\u7bb1\u83b7','\x6f\x70\x71\x72\x73','\x65\x6e\x76','\x75\x61\x69\x73\x68','\x41\x49\x42\x37\x44','\x30\x32\x34\x34','\x70\x61\x72\x73\x65','\x3b\x20\x64\x69\x64','\x20\u83b7\u53d6\u7b2c','\x79\x35\x68\x4d\x79','\x73\x74\x2f\x65\x2f','\x35\x33\x33\x62\x65','\x69\x6e\x65\x64','\x42\x51\x66\x4e\x31','\x36\x76\x4f\x31\x54','\x41\x63\x74\x69\x76','\x72\x65\x61\x73\x75','\x71\x47\x68\x59\x6b','\x32\x55\x37\x63\x77','\x32\x32\x31\x33\x37\x33\x34\x65\x48\x61\x64\x47\x5a','\x74\x65\x6e\x74\x48','\x6a\x73\x5f\x75\x73','\x2f\x61\x6e\x79','\x43\x51\x58\x6c\x6a','\x26\x63\x6f\x6d\x6d','\x52\x51\x32\x4b\x33','\x63\x6b\x61\x67\x65','\x59\x56\x4b\x72\x25','\x73\x6d\x68\x62\x69','\x6e\x42\x69\x7a\x49','\x66\x6e\x71\x6a\x70','\x70\x61\x74\x68','\x6c\x65\x6e\x67\x74','\x69\x32\x2e\x70\x75','\x26\x63\x6c\x69\x65','\x74\x61\x73\x6b\x49','\x62\x36\x62\x39\x62','\x72\x61\x77\x4f\x76','\x65\x65\x65\x33\x66','\x50\x41\x47\x45','\x49\x58\x5a\x63\x44','\x50\x61\x58\x5a\x63','\u672a\u5b8c\u6210','\x48\x51\x75\x71\x78','\x74\x6f\x4f\x62\x6a','\x5a\x4c\x77\x6e\x41','\x5d\u624b\u52a8\u8bbe\u7f6e','\x61\x73\x74\x65\x72','\x79\x61\x78\x66\x75','\x42\x25\x32\x46\x46','\x79\x54\x51\x68\x51','\x68\x41\x53\x43\x43','\x68\x5f\x67\x65\x74','\x6b\x70\x6e\x3d\x4b','\x6a\x31\x65\x73\x41','\x74\x68\x64\x72\x61','\x75\x76\x44\x6d\x6e','\x64\x65\x34\x64\x34','\x2f\x63\x6f\x64\x65','\x31\x7c\x31\x32\x7c','\x45\x66\x44\x77\x6e','\x71\x65\x65\x68\x59','\x4d\x4a\x4c\x7a\x63','\x6d\x61\x70','\x55\x50\x57\x6d\x6e','\x49\x6c\x70\x78\x47','\x59\x6b\x51\x72\x73','\x61\x67\x65\x2f\x61','\x4f\x51\x62\x54\x65','\x74\x61\x3d\x57\x6c','\x59\x75\x62\x79\x51','\x61\x73\x6b\x2f\x72','\x32\x42\x4d\x7a\x74','\x3d\x35\x61\x35\x34','\x6b\x73\x57\x69\x74','\x74\x58\x30\x32\x36','\x71\x6d\x4f\x6f\x58','\x2f\x79\x6f\x64\x61','\x7b\x22\x63\x68\x61','\x61\x37\x38\x31\x66','\x73\x22\x3a\x22','\x61\x70\x69\x5f\x73','\x4a\x71\x52\x6a\x62','\x73\x63\x59\x53\x31','\x74\x6c\x65','\x77\x6e\x36','\x5d\u51c6\u5907\u63d0\u73b0','\x34\x7c\x33\x7c\x30','\x54\x39\x4f\x46\x35','\x66\x4f\x79\x4d\x58','\x6d\x44\x62\x74\x25','\x64\x4e\x6f\x74\x69','\u63d0\u73b0\u60c5\u51b5\u5931','\x48\x33\x4f\x6a\x36','\x2f\x77\x64\x2f\x65','\x62\x6c\x65\x41\x6d','\x69\x74\x65','\x61\x70\x70\x6c\x79','\x3a\x2f\x2f\x61\x70','\u9875\u5b9a\u65f6\u5956\u52b1','\x6a\x52\x76\x67\x54','\x63\x6f\x69\x6e','\x72\x65\x73\x6f\x6c','\x6f\x6d\x65','\x69\x6d\x70\x41\x64','\x56\x78\x4e\x69\x79','\x4b\x74\x62\x68\x66','\x36\x31\x38\x66\x64','\x74\x61\x73\x6b\x54','\x72\x2e\x63\x6f\x6d','\x6f\x73\x22\x3a\x5b','\u52b1\u51b7\u5374\u65f6\u95f4','\x63\x6f\x6d\x2f\x66','\x36\x63\x36\x39\x62','\x5d\u67e5\u8be2\u62bd\u5956','\x61\x4b\x71\x41\x77','\x59\x43\x4d\x51\x63','\x69\x70\x33\x64\x68','\x33\x39\x39\x39\x30\x39\x30\x6a\x41\x66\x75\x63\x6e','\x48\x47\x64\x6f\x58','\x43\x64\x46\x31\x77','\x38\x65\x65\x6b\x72','\x4b\x46\x70\x76\x46','\x5d\u62bd\u5956\u9875\u5956','\x41\x4d\x7a\x72\x4f','\u8fd0\u884c\u901a\u77e5\x0a','\x74\x65\x73\x74','\x39\x35\x32\x35\x62','\x61\x6c\x69\x70\x61','\x78\x49\x6e\x66\x6f','\x48\x4e\x57\x43\x59','\x22\x3a\x31\x7d\x5d','\x75\x63\x79\x42\x49','\x31\x35\x62\x30\x62','\x45\x71\x73\x59\x53','\x72\x53\x63\x61\x6e','\x74\x57\x56\x73\x6f','\x74\x6f\x53\x74\x72','\x73\x2e\x68\x74\x74','\x55\x36\x6d\x47\x54','\x4c\x52\x6a\x68\x25','\x20\u81ea\u52a8\u63d0\u73b0','\x44\x72\x63\x4b\x43','\x2a\x2f\x2a','\x63\x61\x73\x68\x41','\x50\x72\x66\x6d\x54','\x32\x42\x4f\x30\x51','\x54\x77\x6b\x77\x79','\x69\x73\x74','\x2f\x64\x65\x6d\x65','\x6f\x70\x65\x6e\x55','\x6d\x65\x74\x68\x6f','\x64\x4b\x6a\x6b\x38','\x43\x73\x41\x51\x70','\x6e\x76\x69\x74\x61','\x57\x45\x43\x48\x41','\x41\x50\x76\x47\x59','\x2f\x69\x6e\x66\x6f','\x2c\x22\x73\x74\x61','\x31\x51\x71\x74\x6d','\x68\x5f\x73\x65\x74','\x72\x61\x77\x2f\x6d','\x6e\x76\x69\x74\x65','\x61\x65\x44\x7a\x71','\x79\x2f\x61\x63\x63','\x66\x39\x32\x63\x31','\u65f6\u5956\u52b1\u6b21\u6570','\x6f\x6d\x2f\x70\x61','\x5d\u67e5\u8be2\u63d0\u73b0','\x69\x73\x53\x69\x67','\x67\x30\x6d\x61\x57','\x56\x7a\x52\x58\x65','\x69\x31\x79\x59\x34','\x53\x41\x39\x57\x77','\u6b21\u4efb\u52a1','\x50\x4f\x53\x54','\x25\x32\x46\x67\x68','\x65\x73\x49\x6e\x74','\x75\x6e\x64\x65\x66','\x5d\u5931\u8d25\uff1a','\x3d\x3d\x3d','\x63\x68\x61\x72\x41','\x69\x76\x65\x49\x64','\x73\x69\x67\x6e','\x74\x4b\x6d\x67\x6e','\x7c\x31\x7c\x33\x7c','\x79\x43\x6f\x64\x65','\x32\x32\x73\x6f\x75','\x2f\x67\x69\x74\x2f','\x3d\x20\x50\x75\x73','\x66\x6c\x6f\x6f\x72','\x61\x6b\x74\x52\x6d','\x51\x6a\x6e\x6b\x74','\x65\x6f\x49\x6e\x66','\x61\x73\x6b\x2f\x74','\x67\x7a\x41\x59\x67','\u5e7f\u544a\u89c6\u9891\x31','\x3d\x43\x4e\x3b\x20','\x69\x6d\x65','\x6c\x69\x76\x65','\x42\x35\x37\x67\x66','\x3f\x73\x6f\x75\x72','\x6b\x73\x4e\x65\x6f','\x5f\x64\x65\x63\x6f','\x61\x72\x61\x6d','\x48\x75\x4d\x72\x4a','\x56\x75\x69\x46\x50','\x57\x75\x55\x6c\x36','\x7c\x30\x7c\x34\x7c','\x65\x6f\x56\x65\x48','\x54\x79\x70\x65','\x68\x6d\x70\x7a\x4c','\x5a\x58\x53\x53\x42','\x57\x65\x66\x45\x6c','\x68\x6e\x6b\x53\x42','\x62\x75\x73\x69\x6e','\x30\x62\x33\x64\x64','\x65\x77\x61\x72\x64','\x6b\x63\x65\x41\x4a','\x5f\x6b\x65\x79\x53','\x67\x57\x4a\x64\x4e','\x68\x61\x72\x43\x6f','\x61\x67\x65\x2f\x70','\x61\x64\x42\x61\x73','\x69\x73\x73\x69\x6f','\u672a\u7ed1\u5b9a\u652f\u4ed8','\x46\x78\x41\x44\x5a','\x39\x69\x71\x6f\x76','\x69\x73\x4e\x65\x65','\x2f\x72\x65\x70\x6f','\x79\x6d\x67\x4e\x67','\x71\x58\x63\x72\x56','\x31\x6d\x59\x6c\x72','\x63\x63\x6f\x75\x6e','\x7a\x63\x5a\x65\x74','\x72\x33\x25\x32\x46','\x63\x61\x73\x68','\x34\x51\x31\x58\x6f','\x65\x78\x74\x50\x61','\x50\x42\x42\x51\x48','\x50\x47\x57\x61\x77','\x2e\x24\x31','\x78\x4b\x30\x78\x6b','\x50\x48\x4f\x4e\x45','\x67\x65\x74\x6a\x73','\x64\x22\x3a','\x6a\x34\x6f\x7a\x43','\x65\x49\x64\x22\x3a','\x6d\x73\x37\x39\x69','\x2e\x6a\x73\x6f\x6e','\x74\x6f\x4c\x6f\x77','\x5d\x20\x3d\x3d\x3d','\x6d\x53\x30\x57\x57','\x6d\x6f\x75\x6e\x74','\x33\x34\x35\x36\x37','\x63\x61\x74\x69\x6f','\x67\x65\x74\x53\x69','\x6a\x6f\x4a\x72\x48','\x6f\x6d\x2f\x72\x65','\x73\x75\x62\x50\x61','\u5143\uff0c\u4e0d\u63d0\u73b0','\x78\x62\x4d\x46\x4d','\x42\x6a\x6d\x75\x6e','\x74\x6f\x64\x61\x79','\x64\x61\x39\x34\x4c','\x65\x46\x53\x71\x41','\x62\x36\x66\x63\x30','\x4a\x52\x6a\x4c\x6f','\x6d\x6f\x63\x6b\x5f','\x6d\x72\x47\x70\x77','\x43\x6f\x6f\x6b\x69','\x4d\x65\x73\x73\x61','\x71\x77\x25\x32\x42','\x72\x65\x73\x73\x69','\u5143\uff0c\u4e0d\u6267\u884c','\x4b\x69\x6a\x70\x68','\x61\x67\x65\x2f\x74','\x65\x3d\x68\x6f\x74','\x5d\u672a\u7ed1\u5b9a\u63d0','\x47\x74\x67\x72\x6c','\x77\x61\x72\x64','\x63\x61\x6e','\x44\x52\x4f\x49\x44','\x4c\x46\x56\x61\x43','\x61\x63\x4f\x74\x6e','\x6e\x56\x69\x65\x77','\x56\x31\x67\x42\x4d','\x46\x47\x48\x49\x4a','\x73\x5a\x6f\x42\x70','\x58\x4e\x50\x70\x4d','\x6f\x6e\x4d\x73\x67','\x2c\x20\u5f00\u59cb\x21','\x73\x46\x61\x4e\x68','\x70\x65\x3d\x33','\x33\x55\x68\x44\x71','\x54\x35\x50\x65\x6b','\x4f\x64\x45\x59\x5a','\x41\x44\x78\x51\x65','\x78\x6e\x4e\x52\x4b','\x4e\x56\x61\x74\x57','\x69\x6c\x65','\x43\x4e\x61\x67\x79','\x76\x61\x6c\x69\x64','\x47\x4e\x53\x76\x56','\x72\x6d\x2d\x75\x72','\x72\x61\x77','\x5d\u4eca\u5929\u5df2\u63d0','\x77\x69\x6d\x6b\x6d','\x73\x65\x74\x64\x61','\x76\x61\x6c\x75\x65','\x63\x61\x39\x37\x37','\x65\x4a\x61\x72','\x62\x34\x34\x30\x38','\x69\x73\x4e\x6f\x64','\x65\x63\x68\x61\x74','\x6b\x69\x65','\x70\x6f\x73\x74','\x63\x61\x6c\x6c','\x55\x41\x49\x53\x48','\x73\x74\x72\x69\x6e','\x70\x75\x73\x68','\x6e\x74\x5f\x6b\x65','\x31\x7c\x37\x7c\x31','\x46\x7a\x39\x61\x53','\x3d\x3d\x3d\x3d\x3d','\x76\x31\x55\x4f\x38','\x65\x78\x67\x42\x44','\x4b\x4c\x6d\x4d\x6a','\x2f\x62\x69\x7a\x2f','\x77\x69\x74\x68\x64','\x34\x36\x6a\x79\x4f','\x49\x51\x79\x55\x73','\x31\x26\x6b\x70\x6e','\x69\x73\x4d\x75\x74','\x48\x4f\x55','\x54\x5a\x45\x70\x51','\x62\x61\x34\x66\x38','\x6b\x76\x74\x4e\x54','\x6b\x78\x7a\x67\x45','\x71\x6f\x76\x38\x65','\x38\x38\x58\x70\x48','\x76\x62\x71\x74\x5a','\x6b\x2f\x67\x65\x74','\u60c5\u51b5\uff1a','\x70\x70\x6f\x72\x74','\x73\x73\x49\x64\x22','\x2e\x32\x34\x31\x35','\x62\x69\x6e\x64\x57','\x42\x6c\x54\x51\x4e','\u5df2\u7ed1\u5b9a\u652f\u4ed8','\x54\x69\x6d\x65\x22','\x6e\x63\x6f\x75\x72','\x47\x43\x79\x47\x62','\x62\x69\x6e\x64\x41','\x74\x48\x52\x54\x64','\x7a\x6b\x78\x4e\x32','\x57\x45\x69\x7a\x69','\x48\x41\x7a\x6b\x57','\x69\x6c\x65\x53\x79','\u8bbe\u5907\u7f51\u7edc\u60c5','\x22\x76\x69\x64\x65','\x5d\u901b\u8857\u5931\u8d25','\x69\x54\x63\x7a\x6b','\x49\x64\x22\x3a','\x70\x61\x70\x69','\x6a\x71\x41\x63\x56','\x25\x32\x42\x51\x66','\x67\x65\x74\x64\x61','\x77\x70\x51\x49\x51','\x70\x43\x45\x78\x78','\u670d\u52a1\u5668\u8bbf\u95ee','\x63\x6f\x6e\x64\x73','\x67\x65\x74\x44\x61','\u811a\u672c\u7248\u672c\u662f','\x62\x54\x73\x67\x69','\x77\x61\x69\x2f\x69','\x67\x6a\x41\x77\x25','\x65\x6e\x74\x5f\x6b','\x45\x6d\x70\x34\x56','\x6e\x64\x5f\x70\x61','\x4a\x54\x71\x50\x77','\x45\x7a\x6d\x76\x76','\x31\x67\x78\x4a\x58','\x43\x57\x55\x44\x71','\x4e\x66\x48\x6d\x44','\x6c\x6f\x61\x64\x64','\x42\x63\x79\x43\x4b','\x51\x63\x57\x62\x55','\x65\x72\x72\x6f\x72','\x50\x61\x45\x4b\x62','\x52\x48\x6a\x4f\x6f','\x70\x61\x70\x69\x5f','\x6c\x68\x64\x67\x73','\x57\x58\x58\x51\x4f','\x6c\x62\x46\x4f\x52','\x31\x30\x45\x59\x65\x4f\x47\x42','\x35\x34\x65\x65\x63','\x42\x33\x69\x56\x35','\x66\x59\x68\x79\x35','\x6e\x61\x6d\x65','\x2c\x22\x74\x61\x73','\x64\x61\x69\x6c\x79','\u8bf7\u68c0\u67e5\u81ea\u8eab','\x4f\x78\x55\x64\x79','\x51\x49\x78\x69\x77','\uff0c\u9ed8\u8ba4\u63d0\u73b0','\x61\x39\x38\x63\x33','\x6e\x65\x65\x64\x52','\x69\x6d\x65\x72\x2d','\x6e\x74\x65\x6e\x74','\x6d\x6f\x62\x69\x6c','\x5d\u6210\u529f','\x64\x61\x74\x61\x46','\x46\x44\x72\x47\x41','\x61\x59\x77\x42\x44','\x5f\x6d\x73\x67','\x74\x61\x73\x6b','\x6f\x7a\x79\x7a\x4f','\x65\x72\x3d\x31\x30','\u72b6\u6001\u5931\u8d25\uff0c','\x6d\x62\x66\x62\x32','\x61\x59\x56\x7a\x4f','\x6f\x4c\x43\x4f\x4e','\u7248\u672c\uff1a','\x56\x4a\x53\x45\x76','\u5374\u8fd8\u6709','\x43\x62\x59\x69\x41','\x42\x44\x50\x54\x79','\x61\x64\x49\x6e\x66','\x65\x44\x4e\x50\x51','\x63\x35\x33\x34\x66','\x33\x39\x30\x33\x68\x43\x76\x44\x65\x67','\x6e\x74\x44\x61\x79','\x68\x79\x67\x59\x66','\x6a\x52\x68\x4f\x54','\x41\x64\x50\x61\x72','\x72\x69\x70\x74','\x4c\x74\x5a\x77\x67','\x5d\u67e5\u8be2\u5b9d\u7bb1','\x64\x65\x66\x37\x62','\x69\x37\x4a\x33\x77','\x6e\x67\x2e\x6e\x65','\x74\x73\x46\x32\x74','\x42\x61\x4c\x59\x63','\x69\x73\x51\x75\x61','\x70\x66\x3d\x41\x4e','\x78\x57\x56\x66\x70','\x6b\x5f\x6e\x61\x6d','\x69\x32\x2e\x65\x2e','\x7a\x43\x4a\x75\x6e','\x64\x30\x62\x34\x32','\x62\x52\x68\x50\x46','\x72\x74\x54\x69\x6d','\x39\x31\x66\x32\x62','\x65\x65\x63\x64\x65','\x37\x39\x61\x39\x39','\x65\x4c\x66\x58\x6f','\x65\x72\x49\x6e\x66','\x77\x2e\x6b\x75\x61','\x74\x69\x6d\x65\x6f','\x31\x65\x65\x37\x34','\x48\x69\x56\x63\x65','\x65\x78\x74','\x59\x4b\x48\x71\x36','\x72\x65\x73\x75\x6c','\x6b\x73\x50\x61\x79','\x71\x5f\x74\x79\x70','\x30\x7c\x31\x7c\x34','\x6d\x65\x72\x49\x6e','\x36\x7c\x33\x7c\x31','\x69\x74\x79\x52\x65','\x22\x2c\x22\x61\x6d','\x5d\u51c6\u5907\u6700\u5927','\x5a\x34\x6e\x6f\x66','\x25\x32\x46\x35\x6b','\x55\x4c\x43\x6b\x65','\x3a\x2f\x2f\x77\x77','\x54\x65\x4b\x43\x73','\x6f\x70\x65\x6e\x42','\x69\x6e\x64\x65\x78','\u989d\u5916\u5956\u52b1\u89c6','\x67\x65\x74\x4d\x6f','\x25\x32\x42\x5a\x36','\x65\x73\x73\x49\x64','\x35\x33\x36\x37\x39','\x4d\x58\x7a\x6c\x67','\x6b\x73\x41\x64\x52','\x6f\x4e\x59\x6b\x58','\x2c\x22\x70\x61\x67','\x47\x46\x48\x6f\x70','\x6b\x54\x6f\x6b\x65','\x6f\x70\x65\x6e\x2d','\x5d\u67e5\u8be2\u7b7e\u5230','\x70\x6f\x70\x75\x70','\x2f\x72\x65\x73\x74','\x74\x75\x76\x77\x78','\x65\x6e\x65\x22\x3a','\x72\x45\x43\x67\x70','\x74\x2f\x7a\x74\x2f','\x70\x61\x79\x54\x79','\x6a\x69\x72\x72\x4a','\x72\x65\x42\x6f\x78','\x64\x69\x61\x53\x63','\x67\x65\x5f\x74\x79','\x6d\x38\x4c\x6c\x67','\x73\x75\x62\x73\x74','\x6e\x74\x5f\x67\x72','\x74\x61\x72\x74\x54','\x2c\x22\x73\x75\x62','\x71\x62\x7a\x6b\x79','\x66\x66\x59\x31\x38','\x6d\x2f\x72\x65\x73','\x70\x6f\x72\x74','\x61\x64\x3f\x6b\x70','\x34\x36\x38\x65\x39','\x75\x73\x68\x3f\x70','\x78\x53\x78\x52\x61','\x71\x49\x48\x76\x78','\x63\x61\x74\x63\x68','\x48\x70\x78\x6f\x5a','\x63\x61\x73\x68\x53','\x68\x69\x6e\x74\x73','\x4e\x66\x73\x65\x78','\x43\x45\x4e\x54\x49','\x68\x65\x61\x64\x65','\x5a\x52\x52\x54\x63','\x44\x56\x55\x25\x32','\x6f\x6b\x69\x65\x53','\x79\x6e\x63','\x74\x69\x76\x69\x74','\x71\x4f\x43\x42\x41','\x6a\x4a\x55\x56\x6e','\x6d\x57\x76\x61\x6f','\x74\x61\x43\x71\x5a','\x42\x70\x6d\x6d\x7a','\u672a\u627e\u5230\x43\x4b','\x33\x3b\x20\x6b\x75','\x6f\x75\x2e\x63\x6f','\x57\x52\x71\x38\x76','\x63\x72\x65\x61\x74','\x68\x53\x74\x61\x74','\x48\x56\x71\x67\x75','\x57\x25\x32\x42\x45','\x42\x5a\x25\x32\x46','\x63\x6f\x64\x65\x3d','\x33\x39\x64\x66\x35','\x2e\x63\x6f\x64\x69','\x6a\x43\x56\x4a\x51','\x65\x61\x36\x31\x30','\x53\x34\x52\x33\x7a','\x74\x69\x6d\x65','\x2d\x75\x72\x6c','\x5a\x6e\x59\x47\x75','\x6f\x6f\x6b\x69\x65','\x42\x76\x25\x32\x46','\x64\x2f\x69\x6e\x66','\x45\x6b\x4f\x4c\x6c','\x65\x6e\x63\x44\x61','\x6a\x51\x41\x63\x39','\x7a\x57\x6b\x74\x79','\x66\x4a\x47\x66\x74','\x33\x65\x63\x35\x66','\x3a\x2f\x2f\x65\x6e','\x64\x2f\x74\x61\x73','\x42\x56\x25\x32\x42','\x47\x56\x51\x53\x78','\x6d\x6a\x6d\x77\x58','\x74\x70\x73\x25\x33','\x72\x61\x77\x54\x69','\x66\x69\x6e\x61\x6c','\x5a\x47\x45\x65\x70','\x67\x65\x74\x53\x63','\x7c\x33\x7c\x36\x7c','\x6c\x6c\x59\x65\x61','\x41\x68\x4a\x62\x5a','\x72\x65\x70\x6c\x61','\x73\x69\x67\x6e\x32','\x20\ud83d\udd5b\x20','\x56\x56\x63\x54\x61','\x6c\x6c\x69\x73\x65','\x36\x34\x63\x34\x62','\x5d\u62bd\u5956\u9875\u5b9a','\x3d\x4b\x55\x41\x49','\x41\x42\x43\x44\x45','\x79\x6e\x74\x4c\x69','\x6c\x69\x6d\x69\x74','\x73\x6c\x4f\x6f\x30','\x77\x4c\x70\x71\x52','\x73\x65\x6e\x64\x4e','\x42\x39\x50\x37\x5a','\x68\x51\x42\x47\x57','\x4f\x49\x44\x5f\x50','\x57\x57\x6d\x73\x37','\x73\x63\x72\x69\x70','\x78\x25\x32\x42\x44','\x73\x65\x74\x6a\x73','\x77\x65\x63\x68\x61','\x2c\x22\x65\x78\x74','\x6a\x72\x4b\x58\x41','\x68\x35\x2f\x70\x72','\x26\x73\x69\x67\x6e','\x4d\x68\x76\x31\x55','\x73\x69\x67\x6e\x49','\x49\x66\x4b\x49\x77','\x5a\x44\x71\x74\x74','\x63\x77\x7a\x76\x57','\u8d26\u53f7\u7ed1\u5b9a\u60c5','\x6e\x42\x5a\x6a\x4e','\x20\u767b\u5f55\x20\x3d','\x66\x37\x63\x37\x39','\u5931\u8d25\uff1a','\x49\x6e\x66\x6f\x22','\x79\x42\x43\x6e\x55','\x50\x75\x73\x68\x44','\x39\x64\x66\x37\x38','\x61\x73\x73\x69\x67','\x4e\x47\x75\x69\x5a','\x6c\x65\x4f\x72\x44','\x57\x38\x73\x42\x42','\x67\x65\x74\x48\x6f','\x77\x51\x52\x6b\x52','\x4d\x6c\x57\x42\x43','\x63\x77\x64','\x72\x59\x74\x69\x4d','\x46\x47\x63\x70\x59','\x44\x61\x74\x61','\x2e\x31\x2e\x33\x30','\x6e\x66\x6f','\x35\x47\x75\x39\x4d','\x77\x72\x69\x74\x65','\x74\x6b\x4c\x48\x67','\x61\x70\x70\x6c\x69','\x67\x64\x5a\x71\x67','\x47\x76\x50\x78\x48','\x65\x79\x3d\x33\x63','\x67\x65\x74\x53\x65','\x66\x30\x31\x32\x33','\u5df2\u7ed1\u5b9a\u5fae\u4fe1','\x65\x72\x43\x66\x67','\x41\x25\x32\x46\x25','\x75\x2e\x63\x6f\x6d','\x46\x4a\x4c\x49\x5a','\x6f\x75\x6e\x74','\x78\x62\x33\x6d\x4c','\x4f\x55\x3b\x20\x6b','\x54\x73\x6b\x47\x71','\x20\u83b7\u53d6\u7b2c\x31','\x6a\x55\x6a\x4e\x43','\x57\x48\x4a\x72\x46','\x71\x59\x4c\x6d\x42','\x72\x65\x77\x61\x72','\x7c\x32\x7c\x30','\x43\x73\x74\x70\x49','\x72\x63\x6f\x64\x65','\x6c\x4d\x30\x58\x36','\x34\x63\x30\x30\x37','\x69\x66\x79','\x67\x65\x49\x64','\x34\x37\x66\x77\x56','\x31\x63\x66\x33\x63','\x39\x52\x68\x30\x66','\x5d\u9886\u53d6\u62bd\u5956','\x73\x5a\x4d\x58\x69','\x6b\x53\x71\x57\x74','\x6f\x75\x70\x5f\x6b','\x69\x2e\x6b\x75\x61','\x67\x65\x74','\x74\x69\x6f\x6e\x2f','\x65\x3d\x69\x6e\x69','\x53\x69\x67\x6e\x49','\x20\x61\x70\x70\x76','\x74\x79\x5a\x41\x53','\x74\x68\x65\x6e','\u6700\u5927\u5316\u63d0\u73b0','\x77\x6e\x31\x30','\x65\x22\x3a','\x67\x65\x2e\x6b\x75','\x70\x61\x67\x65\x49','\x6c\x6c\x73\x69\x64','\x56\x45\x5f\x43\x41','\x72\x75\x6e\x53\x63','\x5d\u901b\u8857\u83b7\u5f97','\x4a\x5a\x54\x32\x77','\x41\x31\x62\x5a\x4f','\x4d\x41\x56\x59\x76','\x6b\x4d\x71\x30\x31','\x6c\x63\x5a\x72\x4c','\x44\x48\x4d\x49\x68','\x38\x32\x63\x62\x64','\x62\x6c\x4a\x6b\x31','\x2e\x6b\x75\x61\x69','\x6b\x75\x61\x69\x73','\x44\x53\x76\x75\x58','\x73\x75\x62\x54\x69','\x2e\x31\x2f','\x31\x51\x4f\x6a\x6b','\x70\x4e\x6c\x46\x6e','\x72\x6e\x61\x6c\x2f','\x68\x51\x65\x75\x4c','\x5d\u4eca\u5929\u5f00\u5b9d','\x31\x30\x2e\x31\x3b','\u4fe1\u606f\u5931\u8d25\uff1a','\x49\x4b\x41\x42\x65','\x69\x64\x3d\x26\x62','\x74\x5f\x62\x69\x6e','\x6b\x73\x59\x76\x54','\x22\x2c\x22\x6d\x65','\x4c\x33\x78\x50\x7a','\x74\x45\x4f\x43\x48','\x41\x64\x52\x65\x77','\x47\x4c\x67\x6c\x4d','\x74\x2f\x77\x69\x74','\x74\x72\x69\x6d','\x4d\x53\x39\x51\x74','\x63\x68\x3d\x26\x62','\x69\x4b\x61\x6d\x61','\x38\x39\x33\x65\x35','\x6e\x74\x68','\x5d\u6ca1\u6709\u83b7\u53d6','\x52\x45\x50\x78\x57','\u6267\u884c\u63d0\u73b0','\x57\x41\x41\x58\x4e','\x4d\x66\x45\x75\x59','\x36\x66\x35\x31\x31','\x64\x66\x77\x61\x79','\x6f\x62\x6a\x65\x63','\x42\x30\x67\x6e\x78','\u5217\u8868\u5931\u8d25\uff1a','\x49\x54\x51\x66\x50','\x71\x6a\x49\x48\x48','\x66\x72\x6f\x6d\x43','\x61\x72\x64','\x47\x4e\x73\x5a\x25','\x77\x43\x4c\x64\x52','\x35\x66\x64\x65\x35','\x63\x41\x5a\x72\x50','\x73\x65\x74\x43\x6f','\x68\x26\x65\x78\x74','\uff0c\u6bcf\u6b21\u8fd0\u884c','\x69\x6e\x76\x69\x74','\x52\x64\x34\x64\x4b','\x63\x6c\x74\x50\x64','\x56\x37\x65\x63\x67','\x63\x53\x75\x6d\x46','\x47\x76\x68\x71\x46','\x69\x76\x47\x74\x63','\x76\x31\x2f\x72\x65','\x63\x65\x3d\x49\x4e','\x69\x73\x53\x75\x72','\u73b0\u8d26\u53f7\uff0c\u4e0d','\x6d\x4e\x59\x66\x68','\x57\x53\x64\x71\x70','\x32\x42\x78\x39\x35','\x54\x69\x6d\x65','\x43\x65\x6b\x4a\x4b','\x31\x34\x38\x38\x48\x66\x74\x78\x50\x6f','\x55\x4f\x44\x7a\x56','\x79\x5f\x62\x6f\x78','\x62\x6f\x78','\x20\u901a\u77e5\u53d1\u9001','\x6e\x33\x4c\x33\x61','\x64\x6a\x70\x6d\x6c','\x56\x48\x71\x4d\x45','\x4c\x70\x58\x45\x57','\x68\x74\x74\x70\x73','\x2f\x65\x78\x74\x65','\x64\x6e\x72\x69\x50','\x65\x78\x65\x63','\x6f\x75\x6e\x74\x5f','\x65\x73\x74\x2f\x6e','\x33\x34\x32\x5a\x66\x44\x50\x6b\x74','\x69\x6f\x6e','\x61\x6d\x6f\x75\x6e','\x50\x43\x4c\x4c\x42','\x6f\x76\x69\x64\x65','\x6b\x2e\x63\x6f\x6d','\x50\x49\x43\x72\x6f','\x50\x51\x52\x53\x54','\x74\x68\x65\x6d\x65','\x73\x4c\x62\x47\x67','\x36\x62\x30\x65\x30','\x64\x43\x65\x78\x5a','\x75\x72\x65\x42\x6f','\x2d\x63\x6f\x6f\x6b','\x6c\x37\x63\x6e\x25','\x70\x61\x66\x41\x76','\x26\x66\x65\x6e\x3d','\x77\x6e\x32','\x53\x55\x43\x43\x45','\x42\x77\x56\x76\x44','\x67\x6f\x74','\x31\x7c\x33\x7c\x34','\x50\x61\x72\x61\x6d','\x72\x77\x58\x64\x33','\x63\x65\x69\x6c','\x73\x53\x79\x6e\x63','\x37\x32\x39\x31\x76','\x73\x65\x74\x76\x61','\x67\x6e\x49\x6e\x66','\x61\x6d\x65','\x67\x6f\x6c\x64\x4e','\x6f\x41\x6f\x6b\x66','\x58\x65\x44\x44\x6c','\x0a\x3d\x3d\x3d\x3d','\x74\x61\x73\x6b\x52','\x26\x74\x6f\x74\x61','\x55\x72\x6c','\x6a\x6f\x69\x6e','\x61\x64\x31','\x52\x5a\x71\x63\x6c','\x3d\x71\x72\x63\x6f','\x70\x71\x77\x6e\x77','\x44\x6d\x5a\x5a\x43','\x63\x66\x74\x49\x4c','\x69\x73\x41\x72\x72','\x48\x57\x59\x4d\x48','\x6d\x42\x47\x79\x4b','\x34\x35\x36\x37\x38','\x2c\x22\x70\x6f\x73','\u975e\u63d0\u73b0\u65f6\u95f4','\x65\x51\x38\x71\x5a','\x66\x67\x6c\x68\x6f','\x74\x79\x70\x65','\x50\x36\x6f\x37\x64','\x54\x32\x77\x25\x32','\x20\x3d\x3d\x3d\x3d','\x63\x6c\x30\x65\x39','\x74\x72\x65\x61\x73','\x73\x74\x61\x74\x75','\x61\x6b\x65','\x44\x61\x6a\x65\x61','\x61\x73\x6b\x2f\x6c','\x69\x36\x35\x7a\x76','\x7b\x22\x63\x72\x65','\x38\x4f\x30\x46\x61','\x65\x43\x74\x33\x52','\x69\x6d\x65\x72\x54','\x44\x4e\x4a\x4b\x57','\x45\x4f\x54\x79\x59','\x62\x6f\x64\x79','\x64\x70\x57\x30\x39','\x53\x48\x4f\x55\x26','\x64\x43\x6f\x64\x65','\x72\x65\x61\x64','\x64\x4f\x73\x5a\x71','\x30\x33\x64\x37\x34','\x65\x49\x6e\x66\x6f','\x6b\x73\x43\x6f\x6f','\x67\x65\x74\x4e\x69','\x3d\x3d\x3d\x3d\ud83d\udce3','\x50\x69\x55\x74\x34','\x3d\x6c\x69\x67\x68','\x6f\x42\x70\x4d\x68','\x67\x44\x68\x65\x6b','\x32\x36\x33\x64\x38','\x73\x65\x74\x2d\x63','\x63\x6f\x75\x72\x61','\x4b\x55\x41\x49\x53','\x2f\x72\x65\x6e\x65','\x4c\x61\x75\x6e\x63','\x65\x63\x74','\x73\x68\x61\x72\x65','\x72\x69\x70\x74\x69','\x42\x72\x49\x53\x30','\x6e\x5f\x66\x65\x6e','\x64\x65\x64','\x3a\x2f\x2f\x6c\x65','\x73\x65\x6e\x64','\x65\x78\x69\x73\x74','\x67\x36\x68\x74\x39','\x5d\u67e5\u8be2\u8d26\u53f7','\x53\x48\x58\x68\x76','\x75\x6e\x6b\x6e\x6f','\x77\x6e\x38','\x73\x51\x51\x6c\x7a','\x6c\x6f\x67\x45\x72','\x61\x4e\x41\x4a\x7a','\x56\x68\x51\x6d\x65','\x66\x43\x4d\x78\x63','\x3d\x41\x4e\x44\x52','\x64\x69\x64\x3d\x41','\x65\x65\x71\x66\x54','\x74\x5f\x6e\x69\x63','\x62\x58\x78\x46\x4c','\x34\x32\x34\x37\x66','\x48\x4f\x4e\x45\x26','\x47\x49\x54\x48\x55','\x63\x6b\x6a\x61\x72','\x74\x2f\x72\x2f\x67','\x64\x5f\x69\x6e\x66','\x20\x76\x65\x72\x3d','\u672a\u77e5\u89c6\u9891','\x74\x61\x73\x6b\x4c','\x73\x72\x4e\x77\x64','\x36\x31\x35\x36\x33','\x47\x6e\x45\x70\x76','\x53\x4b\x4e\x55\x50','\x61\x64\x42\x74\x74','\u63d0\u73b0\u65f6\u95f4\uff0c','\x63\x6f\x6e\x74\x65','\x59\x79\x52\x67\x7a','\x74\x6f\x75\x67\x68','\x61\x72\x61\x6d\x73','\x67\x65\x74\x54\x69','\x43\x73\x72\x68\x51','\x6c\x75\x63\x6b\x64'];_0x46e9=function(){return _0x2dd9f0;};return _0x46e9();}function _0xc3223b(_0xab2d9e){const _0x10139c=_0x2fc758,_0x503658={};_0x503658[_0x10139c(0x3cc)]=function(_0x1e2abc,_0x42dd65){return _0x1e2abc==_0x42dd65;},_0x503658[_0x10139c(0x2d0)]='\x6f\x62\x6a\x65\x63'+'\x74';const _0x951a24=_0x503658;try{if(_0x951a24[_0x10139c(0x3cc)](typeof JSON[_0x10139c(0x2a3)](_0xab2d9e),_0x951a24[_0x10139c(0x2d0)]))return!![];else console[_0x10139c(0x230)](_0xab2d9e);}catch(_0x16aadb){return console[_0x10139c(0x230)](_0x16aadb),console[_0x10139c(0x230)](_0x10139c(0x40f)+'\u6570\u636e\u4e3a\u7a7a\uff0c'+_0x10139c(0x42f)+_0x10139c(0x404)+'\u51b5'),![];}}function _0x1d445f(_0x12a5dd,_0x8a3805){const _0x30b441=_0x2fc758,_0x273ea0={};_0x273ea0['\x56\x68\x51\x6d\x65']=function(_0x3c7436,_0x1fc955){return _0x3c7436<_0x1fc955;};const _0x17b1ba=_0x273ea0;return _0x17b1ba[_0x30b441(0x60a)](_0x12a5dd,_0x8a3805)?_0x12a5dd:_0x8a3805;}function _0x24d247(_0x3f9de2,_0x251d76){const _0x117838=_0x2fc758,_0x2a99fb={};_0x2a99fb[_0x117838(0x307)]=function(_0x1bb81a,_0x477407){return _0x1bb81a<_0x477407;};const _0x37b0b0=_0x2a99fb;return _0x37b0b0[_0x117838(0x307)](_0x3f9de2,_0x251d76)?_0x251d76:_0x3f9de2;}function _0x33670f(_0x599334,_0x36d680,_0x2432dd='\x30'){const _0x3409d8=_0x2fc758,_0x593718={'\x71\x62\x7a\x6b\x79':function(_0x1beff2,_0x429366){return _0x1beff2(_0x429366);},'\x55\x53\x64\x4d\x64':function(_0x2da7a3,_0x4a18f8){return _0x2da7a3-_0x4a18f8;}};let _0x3a41d0=_0x593718[_0x3409d8(0x49a)](String,_0x599334),_0xb6c6a7=_0x36d680>_0x3a41d0[_0x3409d8(0x2bd)+'\x68']?_0x593718['\x55\x53\x64\x4d\x64'](_0x36d680,_0x3a41d0['\x6c\x65\x6e\x67\x74'+'\x68']):-0xb*0x33d+0x2501+0x162*-0x1,_0x43e2f2='';for(let _0x3ee4cc=-0x1*0xcad+0xe9*-0x20+0x29cd;_0x3ee4cc<_0xb6c6a7;_0x3ee4cc++){_0x43e2f2+=_0x2432dd;}return _0x43e2f2+=_0x3a41d0,_0x43e2f2;}function _0x53e622(_0x29877f=0x1d77+0x1a0*0xc+0x7*-0x6fd){const _0x59f850=_0x2fc758,_0x59f856={};_0x59f856[_0x59f850(0x658)]=function(_0x3f1c9e,_0x2a6993){return _0x3f1c9e<_0x2a6993;};const _0xa6c58=_0x59f856;let _0x1f356c='\x61\x62\x63\x64\x65'+_0x59f850(0x519)+_0x59f850(0x5ce)+'\x39',_0x4b0e00=_0x1f356c[_0x59f850(0x2bd)+'\x68'],_0x366c7f='';for(i=0x6d8+-0x2035+0x2b*0x97;_0xa6c58['\x42\x49\x56\x71\x56'](i,_0x29877f);i++){_0x366c7f+=_0x1f356c['\x63\x68\x61\x72\x41'+'\x74'](Math[_0x59f850(0x35b)](Math['\x72\x61\x6e\x64\x6f'+'\x6d']()*_0x4b0e00));}return _0x366c7f;}var _0x5cc8b5={'\x5f\x6b\x65\x79\x53\x74\x72':_0x2fc758(0x4e4)+_0x2fc758(0x3bc)+_0x2fc758(0x69e)+_0x2fc758(0x5a6)+'\x55\x56\x57\x58\x59'+_0x2fc758(0x6aa)+'\x65\x66\x67\x68\x69'+'\x6a\x6b\x6c\x6d\x6e'+_0x2fc758(0x29e)+_0x2fc758(0x48c)+'\x79\x7a\x30\x31\x32'+_0x2fc758(0x39b)+_0x2fc758(0x27f),'\x65\x6e\x63\x6f\x64\x65':function(_0x441014){const _0x1ec60d=_0x2fc758,_0x4aa6c8={'\x6a\x51\x66\x62\x77':'\x33\x7c\x34\x7c\x32'+_0x1ec60d(0x64c)+'\x35','\x4b\x4c\x6d\x4d\x6a':function(_0x481577,_0x4b58b1){return _0x481577<_0x4b58b1;},'\x79\x43\x4b\x66\x4c':_0x1ec60d(0x472)+_0x1ec60d(0x36d)+_0x1ec60d(0x6ad)+'\x7c\x35','\x74\x51\x70\x4f\x7a':function(_0x5088f4,_0x24d836){return _0x5088f4>>_0x24d836;},'\x6a\x6d\x49\x69\x4d':function(_0x1b64e6,_0xc19d55){return _0x1b64e6&_0xc19d55;},'\x41\x44\x78\x51\x65':function(_0x320b8d,_0xaed0d1){return _0x320b8d<<_0xaed0d1;},'\x4d\x4a\x4c\x7a\x63':function(_0x46ff92,_0x26dd8e){return _0x46ff92+_0x26dd8e;},'\x76\x62\x71\x74\x5a':function(_0x42bdd8,_0xf3f8f4){return _0x42bdd8+_0xf3f8f4;},'\x6d\x57\x76\x61\x6f':function(_0x55ca60,_0x5188e3){return _0x55ca60|_0x5188e3;},'\x47\x43\x79\x47\x62':function(_0x250323,_0x2234b2){return _0x250323(_0x2234b2);}},_0x580e7a=_0x4aa6c8['\x6a\x51\x66\x62\x77'][_0x1ec60d(0x660)]('\x7c');let _0xe6dd33=0x5e6+0x221f+-0x2805;while(!![]){switch(_0x580e7a[_0xe6dd33++]){case'\x30':_0x441014=_0x5cc8b5[_0x1ec60d(0x272)+_0x1ec60d(0x677)+'\x64\x65'](_0x441014);continue;case'\x31':while(_0x4aa6c8[_0x1ec60d(0x3e4)](_0x14cfa4,_0x441014['\x6c\x65\x6e\x67\x74'+'\x68'])){const _0x35f05d=_0x4aa6c8[_0x1ec60d(0x6a0)]['\x73\x70\x6c\x69\x74']('\x7c');let _0x4129ae=-0xbe9+-0x13d0+0x1fb9;while(!![]){switch(_0x35f05d[_0x4129ae++]){case'\x30':_0x55a4ba=_0x4aa6c8[_0x1ec60d(0x664)](_0x4644e9,-0x2*0x11b+-0x101f+0x1257);continue;case'\x31':_0x59e1f5=_0x441014[_0x1ec60d(0x232)+_0x1ec60d(0x273)](_0x14cfa4++);continue;case'\x32':_0x57b658=_0x4aa6c8['\x6a\x6d\x49\x69\x4d'](_0x59e1f5,0x267d*-0x1+0x52b+0x295*0xd);continue;case'\x33':_0x4d70de=_0x441014['\x63\x68\x61\x72\x43'+_0x1ec60d(0x273)](_0x14cfa4++);continue;case'\x34':_0x1965a5=_0x4aa6c8[_0x1ec60d(0x3c6)](_0x4aa6c8['\x6a\x6d\x49\x69\x4d'](_0x4644e9,0x1edd*-0x1+0x3*0x7e2+-0x4a*-0x19),-0x1c6c+-0x1*-0x1ff1+0x12b*-0x3)|_0x4aa6c8[_0x1ec60d(0x664)](_0x4d70de,-0x15b*0xd+-0x1f*-0xd0+-0x78d);continue;case'\x35':_0x30c08a=_0x4aa6c8[_0x1ec60d(0x2db)](_0x4aa6c8[_0x1ec60d(0x2db)](_0x4aa6c8[_0x1ec60d(0x3f2)](_0x30c08a+this['\x5f\x6b\x65\x79\x53'+'\x74\x72']['\x63\x68\x61\x72\x41'+'\x74'](_0x55a4ba),this[_0x1ec60d(0x378)+'\x74\x72']['\x63\x68\x61\x72\x41'+'\x74'](_0x1965a5)),this[_0x1ec60d(0x378)+'\x74\x72'][_0x1ec60d(0x352)+'\x74'](_0x575eb9)),this[_0x1ec60d(0x378)+'\x74\x72'][_0x1ec60d(0x352)+'\x74'](_0x57b658));continue;case'\x36':_0x4644e9=_0x441014[_0x1ec60d(0x232)+_0x1ec60d(0x273)](_0x14cfa4++);continue;case'\x37':_0x575eb9=_0x4aa6c8[_0x1ec60d(0x4b1)](_0x4aa6c8[_0x1ec60d(0x3c6)](_0x4d70de&0x25a0+0x144c+-0x39dd,0xea7+-0x1164+0x2bf),_0x4aa6c8['\x74\x51\x70\x4f\x7a'](_0x59e1f5,-0x2269+-0xefd+-0x316c*-0x1));continue;case'\x38':if(_0x4aa6c8[_0x1ec60d(0x3fd)](isNaN,_0x4d70de))_0x575eb9=_0x57b658=0x16d*-0x1+-0x2022+0x21cf;else _0x4aa6c8[_0x1ec60d(0x3fd)](isNaN,_0x59e1f5)&&(_0x57b658=0x7*0x20e+-0x31a+-0xb08);continue;}break;}}continue;case'\x32':var _0x14cfa4=0x68d+-0xbe8+0x55b;continue;case'\x33':var _0x30c08a='';continue;case'\x34':var _0x4644e9,_0x4d70de,_0x59e1f5,_0x55a4ba,_0x1965a5,_0x575eb9,_0x57b658;continue;case'\x35':return _0x30c08a;}break;}},'\x64\x65\x63\x6f\x64\x65':function(_0x4eedd3){const _0x3f7e11=_0x2fc758,_0x46d0bd={};_0x46d0bd['\x6f\x4c\x43\x4f\x4e']=_0x3f7e11(0x225)+_0x3f7e11(0x356)+_0x3f7e11(0x6be),_0x46d0bd[_0x3f7e11(0x3ff)]=function(_0x23036d,_0x2786db){return _0x23036d<_0x2786db;},_0x46d0bd[_0x3f7e11(0x571)]=function(_0x251d60,_0xa49999){return _0x251d60<<_0xa49999;},_0x46d0bd[_0x3f7e11(0x1fd)]=function(_0x13c25f,_0x2c1c6a){return _0x13c25f>>_0x2c1c6a;},_0x46d0bd['\x57\x58\x58\x51\x4f']=function(_0x17428f,_0x559490){return _0x17428f|_0x559490;},_0x46d0bd[_0x3f7e11(0x45e)]=function(_0xaa4eee,_0x11e2f5){return _0xaa4eee&_0x11e2f5;},_0x46d0bd[_0x3f7e11(0x58b)]=function(_0x15c65a,_0x1ff053){return _0x15c65a|_0x1ff053;},_0x46d0bd[_0x3f7e11(0x6c9)]=function(_0xe74c69,_0x1fdc18){return _0xe74c69<<_0x1fdc18;},_0x46d0bd[_0x3f7e11(0x501)]=function(_0x2c3a35,_0x3e295d){return _0x2c3a35&_0x3e295d;},_0x46d0bd[_0x3f7e11(0x4ba)]=function(_0x1bb8b8,_0x52c8a1){return _0x1bb8b8+_0x52c8a1;},_0x46d0bd[_0x3f7e11(0x423)]=function(_0x49d0ba,_0x26ad3d){return _0x49d0ba!=_0x26ad3d;};const _0x13a1f7=_0x46d0bd,_0x5845d5=_0x13a1f7[_0x3f7e11(0x443)]['\x73\x70\x6c\x69\x74']('\x7c');let _0x2a39d8=-0x164b*0x1+-0x16e8+-0x18f*-0x1d;while(!![]){switch(_0x5845d5[_0x2a39d8++]){case'\x30':var _0x42e3a3,_0x4258ab,_0x30fe5f;continue;case'\x31':var _0x2134b3=-0xbbb+0x82*0x42+-0xa9*0x21;continue;case'\x32':var _0x5def6a='';continue;case'\x33':_0x4eedd3=_0x4eedd3['\x72\x65\x70\x6c\x61'+'\x63\x65'](/[^A-Za-z0-9+/=]/g,'');continue;case'\x34':_0x5def6a=_0x5cc8b5[_0x3f7e11(0x272)+_0x3f7e11(0x368)+'\x64\x65'](_0x5def6a);continue;case'\x35':var _0x5dd7bf,_0x46a4b9,_0xe52caf,_0x5c0230;continue;case'\x36':return _0x5def6a;case'\x37':while(_0x13a1f7['\x74\x48\x52\x54\x64'](_0x2134b3,_0x4eedd3[_0x3f7e11(0x2bd)+'\x68'])){_0x5dd7bf=this[_0x3f7e11(0x378)+'\x74\x72'][_0x3f7e11(0x47c)+'\x4f\x66'](_0x4eedd3[_0x3f7e11(0x352)+'\x74'](_0x2134b3++)),_0x46a4b9=this['\x5f\x6b\x65\x79\x53'+'\x74\x72'][_0x3f7e11(0x47c)+'\x4f\x66'](_0x4eedd3[_0x3f7e11(0x352)+'\x74'](_0x2134b3++)),_0xe52caf=this[_0x3f7e11(0x378)+'\x74\x72'][_0x3f7e11(0x47c)+'\x4f\x66'](_0x4eedd3[_0x3f7e11(0x352)+'\x74'](_0x2134b3++)),_0x5c0230=this[_0x3f7e11(0x378)+'\x74\x72'][_0x3f7e11(0x47c)+'\x4f\x66'](_0x4eedd3[_0x3f7e11(0x352)+'\x74'](_0x2134b3++)),_0x42e3a3=_0x13a1f7['\x64\x66\x77\x61\x79'](_0x5dd7bf,-0x71*0x49+0x23cb+-0x390)|_0x13a1f7['\x47\x46\x45\x55\x6a'](_0x46a4b9,0x1fa1*0x1+-0x12b9+-0xce4),_0x4258ab=_0x13a1f7[_0x3f7e11(0x426)](_0x13a1f7[_0x3f7e11(0x571)](_0x13a1f7[_0x3f7e11(0x45e)](_0x46a4b9,-0x511+0x14f8+-0xfd8),-0x2362+-0x1*-0x9eb+0x251*0xb),_0x13a1f7['\x47\x46\x45\x55\x6a'](_0xe52caf,-0x6*0x34b+-0x1*-0x4e1+-0x67*-0x25)),_0x30fe5f=_0x13a1f7[_0x3f7e11(0x58b)](_0x13a1f7[_0x3f7e11(0x6c9)](_0x13a1f7[_0x3f7e11(0x501)](_0xe52caf,-0x1302+0x150*0x4+-0xdc5*-0x1),0xe41*-0x2+-0x217*-0xf+-0x2d1*0x1),_0x5c0230),_0x5def6a=_0x13a1f7['\x48\x56\x71\x67\x75'](_0x5def6a,String[_0x3f7e11(0x577)+_0x3f7e11(0x37a)+'\x64\x65'](_0x42e3a3)),_0x13a1f7['\x52\x48\x6a\x4f\x6f'](_0xe52caf,-0x2a*0x1a+0x2*-0x23d+0x8fe)&&(_0x5def6a=_0x13a1f7[_0x3f7e11(0x4ba)](_0x5def6a,String['\x66\x72\x6f\x6d\x43'+_0x3f7e11(0x37a)+'\x64\x65'](_0x4258ab))),_0x5c0230!=0x71+0x12a*-0x1+0xf9&&(_0x5def6a=_0x13a1f7[_0x3f7e11(0x4ba)](_0x5def6a,String[_0x3f7e11(0x577)+_0x3f7e11(0x37a)+'\x64\x65'](_0x30fe5f)));}continue;}break;}},'\x5f\x75\x74\x66\x38\x5f\x65\x6e\x63\x6f\x64\x65':function(_0x3b3843){const _0x3e0b9a=_0x2fc758,_0x20fc7b={};_0x20fc7b[_0x3e0b9a(0x6e7)]=function(_0x2bdf3c,_0x5c49e0){return _0x2bdf3c<_0x5c49e0;},_0x20fc7b[_0x3e0b9a(0x1d0)]=function(_0x116636,_0xee3140){return _0x116636<_0xee3140;},_0x20fc7b[_0x3e0b9a(0x1d4)]=function(_0x266928,_0x15dd7a){return _0x266928>_0x15dd7a;},_0x20fc7b[_0x3e0b9a(0x4c9)]=function(_0x28bd46,_0x1a7408){return _0x28bd46<_0x1a7408;},_0x20fc7b[_0x3e0b9a(0x5c6)]=function(_0x35a4db,_0x3229d8){return _0x35a4db|_0x3229d8;},_0x20fc7b['\x48\x65\x41\x71\x44']=function(_0x4b5a67,_0x1e1d5a){return _0x4b5a67>>_0x1e1d5a;},_0x20fc7b['\x54\x65\x4b\x43\x73']=function(_0x1035f7,_0x1339e9){return _0x1035f7&_0x1339e9;},_0x20fc7b['\x51\x6e\x64\x54\x4a']=function(_0x470921,_0x530fc9){return _0x470921&_0x530fc9;};const _0x25493b=_0x20fc7b;_0x3b3843=_0x3b3843['\x72\x65\x70\x6c\x61'+'\x63\x65'](/rn/g,'\x6e');var _0x2b34f5='';for(var _0x1cf92a=0x1d0*0x10+0x1deb+0x1*-0x3aeb;_0x25493b[_0x3e0b9a(0x6e7)](_0x1cf92a,_0x3b3843[_0x3e0b9a(0x2bd)+'\x68']);_0x1cf92a++){var _0x5e040c=_0x3b3843['\x63\x68\x61\x72\x43'+_0x3e0b9a(0x273)](_0x1cf92a);if(_0x25493b[_0x3e0b9a(0x1d0)](_0x5e040c,0x1177+-0x127a*-0x1+-0x2371*0x1))_0x2b34f5+=String['\x66\x72\x6f\x6d\x43'+_0x3e0b9a(0x37a)+'\x64\x65'](_0x5e040c);else _0x25493b[_0x3e0b9a(0x1d4)](_0x5e040c,0xf*-0x130+0x2*-0x4c3+-0x947*-0x3)&&_0x25493b['\x45\x6b\x4f\x4c\x6c'](_0x5e040c,0x1*-0x189+0x17f*0xe+0x17*-0x7f)?(_0x2b34f5+=String[_0x3e0b9a(0x577)+_0x3e0b9a(0x37a)+'\x64\x65'](_0x25493b[_0x3e0b9a(0x5c6)](_0x25493b[_0x3e0b9a(0x663)](_0x5e040c,0xc16+-0x156e+0x95e),0x18e7+0x11de*-0x2+0xb95)),_0x2b34f5+=String['\x66\x72\x6f\x6d\x43'+'\x68\x61\x72\x43\x6f'+'\x64\x65'](_0x25493b[_0x3e0b9a(0x5c6)](_0x25493b[_0x3e0b9a(0x47a)](_0x5e040c,0x397*-0x5+-0xd5b*-0x1+0x15*0x3b),-0x6fb+0x4c9+0x2b2))):(_0x2b34f5+=String[_0x3e0b9a(0x577)+'\x68\x61\x72\x43\x6f'+'\x64\x65'](_0x25493b[_0x3e0b9a(0x5c6)](_0x25493b[_0x3e0b9a(0x663)](_0x5e040c,0x1e89*-0x1+0x2a4*0xa+0x42d*0x1),-0xc9d*0x3+-0x1b33*0x1+0x41ea)),_0x2b34f5+=String[_0x3e0b9a(0x577)+_0x3e0b9a(0x37a)+'\x64\x65'](_0x25493b['\x51\x6e\x64\x54\x4a'](_0x25493b[_0x3e0b9a(0x663)](_0x5e040c,0x1a9d+-0xab2+-0xfe5),-0x6*-0x66a+0x4bf+-0x2afc)|0x60d*-0x2+-0x8d1+0x156b),_0x2b34f5+=String['\x66\x72\x6f\x6d\x43'+'\x68\x61\x72\x43\x6f'+'\x64\x65'](_0x25493b[_0x3e0b9a(0x5c6)](_0x5e040c&-0x2453+0x1*0x59c+0x529*0x6,-0x1f4d+0x2247+0x2*-0x13d)));}return _0x2b34f5;},'\x5f\x75\x74\x66\x38\x5f\x64\x65\x63\x6f\x64\x65':function(_0x11c9de){const _0x572b62=_0x2fc758,_0x5ac755={};_0x5ac755[_0x572b62(0x21c)]=function(_0x197bd3,_0x33f298){return _0x197bd3<_0x33f298;},_0x5ac755[_0x572b62(0x28e)]=function(_0x34ad90,_0xfaf980){return _0x34ad90<_0xfaf980;},_0x5ac755[_0x572b62(0x319)]=function(_0x375766,_0x1af3e0){return _0x375766+_0x1af3e0;},_0x5ac755[_0x572b62(0x1c5)]=function(_0x4edcd9,_0x226102){return _0x4edcd9|_0x226102;},_0x5ac755[_0x572b62(0x58f)]=function(_0x561f63,_0x27435b){return _0x561f63<<_0x27435b;},_0x5ac755['\x76\x74\x4d\x48\x7a']=function(_0x3d37e4,_0x411abf){return _0x3d37e4&_0x411abf;},_0x5ac755[_0x572b62(0x383)]=function(_0x50867a,_0x1033a9){return _0x50867a&_0x1033a9;},_0x5ac755[_0x572b62(0x524)]=function(_0x103304,_0x36f85e){return _0x103304+_0x36f85e;},_0x5ac755['\x52\x55\x4f\x42\x73']=function(_0x51b15e,_0xcbd548){return _0x51b15e&_0xcbd548;},_0x5ac755[_0x572b62(0x522)]=function(_0x5b02d1,_0x5a61f5){return _0x5b02d1&_0x5a61f5;};const _0x4755d8=_0x5ac755,_0x27aa00=(_0x572b62(0x2f4)+_0x572b62(0x23e))[_0x572b62(0x660)]('\x7c');let _0x57a28c=0x215a+-0x4*0x5f9+-0x976;while(!![]){switch(_0x27aa00[_0x57a28c++]){case'\x30':var _0x1921cd=c1=c2=-0x1c37+0x409*-0x3+0x1*0x2852;continue;case'\x31':return _0x27faff;case'\x32':while(_0x4755d8[_0x572b62(0x21c)](_0x2f52fe,_0x11c9de[_0x572b62(0x2bd)+'\x68'])){_0x1921cd=_0x11c9de['\x63\x68\x61\x72\x43'+'\x6f\x64\x65\x41\x74'](_0x2f52fe);if(_0x4755d8[_0x572b62(0x28e)](_0x1921cd,-0x1193+0x1fd5+0x2*-0x6e1))_0x27faff+=String[_0x572b62(0x577)+_0x572b62(0x37a)+'\x64\x65'](_0x1921cd),_0x2f52fe++;else _0x1921cd>-0x1e00+-0x76*-0x2f+0x1d1*0x5&&_0x1921cd<-0xb2b+0x1*0xcca+-0x1*0xbf?(c2=_0x11c9de[_0x572b62(0x232)+'\x6f\x64\x65\x41\x74'](_0x4755d8['\x41\x4d\x7a\x72\x4f'](_0x2f52fe,0x12c5+-0x7d5*0x1+0x9*-0x137)),_0x27faff+=String[_0x572b62(0x577)+_0x572b62(0x37a)+'\x64\x65'](_0x4755d8[_0x572b62(0x1c5)](_0x4755d8[_0x572b62(0x58f)](_0x4755d8[_0x572b62(0x646)](_0x1921cd,-0x14f*0x4+-0x50f+0xa6a*0x1),-0xd4c+-0x1561+-0xbd*-0x2f),_0x4755d8[_0x572b62(0x383)](c2,0x1c4e+-0x1de7+0x1d8))),_0x2f52fe+=-0x1*-0x1f61+-0x1fe2+0x83):(c2=_0x11c9de[_0x572b62(0x232)+_0x572b62(0x273)](_0x4755d8[_0x572b62(0x524)](_0x2f52fe,0x1367+0xedb+0x4f*-0x6f)),c3=_0x11c9de[_0x572b62(0x232)+'\x6f\x64\x65\x41\x74'](_0x2f52fe+(0x3*0x764+-0x2*0xd3d+0x450)),_0x27faff+=String[_0x572b62(0x577)+_0x572b62(0x37a)+'\x64\x65'](_0x4755d8[_0x572b62(0x1c5)](_0x4755d8[_0x572b62(0x1c5)](_0x4755d8[_0x572b62(0x383)](_0x1921cd,-0x1542+0x796*0x2+0x625)<<-0x6ca+0xcf0+-0x61a,_0x4755d8[_0x572b62(0x58f)](_0x4755d8[_0x572b62(0x279)](c2,0xef+-0x6ea+0x63a),-0x1739+0x198a+-0x24b)),_0x4755d8[_0x572b62(0x522)](c3,0x2440+-0x1c*0xed+0x1*-0xa15))),_0x2f52fe+=0x23fb+-0x23*-0x9f+-0x39b5);}continue;case'\x33':var _0x2f52fe=0xb*-0x16+-0x20*-0xff+-0x1*0x1eee;continue;case'\x34':var _0x27faff='';continue;}break;}}};function _0x1f125f(_0x1cac09){const _0x84f7a3=_0x2fc758,_0x1c58f1={'\x44\x73\x69\x46\x4d':function(_0x5c2e45,_0xd9e43){return _0x5c2e45>>>_0xd9e43;},'\x63\x66\x74\x49\x4c':function(_0x479f5d,_0x3d2aac){return _0x479f5d&_0x3d2aac;},'\x57\x48\x4a\x72\x46':function(_0x269aee,_0x24387d){return _0x269aee&_0x24387d;},'\x42\x44\x50\x54\x79':function(_0x4237ec,_0x26fcb2){return _0x4237ec+_0x26fcb2;},'\x4a\x54\x6b\x57\x62':function(_0x4d1765,_0x21a6e3){return _0x4d1765&_0x21a6e3;},'\x68\x6d\x70\x7a\x4c':function(_0x59e852,_0x511359){return _0x59e852^_0x511359;},'\x6b\x53\x71\x57\x74':function(_0x14f9e7,_0x5c8393){return _0x14f9e7^_0x5c8393;},'\x50\x49\x43\x72\x6f':function(_0x271ed4,_0xf38327){return _0x271ed4|_0xf38327;},'\x45\x58\x79\x57\x4e':function(_0x4510e1,_0x16ddfe){return _0x4510e1^_0x16ddfe;},'\x57\x41\x49\x6c\x56':function(_0x2e7fe7,_0x4f3372){return _0x2e7fe7^_0x4f3372;},'\x61\x6b\x74\x52\x6d':function(_0x4b4580,_0x269a63){return _0x4b4580|_0x269a63;},'\x70\x6a\x70\x50\x6f':function(_0x49bb30,_0x458186){return _0x49bb30&_0x458186;},'\x6b\x78\x7a\x67\x45':function(_0x3f9cd1,_0x1a7ff9){return _0x3f9cd1^_0x1a7ff9;},'\x5a\x58\x53\x53\x42':function(_0x118d16,_0x53752a,_0x31fc91){return _0x118d16(_0x53752a,_0x31fc91);},'\x77\x43\x4c\x64\x52':function(_0x3e0e95,_0x3ed1ef,_0x539bc6){return _0x3e0e95(_0x3ed1ef,_0x539bc6);},'\x68\x4f\x7a\x78\x6d':function(_0x3cc105,_0x2d890a,_0x1bb996){return _0x3cc105(_0x2d890a,_0x1bb996);},'\x73\x6d\x68\x62\x69':function(_0x6ea5b,_0x3243e5,_0x209614,_0x4ce749){return _0x6ea5b(_0x3243e5,_0x209614,_0x4ce749);},'\x48\x51\x75\x71\x78':function(_0x260058,_0x5b71b3,_0x55787a){return _0x260058(_0x5b71b3,_0x55787a);},'\x46\x47\x63\x70\x59':function(_0x2f712a,_0xf0ff78,_0x2e16dd){return _0x2f712a(_0xf0ff78,_0x2e16dd);},'\x74\x78\x4e\x6e\x43':function(_0x3703b8,_0x322762,_0x5eee80){return _0x3703b8(_0x322762,_0x5eee80);},'\x48\x69\x57\x69\x68':function(_0x3162e0,_0x459727,_0x156266){return _0x3162e0(_0x459727,_0x156266);},'\x74\x61\x43\x71\x5a':function(_0x5ac9de,_0x549794,_0x1e8b4e){return _0x5ac9de(_0x549794,_0x1e8b4e);},'\x6a\x69\x72\x72\x4a':function(_0x46060c,_0x138936,_0x75e524){return _0x46060c(_0x138936,_0x75e524);},'\x50\x42\x42\x51\x48':function(_0x394fd9,_0x263dda,_0x49ef2c){return _0x394fd9(_0x263dda,_0x49ef2c);},'\x41\x68\x4a\x62\x5a':function(_0x5d235d,_0x5ec03b,_0x4a0f8d,_0x36a29d){return _0x5d235d(_0x5ec03b,_0x4a0f8d,_0x36a29d);},'\x51\x6a\x6e\x6b\x74':function(_0x5425e8,_0x346e66){return _0x5425e8+_0x346e66;},'\x53\x4b\x4e\x55\x50':function(_0x3bc2bb,_0x53b1a1){return _0x3bc2bb-_0x53b1a1;},'\x65\x44\x4d\x63\x7a':function(_0x139b1c,_0x4c32a8){return _0x139b1c%_0x4c32a8;},'\x54\x48\x71\x67\x43':function(_0x3b579f,_0x43eec4){return _0x3b579f*_0x43eec4;},'\x71\x73\x6a\x67\x50':function(_0x5a68fe,_0x67d243){return _0x5a68fe-_0x67d243;},'\x72\x7a\x74\x62\x75':function(_0xa50fd6,_0x2e9307){return _0xa50fd6>_0x2e9307;},'\x55\x6e\x76\x70\x70':function(_0x454e39,_0x31c047){return _0x454e39/_0x31c047;},'\x42\x61\x4c\x59\x63':function(_0x3fcec5,_0x509d13){return _0x3fcec5*_0x509d13;},'\x6b\x63\x65\x41\x4a':function(_0x56dd86,_0x5989c6){return _0x56dd86|_0x5989c6;},'\x4b\x46\x70\x76\x46':function(_0x570ac4,_0x4cf8e0){return _0x570ac4<<_0x4cf8e0;},'\x62\x69\x57\x53\x41':function(_0x597808,_0x54a9d3){return _0x597808-_0x54a9d3;},'\x57\x79\x59\x78\x68':function(_0xe5b86f,_0x17b32c){return _0xe5b86f<<_0x17b32c;},'\x6d\x77\x74\x63\x78':function(_0x369e36,_0x1a4f5d){return _0x369e36-_0x1a4f5d;},'\x6b\x42\x50\x4e\x71':function(_0x2d592c,_0x6bb762){return _0x2d592c*_0x6bb762;},'\x42\x68\x6a\x51\x4d':function(_0x412352,_0x1797cc){return _0x412352<_0x1797cc;},'\x70\x54\x72\x41\x59':function(_0x3b6958,_0x1958e7){return _0x3b6958>>_0x1958e7;},'\x65\x78\x67\x42\x44':function(_0x5451c2,_0x166cd2){return _0x5451c2>>_0x166cd2;},'\x4b\x69\x6a\x70\x68':function(_0x434df6,_0x426c5a){return _0x434df6|_0x426c5a;},'\x63\x45\x43\x51\x75':function(_0x1588e9,_0x1b3c20){return _0x1588e9|_0x1b3c20;},'\x44\x53\x76\x75\x58':function(_0x1658bf,_0x52c55b){return _0x1658bf(_0x52c55b);},'\x49\x66\x4b\x49\x77':function(_0x5871cb,_0x2a0ec6){return _0x5871cb<_0x2a0ec6;},'\x4b\x56\x52\x6a\x66':function(_0x5eb5aa,_0x5e967a,_0x11faac,_0xfdc0e8,_0x33b9c3,_0x33e880,_0x48b469,_0x2a647f){return _0x5eb5aa(_0x5e967a,_0x11faac,_0xfdc0e8,_0x33b9c3,_0x33e880,_0x48b469,_0x2a647f);},'\x70\x4e\x6c\x46\x6e':function(_0x78d9e2,_0x466df9){return _0x78d9e2+_0x466df9;},'\x4d\x41\x56\x59\x76':function(_0x41f413,_0x67d37d,_0x1b0127,_0x7cd081,_0x388fff,_0x2492db,_0x32a475,_0x4edcf7){return _0x41f413(_0x67d37d,_0x1b0127,_0x7cd081,_0x388fff,_0x2492db,_0x32a475,_0x4edcf7);},'\x75\x71\x6b\x67\x56':function(_0x38adc9,_0x7712be,_0x1c349c,_0x1b3a1a,_0x39b351,_0x4cab4c,_0x31f8f6,_0x24ef04){return _0x38adc9(_0x7712be,_0x1c349c,_0x1b3a1a,_0x39b351,_0x4cab4c,_0x31f8f6,_0x24ef04);},'\x61\x65\x44\x7a\x71':function(_0x372433,_0x4c9bb6){return _0x372433+_0x4c9bb6;},'\x7a\x4b\x50\x63\x4a':function(_0x122147,_0x24b4f5,_0xcf448b,_0x466f9d,_0x5867b4,_0x49da5c,_0x544bb9,_0x29efdd){return _0x122147(_0x24b4f5,_0xcf448b,_0x466f9d,_0x5867b4,_0x49da5c,_0x544bb9,_0x29efdd);},'\x48\x75\x4d\x72\x4a':function(_0xe0ba25,_0x14be50){return _0xe0ba25+_0x14be50;},'\x79\x6e\x74\x4c\x69':function(_0x54c9c6,_0x1ae561){return _0x54c9c6+_0x1ae561;},'\x6a\x64\x67\x50\x71':function(_0x44e4e1,_0x5e6ca1){return _0x44e4e1+_0x5e6ca1;},'\x71\x59\x4c\x6d\x42':function(_0x58a183,_0x533c16,_0x48718e,_0x29092a,_0x469d4e,_0x3f0189,_0x3dd9ae,_0x67b66){return _0x58a183(_0x533c16,_0x48718e,_0x29092a,_0x469d4e,_0x3f0189,_0x3dd9ae,_0x67b66);},'\x42\x63\x79\x43\x4b':function(_0x556117,_0x56ffaa){return _0x556117+_0x56ffaa;},'\x4c\x70\x58\x45\x57':function(_0x119ab0,_0x267aad){return _0x119ab0+_0x267aad;},'\x48\x4f\x64\x78\x69':function(_0x4ef645,_0xea0960,_0x203246,_0x305ad8,_0x26b941,_0x76557,_0x3f6e83,_0x66d44a){return _0x4ef645(_0xea0960,_0x203246,_0x305ad8,_0x26b941,_0x76557,_0x3f6e83,_0x66d44a);},'\x71\x65\x65\x68\x59':function(_0x27bada,_0xd05fc,_0x2b1f58,_0x54608d,_0x2a878d,_0x164702,_0xa1faba,_0x54d30e){return _0x27bada(_0xd05fc,_0x2b1f58,_0x54608d,_0x2a878d,_0x164702,_0xa1faba,_0x54d30e);},'\x42\x61\x4e\x4b\x79':function(_0x376d0e,_0xcc048f){return _0x376d0e+_0xcc048f;},'\x49\x48\x66\x63\x46':function(_0x6424bd,_0x5de92e,_0x25a2e1,_0x601dc2,_0x4bf942,_0x1abec0,_0x52091b,_0x1fc4d2){return _0x6424bd(_0x5de92e,_0x25a2e1,_0x601dc2,_0x4bf942,_0x1abec0,_0x52091b,_0x1fc4d2);},'\x46\x44\x72\x47\x41':function(_0x4ad448,_0x1ac218){return _0x4ad448+_0x1ac218;},'\x77\x64\x4a\x6f\x4d':function(_0x10afe1,_0x2812ad,_0x196fa5,_0x29362a,_0x207c90,_0x485a73,_0x5e2864,_0x43813a){return _0x10afe1(_0x2812ad,_0x196fa5,_0x29362a,_0x207c90,_0x485a73,_0x5e2864,_0x43813a);},'\x5a\x75\x5a\x6c\x79':function(_0x3a09d9,_0x427bdf){return _0x3a09d9+_0x427bdf;},'\x55\x6a\x6a\x50\x54':function(_0x279264,_0xb89f38){return _0x279264+_0xb89f38;},'\x61\x74\x49\x67\x46':function(_0x52ca47,_0x401861,_0x119add,_0x2df88e,_0x4bd6bf,_0xb55fd,_0x2d5731,_0x2a558b){return _0x52ca47(_0x401861,_0x119add,_0x2df88e,_0x4bd6bf,_0xb55fd,_0x2d5731,_0x2a558b);},'\x7a\x63\x5a\x65\x74':function(_0x392b7e,_0xb494a9,_0x5d2bfa,_0x1d3687,_0x470afa,_0x6fbd7a,_0x5a1257,_0x535b6b){return _0x392b7e(_0xb494a9,_0x5d2bfa,_0x1d3687,_0x470afa,_0x6fbd7a,_0x5a1257,_0x535b6b);},'\x4e\x68\x43\x66\x7a':function(_0x5c3244,_0x1cf469){return _0x5c3244+_0x1cf469;},'\x4f\x64\x45\x59\x5a':function(_0x5bbd51,_0x58cee2,_0x1f3f59,_0x11d58a,_0x127272,_0x55819a,_0x1d7bb0,_0x7d661b){return _0x5bbd51(_0x58cee2,_0x1f3f59,_0x11d58a,_0x127272,_0x55819a,_0x1d7bb0,_0x7d661b);},'\x61\x64\x42\x74\x74':function(_0x268afc,_0x44e40c){return _0x268afc+_0x44e40c;},'\x52\x78\x52\x58\x72':function(_0x448bbf,_0x21e487){return _0x448bbf+_0x21e487;},'\x77\x51\x52\x6b\x52':function(_0x507e44,_0x22155c,_0x57df38,_0x260b38,_0x3729ef,_0x3d40f4,_0x4cb941,_0x95c8a0){return _0x507e44(_0x22155c,_0x57df38,_0x260b38,_0x3729ef,_0x3d40f4,_0x4cb941,_0x95c8a0);},'\x78\x61\x64\x45\x4b':function(_0x3df26d,_0x487746){return _0x3df26d+_0x487746;},'\x44\x49\x47\x69\x66':function(_0x1cdff2,_0x2cb8f9,_0x14fe00,_0x1c374c,_0x11370c,_0x4101fe,_0x23d213,_0x4c60d2){return _0x1cdff2(_0x2cb8f9,_0x14fe00,_0x1c374c,_0x11370c,_0x4101fe,_0x23d213,_0x4c60d2);},'\x4b\x71\x45\x49\x4f':function(_0x2e6050,_0x986bf){return _0x2e6050+_0x986bf;},'\x66\x4f\x58\x55\x69':function(_0x441151,_0x1ae2d0,_0x249d69,_0x2c4643,_0x214b32,_0x5067bc,_0x1f0165,_0x2d298d){return _0x441151(_0x1ae2d0,_0x249d69,_0x2c4643,_0x214b32,_0x5067bc,_0x1f0165,_0x2d298d);},'\x56\x78\x4e\x69\x79':function(_0x503df8,_0x14d41c,_0x3ad32e,_0x5d61f1,_0x5143ef,_0x5c5adc,_0x1652dd,_0x362eb2){return _0x503df8(_0x14d41c,_0x3ad32e,_0x5d61f1,_0x5143ef,_0x5c5adc,_0x1652dd,_0x362eb2);},'\x46\x78\x41\x44\x5a':function(_0x7ded76,_0x5041c9){return _0x7ded76+_0x5041c9;},'\x62\x7a\x6b\x4e\x54':function(_0x3fc5b2,_0x49698a,_0x51ad71,_0x47b9b5,_0x4175aa,_0x2f56c4,_0x5bac6f,_0x4b57ee){return _0x3fc5b2(_0x49698a,_0x51ad71,_0x47b9b5,_0x4175aa,_0x2f56c4,_0x5bac6f,_0x4b57ee);},'\x56\x48\x71\x4d\x45':function(_0x1cd99b,_0x39cd08,_0xcbc04b,_0x41b964,_0x11e9ab,_0xa9036c,_0x1bdd98,_0x37ed99){return _0x1cd99b(_0x39cd08,_0xcbc04b,_0x41b964,_0x11e9ab,_0xa9036c,_0x1bdd98,_0x37ed99);},'\x76\x54\x73\x4c\x41':function(_0x383241,_0x3594bc){return _0x383241+_0x3594bc;},'\x6c\x62\x46\x4f\x52':function(_0x5c3884,_0x418dd5,_0xdf0138,_0x254c8b,_0x1bde50,_0x37b9e8,_0x44bca5,_0x130860){return _0x5c3884(_0x418dd5,_0xdf0138,_0x254c8b,_0x1bde50,_0x37b9e8,_0x44bca5,_0x130860);},'\x54\x47\x50\x67\x79':function(_0x36bc22,_0x1bccdd){return _0x36bc22+_0x1bccdd;},'\x68\x51\x42\x47\x57':function(_0x160089,_0x182afd,_0x5b6bca,_0x1a5704,_0x48d715,_0x457112,_0x14ba67,_0x215505){return _0x160089(_0x182afd,_0x5b6bca,_0x1a5704,_0x48d715,_0x457112,_0x14ba67,_0x215505);},'\x44\x48\x4d\x49\x68':function(_0x120805,_0x316b3a){return _0x120805+_0x316b3a;},'\x42\x70\x6d\x6d\x7a':function(_0x493dbb,_0x173e2c){return _0x493dbb+_0x173e2c;},'\x66\x4d\x68\x71\x6c':function(_0x191dc7,_0x33235e){return _0x191dc7+_0x33235e;},'\x6e\x69\x43\x6c\x41':function(_0x51575c,_0x5b74b2,_0x2d1cc8,_0x5cc1d5,_0x4ceccf,_0xef1445,_0x634809,_0x460ee0){return _0x51575c(_0x5b74b2,_0x2d1cc8,_0x5cc1d5,_0x4ceccf,_0xef1445,_0x634809,_0x460ee0);},'\x51\x63\x57\x62\x55':function(_0x2b4591,_0x4cdc80){return _0x2b4591+_0x4cdc80;},'\x6a\x4d\x4b\x75\x75':function(_0xa14611,_0x58af8b){return _0xa14611+_0x58af8b;},'\x48\x41\x7a\x6b\x57':function(_0x44b16b,_0x4b4095,_0x1a95e5){return _0x44b16b(_0x4b4095,_0x1a95e5);},'\x58\x49\x4f\x79\x4d':function(_0x173140,_0xdc7e43){return _0x173140(_0xdc7e43);}};function _0x98a5d7(_0x311d4a,_0x41c952){const _0x1e4015=_0x42bc;return _0x311d4a<<_0x41c952|_0x1c58f1[_0x1e4015(0x6e8)](_0x311d4a,0x26b4+0xb2*-0x10+-0x1b74-_0x41c952);}function _0xfeeca5(_0x182966,_0x1f1a36){const _0x4d867f=_0x42bc;var _0x3aaacc,_0x3f547d,_0x3d6fcc,_0x5b7dea,_0x369c79;return _0x3d6fcc=_0x1c58f1[_0x4d867f(0x5ca)](0x2*-0x7f6752a9+-0x3f1*0x2f1d1c+-0x1362*-0x1d5487,_0x182966),_0x5b7dea=_0x1c58f1[_0x4d867f(0x525)](-0xca*-0x24dc55+0xd3214e60+0x70372972*-0x1,_0x1f1a36),_0x3aaacc=_0x1c58f1['\x57\x48\x4a\x72\x46'](0x4072aff3+0x2b7*-0x27bf6b+0x6b75fb8a,_0x182966),_0x3f547d=_0x1c58f1[_0x4d867f(0x5ca)](0x10098e0d+0x1f22113b*0x1+0x133bdc4*0xe,_0x1f1a36),_0x369c79=_0x1c58f1[_0x4d867f(0x448)](_0x1c58f1['\x57\x48\x4a\x72\x46'](0x96b5fed*0xa+-0x6165eb87+0x219a1622*0x2,_0x182966),_0x1c58f1[_0x4d867f(0x5ca)](0x12358dfa+-0xdcd968*0x11+0x1797c25*0x29,_0x1f1a36)),_0x1c58f1[_0x4d867f(0x261)](_0x3aaacc,_0x3f547d)?_0x1c58f1[_0x4d867f(0x370)](_0x1c58f1['\x68\x6d\x70\x7a\x4c'](_0x1c58f1[_0x4d867f(0x534)](-0xe715c2f8+0x6*0x1bb6fe47+0xc0cbcd4e,_0x369c79),_0x3d6fcc),_0x5b7dea):_0x1c58f1[_0x4d867f(0x5a5)](_0x3aaacc,_0x3f547d)?_0x1c58f1[_0x4d867f(0x261)](-0x30609c1*-0x1+0x68cb2cec+-0xb*0x3fbbf27,_0x369c79)?_0x1c58f1['\x6b\x53\x71\x57\x74'](_0x1c58f1[_0x4d867f(0x26a)](_0x1c58f1[_0x4d867f(0x534)](0xf80c67f3+0x4a1*-0x4f2209+0x1364023b6,_0x369c79),_0x3d6fcc),_0x5b7dea):_0x1c58f1['\x45\x58\x79\x57\x4e'](_0x1c58f1[_0x4d867f(0x534)](0x5447077f+0x7e1dd4b+-0x1c28e4ca^_0x369c79,_0x3d6fcc),_0x5b7dea):_0x1c58f1[_0x4d867f(0x62c)](_0x369c79^_0x3d6fcc,_0x5b7dea);}function _0xe3ea2f(_0x3a3d73,_0x2c755a,_0x3ca5ad){return _0x3a3d73&_0x2c755a|~_0x3a3d73&_0x3ca5ad;}function _0x25cf30(_0x42e75c,_0x12b5c3,_0x305ae6){const _0x3abcbe=_0x42bc;return _0x1c58f1[_0x3abcbe(0x35c)](_0x1c58f1[_0x3abcbe(0x5ca)](_0x42e75c,_0x305ae6),_0x1c58f1[_0x3abcbe(0x641)](_0x12b5c3,~_0x305ae6));}function _0x1e4b20(_0x38a37a,_0x16c466,_0x3ae789){const _0x2da641=_0x42bc;return _0x1c58f1[_0x2da641(0x534)](_0x38a37a,_0x16c466)^_0x3ae789;}function _0x33b756(_0x2ed12d,_0x3d1da2,_0x263f32){const _0x1745e1=_0x42bc;return _0x1c58f1[_0x1745e1(0x3ef)](_0x3d1da2,_0x2ed12d|~_0x263f32);}function _0x3846fd(_0xe7607a,_0x4bb9e0,_0x4e67bc,_0x5d4fa6,_0x4428b3,_0x279d61,_0x6d0a11){const _0x2742df=_0x42bc;return _0xe7607a=_0x1c58f1[_0x2742df(0x371)](_0xfeeca5,_0xe7607a,_0x1c58f1[_0x2742df(0x57a)](_0xfeeca5,_0x1c58f1['\x68\x4f\x7a\x78\x6d'](_0xfeeca5,_0x1c58f1[_0x2742df(0x2b9)](_0xe3ea2f,_0x4bb9e0,_0x4e67bc,_0x5d4fa6),_0x4428b3),_0x6d0a11)),_0x1c58f1['\x5a\x58\x53\x53\x42'](_0xfeeca5,_0x98a5d7(_0xe7607a,_0x279d61),_0x4bb9e0);}function _0x452ac6(_0x636a8b,_0x1ed5c5,_0x3363ba,_0x2b554e,_0x3405a2,_0x42f1c2,_0x3694f6){const _0x2981ab=_0x42bc;return _0x636a8b=_0x1c58f1[_0x2981ab(0x2c8)](_0xfeeca5,_0x636a8b,_0x1c58f1[_0x2981ab(0x50d)](_0xfeeca5,_0x1c58f1[_0x2981ab(0x371)](_0xfeeca5,_0x25cf30(_0x1ed5c5,_0x3363ba,_0x2b554e),_0x3405a2),_0x3694f6)),_0x1c58f1['\x77\x43\x4c\x64\x52'](_0xfeeca5,_0x1c58f1['\x74\x78\x4e\x6e\x43'](_0x98a5d7,_0x636a8b,_0x42f1c2),_0x1ed5c5);}function _0x5304be(_0x45d9ae,_0xeaf806,_0x48abf3,_0x2baee5,_0x368844,_0x230a6c,_0x48579d){const _0x260f0f=_0x42bc;return _0x45d9ae=_0x1c58f1[_0x260f0f(0x22e)](_0xfeeca5,_0x45d9ae,_0x1c58f1[_0x260f0f(0x4b2)](_0xfeeca5,_0x1c58f1['\x46\x47\x63\x70\x59'](_0xfeeca5,_0x1c58f1[_0x260f0f(0x2b9)](_0x1e4b20,_0xeaf806,_0x48abf3,_0x2baee5),_0x368844),_0x48579d)),_0x1c58f1[_0x260f0f(0x491)](_0xfeeca5,_0x1c58f1[_0x260f0f(0x38c)](_0x98a5d7,_0x45d9ae,_0x230a6c),_0xeaf806);}function _0x3c5f2e(_0x4ca2ff,_0x4f9262,_0x24e9be,_0x58e7ce,_0x3cfbbc,_0x488032,_0x51868a){const _0x28682b=_0x42bc;return _0x4ca2ff=_0xfeeca5(_0x4ca2ff,_0x1c58f1[_0x28682b(0x57a)](_0xfeeca5,_0xfeeca5(_0x1c58f1[_0x28682b(0x4db)](_0x33b756,_0x4f9262,_0x24e9be,_0x58e7ce),_0x3cfbbc),_0x51868a)),_0x1c58f1['\x48\x51\x75\x71\x78'](_0xfeeca5,_0x1c58f1[_0x28682b(0x57a)](_0x98a5d7,_0x4ca2ff,_0x488032),_0x4f9262);}function _0x155f76(_0x533e6f){const _0x242019=_0x42bc;for(var _0x3b39e7,_0x29c05b=_0x533e6f[_0x242019(0x2bd)+'\x68'],_0x1a17c8=_0x1c58f1[_0x242019(0x35d)](_0x29c05b,0xea9+-0xc54+-0x24d),_0x5c29da=_0x1c58f1[_0x242019(0x61d)](_0x1a17c8,_0x1c58f1[_0x242019(0x1c7)](_0x1a17c8,-0x2062*0x1+-0x7a5+0x2847))/(-0x110f+-0x6da+0x1829),_0x3457ae=_0x1c58f1[_0x242019(0x1de)](-0x85b+-0x6*-0x491+-0x2b*0x71,_0x1c58f1[_0x242019(0x35d)](_0x5c29da,0xb16+0x457*0x8+-0x2dcd)),_0x4e4cf2=new Array(_0x1c58f1['\x71\x73\x6a\x67\x50'](_0x3457ae,-0x1*-0x96+-0x97*-0x2c+0x1*-0x1a89)),_0x152046=0x62a+0xf89+-0x15b3,_0x31f6a0=-0x1bcd+-0xee8+0x2ab5;_0x1c58f1['\x72\x7a\x74\x62\x75'](_0x29c05b,_0x31f6a0);)_0x3b39e7=_0x1c58f1[_0x242019(0x627)](_0x1c58f1[_0x242019(0x61d)](_0x31f6a0,_0x31f6a0%(0x829*0x2+0xde7+-0x1e35)),0x288+-0x3ad*-0x8+-0x1fec),_0x152046=_0x1c58f1[_0x242019(0x458)](_0x31f6a0%(-0x25d6+-0x1c20+0x41fa),0xa*0x12e+0x8*0x1af+-0x193c),_0x4e4cf2[_0x3b39e7]=_0x1c58f1[_0x242019(0x377)](_0x4e4cf2[_0x3b39e7],_0x1c58f1[_0x242019(0x317)](_0x533e6f[_0x242019(0x232)+_0x242019(0x273)](_0x31f6a0),_0x152046)),_0x31f6a0++;return _0x3b39e7=_0x1c58f1[_0x242019(0x627)](_0x1c58f1['\x62\x69\x57\x53\x41'](_0x31f6a0,_0x31f6a0%(-0x5*0x54b+0x4eb*-0x2+0x2451)),0x4*-0x17a+-0x2f*0x1+0x61b*0x1),_0x152046=_0x1c58f1[_0x242019(0x458)](_0x1c58f1[_0x242019(0x1c7)](_0x31f6a0,0x162d+0x12ed+-0x2916),-0x34d+0x1566+-0xb9*0x19),_0x4e4cf2[_0x3b39e7]=_0x1c58f1[_0x242019(0x377)](_0x4e4cf2[_0x3b39e7],_0x1c58f1[_0x242019(0x317)](-0x1*-0x1a75+0x1331*0x1+0x1*-0x2d26,_0x152046)),_0x4e4cf2[_0x1c58f1['\x62\x69\x57\x53\x41'](_0x3457ae,0x18c5+-0x1fb*0x1+-0x16c8)]=_0x1c58f1['\x57\x79\x59\x78\x68'](_0x29c05b,0x1099*0x2+-0x16ee+-0xa41),_0x4e4cf2[_0x1c58f1['\x6d\x77\x74\x63\x78'](_0x3457ae,-0x1*0x1f2d+0x701*0x1+0x182d)]=_0x1c58f1[_0x242019(0x6e8)](_0x29c05b,-0x101f+0xcb1+0x38b),_0x4e4cf2;}function _0x55ff08(_0x24e571){const _0x42e64c=_0x42bc;var _0x15db46,_0x1137b7,_0x22192c='',_0x23a088='';for(_0x1137b7=-0x2002+-0x75*0x15+0x299b;-0xd99*0x1+0x1*-0x1812+0x25ae>=_0x1137b7;_0x1137b7++)_0x15db46=_0x1c58f1['\x44\x73\x69\x46\x4d'](_0x24e571,_0x1c58f1[_0x42e64c(0x661)](0x22d+-0x1c26+0x1a01,_0x1137b7))&0x1a21+0x16c*0x7+-0x2316,_0x23a088='\x30'+_0x15db46['\x74\x6f\x53\x74\x72'+_0x42e64c(0x67e)](0x1a9+0x24*-0x104+0x22f7),_0x22192c+=_0x23a088[_0x42e64c(0x496)+'\x72'](_0x1c58f1[_0x42e64c(0x6bd)](_0x23a088['\x6c\x65\x6e\x67\x74'+'\x68'],-0x19ff+-0x2291+0x3c92),0xbd2+-0xb04+-0xcc);return _0x22192c;}function _0x328de0(_0x1351a7){const _0x4e6cca=_0x42bc;_0x1351a7=_0x1351a7[_0x4e6cca(0x4dc)+'\x63\x65'](/\r\n/g,'\x0a');for(var _0x2b27dd='',_0x5a0cf0=-0xc84+0x1499+-0x815;_0x1c58f1['\x42\x68\x6a\x51\x4d'](_0x5a0cf0,_0x1351a7['\x6c\x65\x6e\x67\x74'+'\x68']);_0x5a0cf0++){var _0x10918f=_0x1351a7[_0x4e6cca(0x232)+_0x4e6cca(0x273)](_0x5a0cf0);_0x1c58f1[_0x4e6cca(0x291)](-0x1780+-0x924+-0x7*-0x4bc,_0x10918f)?_0x2b27dd+=String['\x66\x72\x6f\x6d\x43'+_0x4e6cca(0x37a)+'\x64\x65'](_0x10918f):_0x10918f>0x4d7+-0x11*-0x1f1+0x1*-0x2559&&0x1a86+-0x963+0x1*-0x923>_0x10918f?(_0x2b27dd+=String[_0x4e6cca(0x577)+'\x68\x61\x72\x43\x6f'+'\x64\x65'](_0x1c58f1[_0x4e6cca(0x5a5)](_0x1c58f1['\x70\x54\x72\x41\x59'](_0x10918f,0x1*-0xf13+0x18eb*-0x1+-0x1402*-0x2),-0x10f*0x1+-0x1fc2+0x2191)),_0x2b27dd+=String[_0x4e6cca(0x577)+_0x4e6cca(0x37a)+'\x64\x65'](_0x1c58f1['\x50\x49\x43\x72\x6f'](-0x67*0x1+0x22e3+0x223d*-0x1&_0x10918f,-0xaaf+-0x19*0x2a+-0x22f*-0x7))):(_0x2b27dd+=String[_0x4e6cca(0x577)+_0x4e6cca(0x37a)+'\x64\x65'](_0x1c58f1['\x50\x49\x43\x72\x6f'](_0x1c58f1[_0x4e6cca(0x3e3)](_0x10918f,-0x1*0x1527+0xe*0xcb+0xeb*0xb),-0x269d*0x1+-0x13e3+0xa0*0x5f)),_0x2b27dd+=String[_0x4e6cca(0x577)+'\x68\x61\x72\x43\x6f'+'\x64\x65'](_0x1c58f1[_0x4e6cca(0x3b0)](_0x1c58f1[_0x4e6cca(0x261)](_0x1c58f1[_0x4e6cca(0x3e3)](_0x10918f,-0x1c59+0x2385+-0x726),-0xa*0x2ad+0x1*0x31e+0x17e3*0x1),0x1794+-0xfa3+0x3*-0x27b)),_0x2b27dd+=String[_0x4e6cca(0x577)+_0x4e6cca(0x37a)+'\x64\x65'](_0x1c58f1['\x63\x45\x43\x51\x75'](_0x1c58f1[_0x4e6cca(0x5ca)](-0x1509+-0xcab+-0x1*-0x21f3,_0x10918f),-0xf84+-0x1*-0x1497+-0x493)));}return _0x2b27dd;}var _0x5d85b3,_0x3cdabd,_0x57bb28,_0x288bd0,_0x4f2f28,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696=[],_0xa46d0e=-0xf1*-0x1f+-0x64c+0x10a*-0x16,_0x1929a9=0x1*-0x1444+-0x17b7+-0x1*-0x2c07,_0x3ea645=-0x3cd*-0x5+0xbcb+-0x1ebb,_0x163b85=-0x2556+-0x18e4+0x7ca*0x8,_0x161d71=-0x1c6a+-0x1f*0x107+0x3c48,_0x270006=-0x1e8*-0x9+-0xf*0x163+0x1*0x3ae,_0x2f4699=0x95*0x2f+-0x33*-0x4b+-0x2a3e,_0x44c858=0x1ff8+-0x20f9+-0x1*-0x115,_0xa79ad4=-0x1391*-0x1+0x221e+0x1*-0x35ab,_0x5bf907=-0x20de+-0xbc5+0x2cae,_0x17079b=-0x1762+0x45e+0x1314,_0x2834e3=0x10d4+-0x63*0x1b+0x2*-0x326,_0x2799fb=-0x1958*-0x1+-0x553+-0x13ff*0x1,_0x5b87ee=-0xd18+0xbb7*0x1+0xb*0x21,_0xc5cafd=0x26b9+-0xa9f+-0x1c0b,_0x23b6d4=-0x1*0x308+-0x1c5+-0x19*-0x32;for(_0x1cac09=_0x1c58f1['\x44\x53\x76\x75\x58'](_0x328de0,_0x1cac09),_0x551696=_0x1c58f1[_0x84f7a3(0x551)](_0x155f76,_0x1cac09),_0x2071f9=0x1*0xa58fe361+0x2883f46*-0x3b+-0xe*-0x638d857,_0x111f63=-0x53ec07d7*-0x3+0x1*-0x52aad7b9+0x1*0x46b46bbd,_0x1d9895=0x2*-0x25eb236b+-0x27efaf1f*-0x3+0x6cc21677*0x1,_0x1ed327=-0x70d80bd*-0x2+0x1053ff9d+-0xe3caca1,_0x5d85b3=-0x850+-0x1*-0xd6a+-0x51a;_0x1c58f1[_0x84f7a3(0x4f8)](_0x5d85b3,_0x551696['\x6c\x65\x6e\x67\x74'+'\x68']);_0x5d85b3+=-0xc*-0x2f+0x14b*0x19+-0x2277)_0x3cdabd=_0x2071f9,_0x57bb28=_0x111f63,_0x288bd0=_0x1d9895,_0x4f2f28=_0x1ed327,_0x2071f9=_0x3846fd(_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1[_0x84f7a3(0x448)](_0x5d85b3,-0xa*0xa0+0xa*0x35b+-0x1b4e)],_0xa46d0e,-0xbe326647+-0x2bfba2bf+0x426d*0x6c4b6),_0x1ed327=_0x1c58f1['\x4b\x56\x52\x6a\x66'](_0x3846fd,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x5d85b3+(0x1376*-0x1+0x8b9+0xabe)],_0x1929a9,0x1591402a1*-0x1+0xce972ffa*-0x2+-0x5a29*-0xafdf3),_0x1d9895=_0x1c58f1[_0x84f7a3(0x266)](_0x3846fd,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x555)](_0x5d85b3,-0xdc*-0x2c+0x3c1*-0x1+0x17b*-0x17)],_0x3ea645,0x22698d14+-0x2a553179+-0x18*-0x1d5d638),_0x111f63=_0x1c58f1[_0x84f7a3(0x549)](_0x3846fd,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x555)](_0x5d85b3,0x21d3+-0x1e4f+0xd*-0x45)],_0x163b85,0xf3f71b81*0x1+-0x11dd4ef25+0x2e*0x51f359f),_0x2071f9=_0x1c58f1[_0x84f7a3(0x266)](_0x3846fd,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x5d85b3+(0x9f5+-0x1*0x1e63+-0xa39*-0x2)],_0xa46d0e,0xa64240a1*0x1+-0xa28d529*-0x15+-0x861fad4f),_0x1ed327=_0x1c58f1[_0x84f7a3(0x64a)](_0x3846fd,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1[_0x84f7a3(0x35d)](_0x5d85b3,0x1236+0xe4b+0xe7*-0x24)],_0x1929a9,-0x79232e5c+0xd2fb2*0x587+0x77c853a8),_0x1d9895=_0x1c58f1[_0x84f7a3(0x549)](_0x3846fd,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x555)](_0x5d85b3,-0x7*0x19f+0x1fea+-0x148b)],_0x3ea645,-0xece98eb0+0x12964dd1*0x3+0x1e*0xba507d8),_0x111f63=_0x1c58f1[_0x84f7a3(0x266)](_0x3846fd,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x555)](_0x5d85b3,0x323*-0x7+0x3f1*0x7+-0x59b)],_0x163b85,-0x75081*0x301d+0x1*-0x1a1fcc7c1+0x19b5*0x27cd43),_0x2071f9=_0x1c58f1[_0x84f7a3(0x64a)](_0x3846fd,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1[_0x84f7a3(0x340)](_0x5d85b3,-0x14*-0x9f+-0x4f*0x1+-0xc15)],_0xa46d0e,-0xce7fdedd+-0xa76b46cc+0x1df6bbe81),_0x1ed327=_0x1c58f1['\x7a\x4b\x50\x63\x4a'](_0x3846fd,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x5d85b3+(-0x1bf4+0xc58+0xfa5)],_0x1929a9,0xe04f9f81+-0x26*0x2984e12+-0x1*-0xd90eeda),_0x1d9895=_0x1c58f1['\x4d\x41\x56\x59\x76'](_0x3846fd,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x5d85b3+(0x4a*-0x40+-0x1535+0x113*0x25)],_0x3ea645,0x1a2239ca*-0x6+0xd192bf7d*0x1+-0x3130*-0x421b5),_0x111f63=_0x3846fd(_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1['\x51\x6a\x6e\x6b\x74'](_0x5d85b3,0x5*-0x68+0xf94+0xd81*-0x1)],_0x163b85,0x54843742+0x50cc1d38*0x1+-0xf7cf2*0x1ce),_0x2071f9=_0x3846fd(_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x5d85b3+(-0x24ca+0x2*0x56d+0x19fc)],_0xa46d0e,0x2e0c9645+0xd24da223*0x1+-0x94ca2746),_0x1ed327=_0x1c58f1[_0x84f7a3(0x549)](_0x3846fd,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1['\x61\x65\x44\x7a\x71'](_0x5d85b3,0x2*-0x63d+0x184c+0x1*-0xbc5)],_0x1929a9,0x96449fb7+-0x1*0x1de5c386+-0x85399562*-0x1),_0x1d9895=_0x1c58f1[_0x84f7a3(0x257)](_0x3846fd,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x36a)](_0x5d85b3,-0x1*-0x1ca+-0x1e7a+0x1cbe)],_0x3ea645,-0x707f2797*-0x2+-0xe*0x3ebb967+0x825f7*-0x72),_0x111f63=_0x1c58f1[_0x84f7a3(0x266)](_0x3846fd,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x340)](_0x5d85b3,0x15cd+0x1e61*-0x1+-0x43*-0x21)],_0x163b85,0x76f0da4c+-0x78472f2e+0x4b0a5d03),_0x2071f9=_0x1c58f1[_0x84f7a3(0x64a)](_0x452ac6,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1['\x79\x6e\x74\x4c\x69'](_0x5d85b3,0x16eb+0xea0+-0x1*0x258a)],_0x161d71,0x1526d348f+-0x1b203c68f+-0x1a*-0xd247d35),_0x1ed327=_0x452ac6(_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1['\x6a\x64\x67\x50\x71'](_0x5d85b3,0x8c2*-0x2+-0x2072+-0x1c9*-0x1c)],_0x270006,-0xc1ed0819+0x73938f63+-0x874d15fb*-0x2),_0x1d9895=_0x1c58f1[_0x84f7a3(0x257)](_0x452ac6,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x5d85b3+(0x8*0x11d+-0x27*0x84+-0x1*-0xb3f)],_0x2f4699,-0x68e1e73+0x302daa78+-0x34131b4),_0x111f63=_0x1c58f1[_0x84f7a3(0x64a)](_0x452ac6,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x5d85b3+(0x13d1+0x2473*0x1+-0x1*0x3844)],_0x44c858,-0xbc746797+-0x22fa*0x21adb+0x1efca7f1f),_0x2071f9=_0x452ac6(_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x5d85b3+(-0x7*-0x1f3+-0x7cb+-0x1*0x5d5)],_0x161d71,0x2*-0x10f53623+-0x2*-0x5175d877+0x552dcbb5),_0x1ed327=_0x1c58f1[_0x84f7a3(0x526)](_0x452ac6,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x5d85b3+(-0xa10+0x2663+-0x1c49)],_0x270006,0x17db74*0x28+0x63*-0x89d1f+0x1de8d30),_0x1d9895=_0x452ac6(_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x4e5)](_0x5d85b3,-0x2626+0x925*-0x1+0x2f5a*0x1)],_0x2f4699,-0xba39c05e+0x349db29*0x39+0xd769dabe*0x1),_0x111f63=_0x1c58f1[_0x84f7a3(0x549)](_0x452ac6,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x448)](_0x5d85b3,0x1*0x11+0xd*0x23+-0x9*0x34)],_0x44c858,0xac7*0x15ba77+0x156009461+-0x277*0x8bb436),_0x2071f9=_0x452ac6(_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x5d85b3+(-0x1*-0x4c9+-0x13f9+0xf39)],_0x161d71,0x3861694a+0x1b65a957+0x31e544bb*-0x1),_0x1ed327=_0x452ac6(_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1[_0x84f7a3(0x41f)](_0x5d85b3,0x1d78+-0x36*-0x26+-0x256e)],_0x270006,-0xed536150+0x15d*-0x10844ef+-0x318d062f9*-0x1),_0x1d9895=_0x452ac6(_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x598)](_0x5d85b3,0x6a3*-0x1+0x1f97+-0x18f1)],_0x2f4699,-0xb6aac5fe+0x296*-0x5f7ed1+0x2a271c3fb),_0x111f63=_0x1c58f1[_0x84f7a3(0x6c6)](_0x452ac6,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x340)](_0x5d85b3,0x4*-0x716+0x1785+-0x1*-0x4db)],_0x44c858,0x92c3*-0xe1f7+-0x2*0x1fed4c59+0x106bfaac4),_0x2071f9=_0x1c58f1['\x71\x65\x65\x68\x59'](_0x452ac6,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1[_0x84f7a3(0x1e1)](_0x5d85b3,-0xc3f+0x1d8a+-0x113e)],_0x161d71,0xd7c38d43+0x3f*-0xc1ffba+0x446*0x6fec),_0x1ed327=_0x1c58f1[_0x84f7a3(0x6e4)](_0x452ac6,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1[_0x84f7a3(0x4e5)](_0x5d85b3,0x1*-0x1d09+0x1bef+0x11c*0x1)],_0x270006,0x2*0xfce3e16c+-0x1a6b171*0x22+0x2f*-0x42f6a82),_0x1d9895=_0x1c58f1['\x7a\x4b\x50\x63\x4a'](_0x452ac6,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x555)](_0x5d85b3,0x2f*0x97+-0x1806+-0x3ac)],_0x2f4699,0xce37020c+-0x5f1f22b*-0x11+-0xcbd9140e),_0x111f63=_0x1c58f1[_0x84f7a3(0x2da)](_0x452ac6,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1['\x46\x44\x72\x47\x41'](_0x5d85b3,0x926+0x1*0xe17+-0x1731)],_0x44c858,0x2f6db*0x45d+0xab4784*0x167+-0x30473*0x251b),_0x2071f9=_0x1c58f1['\x77\x64\x4a\x6f\x4d'](_0x5304be,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1[_0x84f7a3(0x692)](_0x5d85b3,-0x467+0x1*0xbb7+-0x74b)],_0xa79ad4,-0x1c8167089+-0x10517b1ca+-0x1*-0x3cd285b95),_0x1ed327=_0x1c58f1['\x71\x65\x65\x68\x59'](_0x5304be,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x5d85b3+(-0x27*-0x76+0x1065+-0x2257)],_0x5bf907,-0x4*0x59e4ea6+0x8c1e0fde+0x11cd213b),_0x1d9895=_0x1c58f1['\x75\x71\x6b\x67\x56'](_0x5304be,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x1e5)](_0x5d85b3,-0x71d*-0x2+-0x23ed*0x1+-0x79*-0x2e)],_0x17079b,0x16ba8925+-0x349ecb2*-0x19+-0xeef21f*-0x5),_0x111f63=_0x1c58f1['\x61\x74\x49\x67\x46'](_0x5304be,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x340)](_0x5d85b3,-0x4f7+-0x1*-0x653+-0x2*0xa7)],_0x2834e3,-0x14e691d3a+-0x5a2b4dda*-0x2+0x197f7b992),_0x2071f9=_0x1c58f1[_0x84f7a3(0x387)](_0x5304be,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1[_0x84f7a3(0x6ae)](_0x5d85b3,-0x1*0x47d+-0x1*0x15f4+0x1a72)],_0xa79ad4,-0x1b04b2d*-0x39+0x127f4466f+0x170*-0x9e3be5),_0x1ed327=_0x1c58f1[_0x84f7a3(0x3c5)](_0x5304be,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1[_0x84f7a3(0x1e1)](_0x5d85b3,0x1*0x811+-0x10bb+-0x65*-0x16)],_0x5bf907,-0x945d58c0+-0x35cc4a3f+0x1160872a8),_0x1d9895=_0x1c58f1[_0x84f7a3(0x3c5)](_0x5304be,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x61e)](_0x5d85b3,-0xda5+-0x3*-0x1d8+-0x824*-0x1)],_0x17079b,-0x3965ea31+-0x197f802eb+0x2c819387c),_0x111f63=_0x1c58f1['\x75\x71\x6b\x67\x56'](_0x5304be,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x1ca)](_0x5d85b3,0x26e2+0x1a*-0x6b+-0x1bfa)],_0x2834e3,0x483*0x81e0f+-0x6cb7*0x1621b+0x13080a410),_0x2071f9=_0x1c58f1[_0x84f7a3(0x509)](_0x5304be,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1['\x78\x61\x64\x45\x4b'](_0x5d85b3,0xd05+0x21d2+-0x2eca)],_0xa79ad4,-0x1eec9815*-0x2+-0x19282679+0x3ea7515),_0x1ed327=_0x5304be(_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1[_0x84f7a3(0x43a)](_0x5d85b3,0x2a2*0x5+-0x24cc+0x6e*0x37)],_0x5bf907,-0x1*0x197f2fbb2+0x318f6fb2*0x1+-0x3*-0xc5ac3bfe),_0x1d9895=_0x1c58f1['\x44\x49\x47\x69\x66'](_0x5304be,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x692)](_0x5d85b3,0x7*-0x4ed+-0x23f9+0x4677)],_0x17079b,0xb657*0x1b389+-0xff90ed64+0x2e0bd76*0x37),_0x111f63=_0x1c58f1[_0x84f7a3(0x3c5)](_0x5304be,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1['\x4b\x71\x45\x49\x4f'](_0x5d85b3,0x15e0+0x555+-0x1b2f)],_0x2834e3,-0x76c8efa+-0x63b04d4+0x122fb0d3*0x1),_0x2071f9=_0x1c58f1['\x66\x4f\x58\x55\x69'](_0x5304be,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x5d85b3+(0x3*-0x6f3+-0x2056+0xd*0x418)],_0xa79ad4,-0xbfb*0x4e441+0xde2189*-0x75+-0x163b9281*-0x11),_0x1ed327=_0x1c58f1[_0x84f7a3(0x306)](_0x5304be,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x5d85b3+(0x3e0+-0x12e+0x3*-0xe2)],_0x5bf907,-0xac3938e+-0x1e9*-0xbd571a+-0x780c3337),_0x1d9895=_0x1c58f1[_0x84f7a3(0x257)](_0x5304be,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1[_0x84f7a3(0x37f)](_0x5d85b3,0x7e0+0x2260+-0x2a31)],_0x17079b,0x237efb1*0x9+-0x30522937+0x3bfd38f6),_0x111f63=_0x1c58f1[_0x84f7a3(0x6b9)](_0x5304be,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x1e5)](_0x5d85b3,0xdb*0xe+0x1*-0x1816+0x40a*0x3)],_0x2834e3,0x18276f7a+0x459*-0x2e05ab+0x1749b8b5e),_0x2071f9=_0x1c58f1[_0x84f7a3(0x597)](_0x3c5f2e,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1[_0x84f7a3(0x254)](_0x5d85b3,0x240d+-0x1a47+-0x9c6)],_0x2799fb,-0x1a3e6dcaa*-0x1+-0x2570ffb0+-0x396e*0x2687d),_0x1ed327=_0x1c58f1[_0x84f7a3(0x427)](_0x3c5f2e,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1['\x6a\x64\x67\x50\x71'](_0x5d85b3,-0x997+0x4*0x162+0x416)],_0x5b87ee,-0x70f8061e+0x1d9*-0x363505+0x1184afbf2),_0x1d9895=_0x1c58f1[_0x84f7a3(0x2da)](_0x3c5f2e,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x5d85b3+(-0x2b5*-0x1+0x49*0x19+-0x139*0x8)],_0xc5cafd,-0x18a10ad*0x8e+-0x104bea271+-0xbdc931*-0x36e),_0x111f63=_0x1c58f1[_0x84f7a3(0x526)](_0x3c5f2e,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1['\x54\x47\x50\x67\x79'](_0x5d85b3,-0x1e5d+0x146*-0x13+-0x3694*-0x1)],_0x23b6d4,0x1c1be475c+0x14d73a35*0x12+-0x23c4cbedd),_0x2071f9=_0x1c58f1[_0x84f7a3(0x4eb)](_0x3c5f2e,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x1c58f1[_0x84f7a3(0x54c)](_0x5d85b3,0x1f06+-0x1a62+-0x498)],_0x2799fb,0x23a96b*-0x44d+-0x4f2fe778+-0x14deae26a*-0x1),_0x1ed327=_0x1c58f1['\x56\x78\x4e\x69\x79'](_0x3c5f2e,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1[_0x84f7a3(0x4b3)](_0x5d85b3,0x3*0xbc5+0x2660+-0x3af*0x14)],_0x5b87ee,0x21123adf*0x2+0xa297eb99+-0x55af94c5),_0x1d9895=_0x1c58f1['\x4d\x41\x56\x59\x76'](_0x3c5f2e,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x1c58f1['\x66\x4d\x68\x71\x6c'](_0x5d85b3,0x2293*0x1+-0x1*-0xb47+-0x2dd0)],_0xc5cafd,0x7131e609+0x6a0cc984+-0x1*-0x24b144f0),_0x111f63=_0x3c5f2e(_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1['\x70\x4e\x6c\x46\x6e'](_0x5d85b3,-0x152c+0x6c2*0x4+-0x5db)],_0x23b6d4,0x253eb467*-0x4+0xe0c0f099*0x1+0xbd4*0x4e1c1),_0x2071f9=_0x1c58f1[_0x84f7a3(0x673)](_0x3c5f2e,_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x5d85b3+(-0x905*0x4+0x1846+-0x1*-0xbd6)],_0x2799fb,0x4d862836+0x43e0b3*-0xab+-0xf1d*-0x54232),_0x1ed327=_0x3c5f2e(_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1[_0x84f7a3(0x6ae)](_0x5d85b3,-0x20*0x102+-0xa89+-0x6*-0x724)],_0x5b87ee,-0xcd63899d+-0x3955056*0x56+0x35565*0xe64d),_0x1d9895=_0x3c5f2e(_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x5d85b3+(0x1*-0x2669+-0x2*-0xa63+-0x5e3*-0x3)],_0xc5cafd,-0x137b2177c+-0x41cde51c+0x21c813fac),_0x111f63=_0x3c5f2e(_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1[_0x84f7a3(0x43a)](_0x5d85b3,-0x7d6+0x1801+0x101e*-0x1)],_0x23b6d4,0x23ac*0x28a88+-0x8551*-0xcf36+0xd5*-0x90db01),_0x2071f9=_0x3c5f2e(_0x2071f9,_0x111f63,_0x1d9895,_0x1ed327,_0x551696[_0x5d85b3+(-0x1acc+-0x5fb+0x73*0x49)],_0x2799fb,0xdbb5f5e+-0x1*0xb736d14b+0x1a0cef06f),_0x1ed327=_0x1c58f1[_0x84f7a3(0x597)](_0x3c5f2e,_0x1ed327,_0x2071f9,_0x111f63,_0x1d9895,_0x551696[_0x1c58f1[_0x84f7a3(0x420)](_0x5d85b3,0x25*0x29+0xcd7+0x1*-0x12b9)],_0x5b87ee,-0xf7710d28+-0x16a6e8ba9+0x31f1a8b06),_0x1d9895=_0x1c58f1[_0x84f7a3(0x2da)](_0x3c5f2e,_0x1d9895,_0x1ed327,_0x2071f9,_0x111f63,_0x551696[_0x5d85b3+(-0x5bf+0x6d*-0x26+0x15ef)],_0xc5cafd,0x977*-0x45976+-0x600*-0xbfba1+0xc1cc895),_0x111f63=_0x1c58f1['\x66\x4f\x58\x55\x69'](_0x3c5f2e,_0x111f63,_0x1d9895,_0x1ed327,_0x2071f9,_0x551696[_0x1c58f1['\x6a\x4d\x4b\x75\x75'](_0x5d85b3,-0x55f*0x3+0x16cb+-0x6a5)],_0x23b6d4,-0x1*-0x17a0dbee8+-0xa1f4be32+0x136dd2db),_0x2071f9=_0x1c58f1[_0x84f7a3(0x402)](_0xfeeca5,_0x2071f9,_0x3cdabd),_0x111f63=_0x1c58f1[_0x84f7a3(0x50d)](_0xfeeca5,_0x111f63,_0x57bb28),_0x1d9895=_0x1c58f1[_0x84f7a3(0x50d)](_0xfeeca5,_0x1d9895,_0x288bd0),_0x1ed327=_0xfeeca5(_0x1ed327,_0x4f2f28);var _0x39920d=_0x1c58f1[_0x84f7a3(0x1e5)](_0x1c58f1[_0x84f7a3(0x598)](_0x55ff08(_0x2071f9),_0x55ff08(_0x111f63)),_0x1c58f1[_0x84f7a3(0x1f7)](_0x55ff08,_0x1d9895))+_0x55ff08(_0x1ed327);return _0x39920d[_0x84f7a3(0x397)+'\x65\x72\x43\x61\x73'+'\x65']();}function _0xbd0ce1(_0xe7e934,_0x36578e){const _0x58d552=_0x2fc758,_0x5b5639={'\x41\x6a\x45\x71\x44':function(_0x3783d3,_0x476b7b){return _0x3783d3==_0x476b7b;},'\x4e\x66\x73\x65\x78':_0x58d552(0x3dc)+'\x67','\x4a\x71\x52\x6a\x62':function(_0x3189f2,_0x540df6){return _0x3189f2===_0x540df6;},'\x42\x64\x72\x52\x51':_0x58d552(0x219),'\x78\x6e\x4e\x52\x4b':_0x58d552(0x34c),'\x6a\x71\x41\x63\x56':function(_0x1df31a,_0x528871){return _0x1df31a!=_0x528871;},'\x56\x63\x69\x53\x52':'\x75\x6e\x64\x65\x66'+_0x58d552(0x2a9),'\x49\x51\x79\x55\x73':function(_0xfe1fe5,_0x68979e){return _0xfe1fe5!=_0x68979e;},'\x4d\x6c\x57\x42\x43':_0x58d552(0x669)+'\x79\x5f\x62\x6f\x78'+'\x6a\x73\x5f\x75\x73'+_0x58d552(0x51b)+'\x73\x2e\x68\x74\x74'+_0x58d552(0x424)+'\x74\x69\x6d\x65\x6f'+'\x75\x74','\x44\x4e\x4a\x4b\x57':function(_0x355cff,_0x3fbb85){return _0x355cff*_0x3fbb85;},'\x42\x49\x71\x74\x4c':_0x58d552(0x1d5),'\x4f\x67\x69\x78\x69':function(_0x3e80e2,_0x542eee){return _0x3e80e2(_0x542eee);},'\x75\x63\x79\x42\x49':_0x58d552(0x2bc),'\x66\x4f\x79\x4d\x58':function(_0x1a7d32,_0x432bb7){return _0x1a7d32&&_0x432bb7;},'\x55\x51\x63\x6f\x57':function(_0x54df1d,_0x41639f){return _0x54df1d(_0x41639f);},'\x65\x4e\x50\x4a\x49':function(_0x1ef220,_0x1b69a5){return _0x1ef220!==_0x1b69a5;},'\x67\x44\x68\x65\x6b':function(_0xaa8263,_0x4ec826){return _0xaa8263-_0x4ec826;},'\x46\x4a\x4c\x49\x5a':'\x6e\x75\x6c\x6c','\x6e\x57\x64\x53\x4c':function(_0x3c1c64,_0x258d74){return _0x3c1c64||_0x258d74;},'\x54\x77\x6b\x77\x79':_0x58d552(0x5b3),'\x77\x42\x44\x72\x4e':_0x58d552(0x622)+_0x58d552(0x5ac)+'\x69\x65','\x54\x59\x49\x51\x68':function(_0x2a24fb,_0x39d774){return _0x2a24fb===_0x39d774;},'\x4b\x55\x52\x41\x6d':function(_0x4ca1a7,_0x1170bd,_0xb8c324,_0x274063){return _0x4ca1a7(_0x1170bd,_0xb8c324,_0x274063);},'\x68\x79\x67\x59\x66':'\x73\x65\x74\x2d\x63'+_0x58d552(0x4c6),'\x63\x41\x5a\x72\x50':function(_0x2d9fa5,_0x2cf7d0,_0x5294dc,_0x2826ab){return _0x2d9fa5(_0x2cf7d0,_0x5294dc,_0x2826ab);},'\x44\x6d\x5a\x5a\x43':_0x58d552(0x65f)+_0x58d552(0x6c5)+'\x70\x65','\x63\x77\x7a\x76\x57':'\x43\x6f\x6e\x74\x65'+_0x58d552(0x200)+'\x6e\x67\x74\x68','\x45\x7a\x6d\x76\x76':'\x61\x70\x70\x6c\x69'+_0x58d552(0x39c)+_0x58d552(0x6d6)+_0x58d552(0x1c2)+_0x58d552(0x3cd)+'\x6c\x65\x6e\x63\x6f'+_0x58d552(0x5fe),'\x5a\x4c\x77\x6e\x41':function(_0x5087c6,_0x139c47,_0x14e665,_0x551e10){return _0x5087c6(_0x139c47,_0x14e665,_0x551e10);},'\x64\x5a\x57\x69\x47':function(_0x4af5f8,_0x5c2168){return _0x4af5f8+_0x5c2168;},'\x43\x73\x41\x51\x70':function(_0xe8e01,_0x42787e){return _0xe8e01/_0x42787e;},'\x6a\x72\x4b\x58\x41':function(_0xfee4b0,_0x1032c3){return _0xfee4b0+_0x1032c3;},'\x5a\x47\x45\x65\x70':function(_0x1bc649,_0xb988c7){return _0x1bc649+_0xb988c7;},'\x6b\x58\x58\x72\x43':function(_0x7502d5,_0x3fe3fe){return _0x7502d5+_0x3fe3fe;},'\x73\x46\x61\x4e\x68':function(_0x26502b,_0x4ecf02){return _0x26502b+_0x4ecf02;},'\x43\x73\x72\x68\x51':function(_0xfd32b6,_0x11d90c){return _0xfd32b6==_0x11d90c;},'\x54\x57\x47\x4b\x47':function(_0x2e096c,_0x505886){return _0x2e096c==_0x505886;},'\x59\x54\x56\x74\x73':_0x58d552(0x572)+'\x74','\x45\x71\x73\x59\x53':_0x58d552(0x1cf)+'\x2d\x75\x72\x6c','\x5a\x44\x71\x74\x74':_0x58d552(0x488)+'\x75\x72\x6c','\x4f\x78\x55\x64\x79':_0x58d552(0x3e1)+'\x3d\x3d\x3d\x3d\x3d'+_0x58d552(0x5ee)+'\u7cfb\u7edf\u901a\u77e5\ud83d\udce3'+_0x58d552(0x3e1)+'\x3d\x3d\x3d\x3d\x3d'+'\x3d\x3d\x3d\x3d','\x76\x4b\x70\x6c\x57':function(_0x531d5d,_0x523fe3){return _0x531d5d/_0x523fe3;},'\x67\x68\x7a\x68\x6b':function(_0x396546,_0x4e0cf9){return _0x396546-_0x4e0cf9;},'\x64\x53\x4e\x67\x49':function(_0x359744,_0x240565){return _0x359744>_0x240565;},'\x78\x62\x4d\x46\x4d':_0x58d552(0x613)+'\x42'};_0x5b5639[_0x58d552(0x3e8)](_0x58d552(0x34f)+_0x58d552(0x2a9),typeof process)&&_0x5b5639['\x64\x53\x4e\x67\x49'](JSON['\x73\x74\x72\x69\x6e'+_0x58d552(0x640)](process[_0x58d552(0x29f)])['\x69\x6e\x64\x65\x78'+'\x4f\x66'](_0x5b5639[_0x58d552(0x3a2)]),-(0x3*-0x59f+0x578+0xb66))&&process['\x65\x78\x69\x74'](0xeac+0x130c+0x2*-0x10dc);class _0x541ae0{constructor(_0x12fcf6){const _0x2d9b77=_0x58d552;this[_0x2d9b77(0x29f)]=_0x12fcf6;}[_0x58d552(0x600)](_0x20c859,_0x1d3ada=_0x58d552(0x1d8)){const _0x8d1e1f=_0x58d552,_0x55b285={'\x68\x55\x6b\x75\x6e':function(_0x4b5586,_0x4bd001){return _0x4b5586(_0x4bd001);}};_0x20c859=_0x5b5639['\x41\x6a\x45\x71\x44'](_0x5b5639[_0x8d1e1f(0x4a7)],typeof _0x20c859)?{'\x75\x72\x6c':_0x20c859}:_0x20c859;let _0x39699b=this[_0x8d1e1f(0x537)];return _0x8d1e1f(0x34c)===_0x1d3ada&&(_0x39699b=this[_0x8d1e1f(0x3d9)]),_0x5b5639[_0x8d1e1f(0x2ef)](_0x5b5639[_0x8d1e1f(0x25a)],_0x1d3ada)&&(_0x39699b=this[_0x8d1e1f(0x21d)]),new Promise((_0xe8f277,_0x5a9ad1)=>{const _0x158fbd={'\x42\x6c\x54\x51\x4e':function(_0x140aea,_0x94d3ea){return _0x55b285['\x68\x55\x6b\x75\x6e'](_0x140aea,_0x94d3ea);}};_0x39699b['\x63\x61\x6c\x6c'](this,_0x20c859,(_0x4c185b,_0x102a64,_0x5165f1)=>{const _0x5d64d4=_0x42bc;_0x4c185b?_0x5a9ad1(_0x4c185b):_0x158fbd[_0x5d64d4(0x3f9)](_0xe8f277,_0x102a64);});});}[_0x58d552(0x537)](_0x44d54b){const _0x2b9438=_0x58d552;return this[_0x2b9438(0x600)][_0x2b9438(0x3da)](this['\x65\x6e\x76'],_0x44d54b);}[_0x58d552(0x3d9)](_0x19ed36){const _0x5e2e81=_0x58d552;return this['\x73\x65\x6e\x64'][_0x5e2e81(0x3da)](this['\x65\x6e\x76'],_0x19ed36,_0x5b5639['\x78\x6e\x4e\x52\x4b']);}['\x70\x75\x74'](_0x345b2c){const _0x364250=_0x58d552;return this[_0x364250(0x600)]['\x63\x61\x6c\x6c'](this[_0x364250(0x29f)],_0x345b2c,_0x5b5639[_0x364250(0x25a)]);}}return new class{constructor(_0x4fecb6,_0x5840de){const _0x258ffc=_0x58d552;this[_0x258ffc(0x42c)]=_0x4fecb6,this[_0x258ffc(0x268)]=new _0x541ae0(this),this[_0x258ffc(0x251)]=null,this['\x64\x61\x74\x61\x46'+_0x258ffc(0x3c9)]='\x62\x6f\x78\x2e\x64'+'\x61\x74',this[_0x258ffc(0x666)]=[],this[_0x258ffc(0x3ea)+'\x65']=!(0xb68+-0x1c18+-0x10b1*-0x1),this[_0x258ffc(0x381)+'\x64\x52\x65\x77\x72'+'\x69\x74\x65']=!(0x16a4+0xee*-0x17+-0x141),this['\x6c\x6f\x67\x53\x65'+_0x258ffc(0x229)+'\x6f\x72']='\x0a',this[_0x258ffc(0x286)+'\x54\x69\x6d\x65']=new Date()[_0x258ffc(0x624)+'\x6d\x65'](),Object[_0x258ffc(0x504)+'\x6e'](this,_0x5840de),this[_0x258ffc(0x230)]('','\ud83d\udd14'+this[_0x258ffc(0x42c)]+_0x258ffc(0x3c0));}[_0x58d552(0x3d6)+'\x65'](){const _0x37e49c=_0x58d552;return _0x5b5639[_0x37e49c(0x40a)](_0x5b5639[_0x37e49c(0x680)],typeof module)&&!!module[_0x37e49c(0x23d)+'\x74\x73'];}[_0x58d552(0x459)+'\x6e\x58'](){const _0x14d59e=_0x58d552;return _0x5b5639[_0x14d59e(0x3e8)]('\x75\x6e\x64\x65\x66'+'\x69\x6e\x65\x64',typeof $task);}[_0x58d552(0x589)+'\x67\x65'](){const _0xb8ee66=_0x58d552;return _0x5b5639[_0xb8ee66(0x680)]!=typeof $httpClient&&_0xb8ee66(0x34f)+_0xb8ee66(0x2a9)==typeof $loon;}[_0x58d552(0x64e)+'\x6e'](){const _0x12a547=_0x58d552;return _0x5b5639[_0x12a547(0x680)]!=typeof $loon;}[_0x58d552(0x2c9)](_0x209a78,_0x3eada0=null){const _0x56f3ce=_0x58d552;try{return JSON[_0x56f3ce(0x2a3)](_0x209a78);}catch{return _0x3eada0;}}['\x74\x6f\x53\x74\x72'](_0x443d80,_0x49a81f=null){const _0x494d48=_0x58d552;try{return JSON['\x73\x74\x72\x69\x6e'+_0x494d48(0x640)](_0x443d80);}catch{return _0x49a81f;}}[_0x58d552(0x391)+'\x6f\x6e'](_0x2777ae,_0x284291){const _0x2eca16=_0x58d552;let _0x713d09=_0x284291;const _0x37cda6=this['\x67\x65\x74\x64\x61'+'\x74\x61'](_0x2777ae);if(_0x37cda6)try{_0x713d09=JSON[_0x2eca16(0x2a3)](this[_0x2eca16(0x40c)+'\x74\x61'](_0x2777ae));}catch{}return _0x713d09;}[_0x58d552(0x4f0)+'\x6f\x6e'](_0xc3d166,_0x37b0dc){const _0x2db2c7=_0x58d552;try{return this[_0x2db2c7(0x3d1)+'\x74\x61'](JSON[_0x2db2c7(0x3dc)+_0x2db2c7(0x640)](_0xc3d166),_0x37b0dc);}catch{return!(0xca7+-0x7a0+0x283*-0x2);}}[_0x58d552(0x4d8)+_0x58d552(0x451)](_0x25ddff){return new Promise(_0x586dcf=>{const _0x38b04f=_0x42bc,_0x5da338={};_0x5da338['\x75\x72\x6c']=_0x25ddff,this[_0x38b04f(0x537)](_0x5da338,(_0x26642e,_0x2c8a36,_0x279190)=>_0x586dcf(_0x279190));});}[_0x58d552(0x545)+_0x58d552(0x451)](_0x3bcb46,_0x206c58){const _0xfa009d=_0x58d552,_0x403bdc={'\x4e\x56\x61\x74\x57':_0x5b5639[_0xfa009d(0x50a)],'\x55\x4c\x43\x6b\x65':function(_0x279e99,_0x51a3dc){const _0x3eb3b5=_0xfa009d;return _0x5b5639[_0x3eb3b5(0x5e2)](_0x279e99,_0x51a3dc);},'\x68\x6e\x6b\x53\x42':_0x5b5639[_0xfa009d(0x68b)]};return new Promise(_0x21a44b=>{const _0x5b5aa3=_0xfa009d;let _0x2593f4=this[_0x5b5aa3(0x40c)+'\x74\x61'](_0x5b5aa3(0x669)+_0x5b5aa3(0x592)+_0x5b5aa3(0x2b2)+'\x65\x72\x43\x66\x67'+_0x5b5aa3(0x327)+_0x5b5aa3(0x409));_0x2593f4=_0x2593f4?_0x2593f4['\x72\x65\x70\x6c\x61'+'\x63\x65'](/\n/g,'')[_0x5b5aa3(0x565)]():_0x2593f4;let _0x19c50a=this[_0x5b5aa3(0x40c)+'\x74\x61'](_0x403bdc[_0x5b5aa3(0x3c8)]);_0x19c50a=_0x19c50a?_0x403bdc[_0x5b5aa3(0x478)](0x133c*0x2+-0x1*-0x1a8e+0x1*-0x4105,_0x19c50a):0xfa*-0x5+0x2222+-0x1d2c,_0x19c50a=_0x206c58&&_0x206c58['\x74\x69\x6d\x65\x6f'+'\x75\x74']?_0x206c58[_0x5b5aa3(0x468)+'\x75\x74']:_0x19c50a;const _0x43b68c={};_0x43b68c[_0x5b5aa3(0x4ee)+'\x74\x5f\x74\x65\x78'+'\x74']=_0x3bcb46,_0x43b68c[_0x5b5aa3(0x3a9)+_0x5b5aa3(0x5d3)]=_0x403bdc[_0x5b5aa3(0x373)],_0x43b68c[_0x5b5aa3(0x468)+'\x75\x74']=_0x19c50a;const [_0x29625f,_0x2cc7a3]=_0x2593f4[_0x5b5aa3(0x660)]('\x40'),_0x4038b3={'\x75\x72\x6c':'\x68\x74\x74\x70\x3a'+'\x2f\x2f'+_0x2cc7a3+(_0x5b5aa3(0x62a)+_0x5b5aa3(0x6df)+_0x5b5aa3(0x1e6)+'\x76\x61\x6c\x75\x61'+'\x74\x65'),'\x62\x6f\x64\x79':_0x43b68c,'\x68\x65\x61\x64\x65\x72\x73':{'\x58\x2d\x4b\x65\x79':_0x29625f,'\x41\x63\x63\x65\x70\x74':_0x5b5aa3(0x32c)}};this[_0x5b5aa3(0x3d9)](_0x4038b3,(_0x2105d3,_0x24eadb,_0x4f5cac)=>_0x21a44b(_0x4f5cac));})[_0xfa009d(0x4a3)](_0x1a4320=>this['\x6c\x6f\x67\x45\x72'+'\x72'](_0x1a4320));}[_0x58d552(0x41e)+_0x58d552(0x6c7)](){const _0x3223e8=_0x58d552;if(!this[_0x3223e8(0x3d6)+'\x65']())return{};{this['\x66\x73']=this['\x66\x73']?this['\x66\x73']:require('\x66\x73'),this[_0x3223e8(0x2bc)]=this[_0x3223e8(0x2bc)]?this[_0x3223e8(0x2bc)]:_0x5b5639[_0x3223e8(0x20d)](require,_0x5b5639[_0x3223e8(0x321)]);const _0x57be57=this['\x70\x61\x74\x68'][_0x3223e8(0x303)+'\x76\x65'](this[_0x3223e8(0x439)+_0x3223e8(0x3c9)]),_0x5ef36a=this[_0x3223e8(0x2bc)][_0x3223e8(0x303)+'\x76\x65'](process[_0x3223e8(0x50b)](),this['\x64\x61\x74\x61\x46'+_0x3223e8(0x3c9)]),_0x53286a=this['\x66\x73']['\x65\x78\x69\x73\x74'+_0x3223e8(0x5b8)](_0x57be57),_0x3a0648=!_0x53286a&&this['\x66\x73'][_0x3223e8(0x601)+'\x73\x53\x79\x6e\x63'](_0x5ef36a);if(_0x5b5639[_0x3223e8(0x2f6)](!_0x53286a,!_0x3a0648))return{};{const _0x4b6f2e=_0x53286a?_0x57be57:_0x5ef36a;try{return JSON[_0x3223e8(0x2a3)](this['\x66\x73']['\x72\x65\x61\x64\x46'+_0x3223e8(0x403)+'\x6e\x63'](_0x4b6f2e));}catch(_0x5f1336){return{};}}}}[_0x58d552(0x512)+'\x64\x61\x74\x61'](){const _0x4319a2=_0x58d552;if(this[_0x4319a2(0x3d6)+'\x65']()){this['\x66\x73']=this['\x66\x73']?this['\x66\x73']:_0x5b5639[_0x4319a2(0x20d)](require,'\x66\x73'),this[_0x4319a2(0x2bc)]=this[_0x4319a2(0x2bc)]?this[_0x4319a2(0x2bc)]:_0x5b5639[_0x4319a2(0x20d)](require,_0x4319a2(0x2bc));const _0x262820=this[_0x4319a2(0x2bc)][_0x4319a2(0x303)+'\x76\x65'](this[_0x4319a2(0x439)+'\x69\x6c\x65']),_0x40761f=this[_0x4319a2(0x2bc)][_0x4319a2(0x303)+'\x76\x65'](process['\x63\x77\x64'](),this[_0x4319a2(0x439)+_0x4319a2(0x3c9)]),_0x1d488b=this['\x66\x73']['\x65\x78\x69\x73\x74'+_0x4319a2(0x5b8)](_0x262820),_0x83f1a2=!_0x1d488b&&this['\x66\x73'][_0x4319a2(0x601)+'\x73\x53\x79\x6e\x63'](_0x40761f),_0x3e4546=JSON[_0x4319a2(0x3dc)+_0x4319a2(0x640)](this[_0x4319a2(0x251)]);_0x1d488b?this['\x66\x73'][_0x4319a2(0x512)+_0x4319a2(0x22d)+_0x4319a2(0x4ad)](_0x262820,_0x3e4546):_0x83f1a2?this['\x66\x73'][_0x4319a2(0x512)+'\x46\x69\x6c\x65\x53'+_0x4319a2(0x4ad)](_0x40761f,_0x3e4546):this['\x66\x73'][_0x4319a2(0x512)+_0x4319a2(0x22d)+_0x4319a2(0x4ad)](_0x262820,_0x3e4546);}}[_0x58d552(0x69b)+_0x58d552(0x2d1)](_0xb6fdcd,_0x29e54e,_0x4a43b7){const _0x550205=_0x58d552,_0x14d4ea=_0x29e54e[_0x550205(0x4dc)+'\x63\x65'](/\[(\d+)\]/g,_0x550205(0x38e))[_0x550205(0x660)]('\x2e');let _0x5d7645=_0xb6fdcd;for(const _0x40e7ca of _0x14d4ea)if(_0x5d7645=_0x5b5639['\x55\x51\x63\x6f\x57'](Object,_0x5d7645)[_0x40e7ca],void(-0x1*0x2239+0x16c4*0x1+0xb75)===_0x5d7645)return _0x4a43b7;return _0x5d7645;}['\x6c\x6f\x64\x61\x73'+'\x68\x5f\x73\x65\x74'](_0x57f4f9,_0x34303e,_0x1a1d29){const _0xb72d73=_0x58d552;return _0x5b5639['\x65\x4e\x50\x4a\x49'](Object(_0x57f4f9),_0x57f4f9)?_0x57f4f9:(Array[_0xb72d73(0x5cb)+'\x61\x79'](_0x34303e)||(_0x34303e=_0x34303e[_0xb72d73(0x326)+'\x69\x6e\x67']()[_0xb72d73(0x1dc)](/[^.[\]]+/g)||[]),_0x34303e[_0xb72d73(0x252)](-0x1d46+-0xca*-0x4+0x1a1e,-(0x136*-0x20+-0x13be+0x3a7f))['\x72\x65\x64\x75\x63'+'\x65']((_0x400ae8,_0x6a7404,_0x4e60a9)=>Object(_0x400ae8[_0x6a7404])===_0x400ae8[_0x6a7404]?_0x400ae8[_0x6a7404]:_0x400ae8[_0x6a7404]=Math['\x61\x62\x73'](_0x34303e[_0x4e60a9+(-0x6ad*0x2+-0x22d5*0x1+0x1010*0x3)])>>-0x1ebc+-0xc89*-0x1+0x3*0x611==+_0x34303e[_0x4e60a9+(0x14a3+-0x2*0x8e9+0x14*-0x24)]?[]:{},_0x57f4f9)[_0x34303e[_0x5b5639[_0xb72d73(0x5f2)](_0x34303e[_0xb72d73(0x2bd)+'\x68'],0xb57*-0x1+0x5c1+0x597)]]=_0x1a1d29,_0x57f4f9);}[_0x58d552(0x40c)+'\x74\x61'](_0x58af97){const _0x1caaae=_0x58d552;let _0x49c8c7=this[_0x1caaae(0x22b)+'\x6c'](_0x58af97);if(/^@/[_0x1caaae(0x31b)](_0x58af97)){const [,_0x16fb2c,_0x8154aa]=/^@(.*?)\.(.*?)$/[_0x1caaae(0x59c)](_0x58af97),_0x579b6d=_0x16fb2c?this[_0x1caaae(0x22b)+'\x6c'](_0x16fb2c):'';if(_0x579b6d)try{const _0xe440c8=JSON[_0x1caaae(0x2a3)](_0x579b6d);_0x49c8c7=_0xe440c8?this[_0x1caaae(0x69b)+'\x68\x5f\x67\x65\x74'](_0xe440c8,_0x8154aa,''):_0x49c8c7;}catch(_0x7d05bf){_0x49c8c7='';}}return _0x49c8c7;}[_0x58d552(0x3d1)+'\x74\x61'](_0x36ff22,_0x4cf9ee){const _0x1ff6db=_0x58d552;let _0x5b409a=!(-0x1171+0x5*-0x7be+0x705*0x8);if(/^@/[_0x1ff6db(0x31b)](_0x4cf9ee)){const [,_0x1dd168,_0xb451cc]=/^@(.*?)\.(.*?)$/[_0x1ff6db(0x59c)](_0x4cf9ee),_0xb8962f=this[_0x1ff6db(0x22b)+'\x6c'](_0x1dd168),_0x2f750b=_0x1dd168?_0x5b5639[_0x1ff6db(0x2ef)](_0x5b5639[_0x1ff6db(0x51e)],_0xb8962f)?null:_0x5b5639[_0x1ff6db(0x278)](_0xb8962f,'\x7b\x7d'):'\x7b\x7d';try{const _0x46ccb0=JSON['\x70\x61\x72\x73\x65'](_0x2f750b);this[_0x1ff6db(0x69b)+_0x1ff6db(0x33d)](_0x46ccb0,_0xb451cc,_0x36ff22),_0x5b409a=this[_0x1ff6db(0x5ba)+'\x6c'](JSON[_0x1ff6db(0x3dc)+_0x1ff6db(0x640)](_0x46ccb0),_0x1dd168);}catch(_0x5bcf73){const _0x9b4445={};this[_0x1ff6db(0x69b)+_0x1ff6db(0x33d)](_0x9b4445,_0xb451cc,_0x36ff22),_0x5b409a=this[_0x1ff6db(0x5ba)+'\x6c'](JSON[_0x1ff6db(0x3dc)+'\x67\x69\x66\x79'](_0x9b4445),_0x1dd168);}}else _0x5b409a=this[_0x1ff6db(0x5ba)+'\x6c'](_0x36ff22,_0x4cf9ee);return _0x5b409a;}['\x67\x65\x74\x76\x61'+'\x6c'](_0x539720){const _0x593bdf=_0x58d552;return this[_0x593bdf(0x589)+'\x67\x65']()||this[_0x593bdf(0x64e)+'\x6e']()?$persistentStore[_0x593bdf(0x5e8)](_0x539720):this[_0x593bdf(0x459)+'\x6e\x58']()?$prefs[_0x593bdf(0x3d2)+'\x46\x6f\x72\x4b\x65'+'\x79'](_0x539720):this[_0x593bdf(0x3d6)+'\x65']()?(this[_0x593bdf(0x251)]=this[_0x593bdf(0x41e)+_0x593bdf(0x6c7)](),this[_0x593bdf(0x251)][_0x539720]):this[_0x593bdf(0x251)]&&this[_0x593bdf(0x251)][_0x539720]||null;}[_0x58d552(0x5ba)+'\x6c'](_0x4b7d2a,_0x21898b){const _0x5be65b=_0x58d552;return this[_0x5be65b(0x589)+'\x67\x65']()||this[_0x5be65b(0x64e)+'\x6e']()?$persistentStore[_0x5be65b(0x512)](_0x4b7d2a,_0x21898b):this[_0x5be65b(0x459)+'\x6e\x58']()?$prefs['\x73\x65\x74\x56\x61'+'\x6c\x75\x65\x46\x6f'+'\x72\x4b\x65\x79'](_0x4b7d2a,_0x21898b):this[_0x5be65b(0x3d6)+'\x65']()?(this[_0x5be65b(0x251)]=this[_0x5be65b(0x41e)+'\x61\x74\x61'](),this['\x64\x61\x74\x61'][_0x21898b]=_0x4b7d2a,this['\x77\x72\x69\x74\x65'+_0x5be65b(0x251)](),!(0x18d8+-0x1d*0x1a+-0x15e6)):this['\x64\x61\x74\x61']&&this[_0x5be65b(0x251)][_0x21898b]||null;}[_0x58d552(0x223)+_0x58d552(0x212)](_0x239571){const _0x387a84=_0x58d552;this[_0x387a84(0x5b3)]=this['\x67\x6f\x74']?this[_0x387a84(0x5b3)]:_0x5b5639[_0x387a84(0x20d)](require,_0x5b5639[_0x387a84(0x330)]),this[_0x387a84(0x6d1)+'\x67\x68']=this[_0x387a84(0x6d1)+'\x67\x68']?this[_0x387a84(0x6d1)+'\x67\x68']:_0x5b5639['\x55\x51\x63\x6f\x57'](require,_0x5b5639['\x77\x42\x44\x72\x4e']),this[_0x387a84(0x614)]=this[_0x387a84(0x614)]?this[_0x387a84(0x614)]:new this['\x63\x6b\x74\x6f\x75'+'\x67\x68'][(_0x387a84(0x3ab))+'\x65\x4a\x61\x72'](),_0x239571&&(_0x239571[_0x387a84(0x4a9)+'\x72\x73']=_0x239571[_0x387a84(0x4a9)+'\x72\x73']?_0x239571[_0x387a84(0x4a9)+'\x72\x73']:{},_0x5b5639[_0x387a84(0x298)](void(-0x152c+-0x13*-0x185+-0x7b3),_0x239571[_0x387a84(0x4a9)+'\x72\x73']['\x43\x6f\x6f\x6b\x69'+'\x65'])&&void(-0x2398+0xe7*-0x27+0x46c9)===_0x239571[_0x387a84(0x6c1)+_0x387a84(0x3d4)]&&(_0x239571[_0x387a84(0x6c1)+_0x387a84(0x3d4)]=this[_0x387a84(0x614)]));}[_0x58d552(0x537)](_0x187cc9,_0x192ecf=()=>{}){const _0x3ce730=_0x58d552,_0x5ba34c={'\x70\x46\x54\x74\x6e':function(_0x25e09f,_0x464761){const _0x1b237b=_0x42bc;return _0x5b5639[_0x1b237b(0x2f6)](_0x25e09f,_0x464761);},'\x73\x72\x4e\x77\x64':function(_0x1190a8,_0x373572,_0x42bd88,_0x41b62f){const _0x4e91bf=_0x42bc;return _0x5b5639[_0x4e91bf(0x57c)](_0x1190a8,_0x373572,_0x42bd88,_0x41b62f);}},_0x16ad6b={};_0x16ad6b['\x58\x2d\x53\x75\x72'+'\x67\x65\x2d\x53\x6b'+_0x3ce730(0x6d5)+_0x3ce730(0x5fb)+'\x6e\x67']=!(0x31f*0x3+-0x1*-0xdbe+-0x171a);const _0x4ba8e0={};_0x4ba8e0[_0x3ce730(0x4a6)]=!(-0x1c6f+0x8*-0x2+0x1c80),(_0x187cc9[_0x3ce730(0x4a9)+'\x72\x73']&&(delete _0x187cc9[_0x3ce730(0x4a9)+'\x72\x73'][_0x5b5639[_0x3ce730(0x5c9)]],delete _0x187cc9[_0x3ce730(0x4a9)+'\x72\x73'][_0x5b5639[_0x3ce730(0x4fa)]]),this['\x69\x73\x53\x75\x72'+'\x67\x65']()||this[_0x3ce730(0x64e)+'\x6e']()?(this[_0x3ce730(0x589)+'\x67\x65']()&&this[_0x3ce730(0x381)+_0x3ce730(0x668)+_0x3ce730(0x2fd)]&&(_0x187cc9[_0x3ce730(0x4a9)+'\x72\x73']=_0x187cc9['\x68\x65\x61\x64\x65'+'\x72\x73']||{},Object[_0x3ce730(0x504)+'\x6e'](_0x187cc9['\x68\x65\x61\x64\x65'+'\x72\x73'],_0x16ad6b)),$httpClient['\x67\x65\x74'](_0x187cc9,(_0x29ee0d,_0x2428e0,_0x48c81a)=>{const _0x343d56=_0x3ce730;_0x5ba34c['\x70\x46\x54\x74\x6e'](!_0x29ee0d,_0x2428e0)&&(_0x2428e0[_0x343d56(0x5e4)]=_0x48c81a,_0x2428e0['\x73\x74\x61\x74\x75'+_0x343d56(0x276)]=_0x2428e0[_0x343d56(0x5d9)+'\x73']),_0x5ba34c[_0x343d56(0x61a)](_0x192ecf,_0x29ee0d,_0x2428e0,_0x48c81a);})):this[_0x3ce730(0x459)+'\x6e\x58']()?(this['\x69\x73\x4e\x65\x65'+_0x3ce730(0x668)+_0x3ce730(0x2fd)]&&(_0x187cc9[_0x3ce730(0x1f2)]=_0x187cc9[_0x3ce730(0x1f2)]||{},Object[_0x3ce730(0x504)+'\x6e'](_0x187cc9['\x6f\x70\x74\x73'],_0x4ba8e0)),$task[_0x3ce730(0x6c2)](_0x187cc9)[_0x3ce730(0x53d)](_0x2f3cdd=>{const _0x57d57d=_0x3ce730,{statusCode:_0x2a8507,statusCode:_0x2a249d,headers:_0x366539,body:_0x23e568}=_0x2f3cdd,_0x1dfadf={};_0x1dfadf['\x73\x74\x61\x74\x75'+'\x73']=_0x2a8507,_0x1dfadf[_0x57d57d(0x5d9)+_0x57d57d(0x276)]=_0x2a249d,_0x1dfadf['\x68\x65\x61\x64\x65'+'\x72\x73']=_0x366539,_0x1dfadf['\x62\x6f\x64\x79']=_0x23e568,_0x5b5639[_0x57d57d(0x679)](_0x192ecf,null,_0x1dfadf,_0x23e568);},_0x2a7441=>_0x192ecf(_0x2a7441))):this[_0x3ce730(0x3d6)+'\x65']()&&(this['\x69\x6e\x69\x74\x47'+_0x3ce730(0x212)](_0x187cc9),this[_0x3ce730(0x5b3)](_0x187cc9)['\x6f\x6e'](_0x3ce730(0x24a)+_0x3ce730(0x5f9),(_0x48080d,_0xb52510)=>{const _0x21205b=_0x3ce730;try{if(_0x48080d['\x68\x65\x61\x64\x65'+'\x72\x73'][_0x21205b(0x5f4)+_0x21205b(0x4c6)]){const _0x5405de=_0x48080d[_0x21205b(0x4a9)+'\x72\x73'][_0x5b5639[_0x21205b(0x44e)]][_0x21205b(0x2dc)](this[_0x21205b(0x6d1)+'\x67\x68'][_0x21205b(0x3ab)+'\x65'][_0x21205b(0x2a3)])[_0x21205b(0x326)+_0x21205b(0x67e)]();this[_0x21205b(0x614)][_0x21205b(0x57d)+_0x21205b(0x4ac)+_0x21205b(0x4ad)](_0x5405de,null),_0xb52510[_0x21205b(0x6c1)+'\x65\x4a\x61\x72']=this[_0x21205b(0x614)];}}catch(_0x21619b){this[_0x21205b(0x608)+'\x72'](_0x21619b);}})[_0x3ce730(0x53d)](_0x59ce08=>{const _0x1a6b6c=_0x3ce730,{statusCode:_0x13b600,statusCode:_0x2dac65,headers:_0x4e0e9b,body:_0xc0022d}=_0x59ce08,_0x5ca8ba={};_0x5ca8ba['\x73\x74\x61\x74\x75'+'\x73']=_0x13b600,_0x5ca8ba[_0x1a6b6c(0x5d9)+'\x73\x43\x6f\x64\x65']=_0x2dac65,_0x5ca8ba[_0x1a6b6c(0x4a9)+'\x72\x73']=_0x4e0e9b,_0x5ca8ba[_0x1a6b6c(0x5e4)]=_0xc0022d,_0x5ba34c[_0x1a6b6c(0x61a)](_0x192ecf,null,_0x5ca8ba,_0xc0022d);},_0x77540c=>{const _0x196204=_0x3ce730,{message:_0x4ee19e,response:_0x41b64e}=_0x77540c;_0x192ecf(_0x4ee19e,_0x41b64e,_0x41b64e&&_0x41b64e[_0x196204(0x5e4)]);})));}[_0x58d552(0x3d9)](_0x3084fa,_0x2fbb9c=()=>{}){const _0x146ba2=_0x58d552,_0x4b3e07={'\x6b\x73\x59\x76\x54':function(_0x35b888,_0x4c860c,_0x12d16c,_0x3b3e81){return _0x5b5639['\x4b\x55\x52\x41\x6d'](_0x35b888,_0x4c860c,_0x12d16c,_0x3b3e81);},'\x63\x48\x42\x79\x54':function(_0x22c9ba,_0x15e09b,_0x2f9ff2,_0x27d0dc){const _0x3a1db4=_0x42bc;return _0x5b5639[_0x3a1db4(0x57c)](_0x22c9ba,_0x15e09b,_0x2f9ff2,_0x27d0dc);}},_0x3fd3ae={};_0x3fd3ae[_0x146ba2(0x693)+_0x146ba2(0x269)+_0x146ba2(0x6d5)+_0x146ba2(0x5fb)+'\x6e\x67']=!(-0x2174+-0x6bb+0x2830);const _0x5a5d64={};_0x5a5d64[_0x146ba2(0x4a6)]=!(0x4*0x8f3+0x1461+-0x382c);if(_0x3084fa[_0x146ba2(0x5e4)]&&_0x3084fa[_0x146ba2(0x4a9)+'\x72\x73']&&!_0x3084fa[_0x146ba2(0x4a9)+'\x72\x73'][_0x146ba2(0x65f)+_0x146ba2(0x6c5)+'\x70\x65']&&(_0x3084fa[_0x146ba2(0x4a9)+'\x72\x73'][_0x5b5639[_0x146ba2(0x5c9)]]=_0x5b5639['\x45\x7a\x6d\x76\x76']),_0x3084fa[_0x146ba2(0x4a9)+'\x72\x73']&&delete _0x3084fa['\x68\x65\x61\x64\x65'+'\x72\x73'][_0x5b5639[_0x146ba2(0x4fa)]],this['\x69\x73\x53\x75\x72'+'\x67\x65']()||this[_0x146ba2(0x64e)+'\x6e']())this[_0x146ba2(0x589)+'\x67\x65']()&&this[_0x146ba2(0x381)+'\x64\x52\x65\x77\x72'+_0x146ba2(0x2fd)]&&(_0x3084fa[_0x146ba2(0x4a9)+'\x72\x73']=_0x3084fa[_0x146ba2(0x4a9)+'\x72\x73']||{},Object['\x61\x73\x73\x69\x67'+'\x6e'](_0x3084fa[_0x146ba2(0x4a9)+'\x72\x73'],_0x3fd3ae)),$httpClient[_0x146ba2(0x3d9)](_0x3084fa,(_0xb2eba8,_0x10ac7d,_0xe3c9e7)=>{const _0x2625af=_0x146ba2;!_0xb2eba8&&_0x10ac7d&&(_0x10ac7d['\x62\x6f\x64\x79']=_0xe3c9e7,_0x10ac7d[_0x2625af(0x5d9)+_0x2625af(0x276)]=_0x10ac7d[_0x2625af(0x5d9)+'\x73']),_0x4b3e07[_0x2625af(0x55e)](_0x2fbb9c,_0xb2eba8,_0x10ac7d,_0xe3c9e7);});else{if(this[_0x146ba2(0x459)+'\x6e\x58']())_0x3084fa[_0x146ba2(0x334)+'\x64']=_0x5b5639[_0x146ba2(0x3c7)],this['\x69\x73\x4e\x65\x65'+_0x146ba2(0x668)+_0x146ba2(0x2fd)]&&(_0x3084fa[_0x146ba2(0x1f2)]=_0x3084fa[_0x146ba2(0x1f2)]||{},Object[_0x146ba2(0x504)+'\x6e'](_0x3084fa[_0x146ba2(0x1f2)],_0x5a5d64)),$task[_0x146ba2(0x6c2)](_0x3084fa)['\x74\x68\x65\x6e'](_0x2091cc=>{const _0x3dd9d5=_0x146ba2,{statusCode:_0x4805cd,statusCode:_0x17c7c3,headers:_0x8cb443,body:_0x3ceaac}=_0x2091cc,_0x149402={};_0x149402[_0x3dd9d5(0x5d9)+'\x73']=_0x4805cd,_0x149402[_0x3dd9d5(0x5d9)+_0x3dd9d5(0x276)]=_0x17c7c3,_0x149402[_0x3dd9d5(0x4a9)+'\x72\x73']=_0x8cb443,_0x149402['\x62\x6f\x64\x79']=_0x3ceaac,_0x5b5639[_0x3dd9d5(0x57c)](_0x2fbb9c,null,_0x149402,_0x3ceaac);},_0x1fa447=>_0x2fbb9c(_0x1fa447));else{if(this[_0x146ba2(0x3d6)+'\x65']()){this[_0x146ba2(0x223)+'\x6f\x74\x45\x6e\x76'](_0x3084fa);const {url:_0x572548,..._0x2c622f}=_0x3084fa;this[_0x146ba2(0x5b3)][_0x146ba2(0x3d9)](_0x572548,_0x2c622f)[_0x146ba2(0x53d)](_0x5b4204=>{const _0x20a9ca=_0x146ba2,{statusCode:_0x4e15c7,statusCode:_0x5adbce,headers:_0x29efdc,body:_0x483aa0}=_0x5b4204,_0x59680a={};_0x59680a[_0x20a9ca(0x5d9)+'\x73']=_0x4e15c7,_0x59680a[_0x20a9ca(0x5d9)+_0x20a9ca(0x276)]=_0x5adbce,_0x59680a['\x68\x65\x61\x64\x65'+'\x72\x73']=_0x29efdc,_0x59680a[_0x20a9ca(0x5e4)]=_0x483aa0,_0x4b3e07[_0x20a9ca(0x205)](_0x2fbb9c,null,_0x59680a,_0x483aa0);},_0x279f28=>{const _0x30fa9c=_0x146ba2,{message:_0x19630e,response:_0x593530}=_0x279f28;_0x4b3e07[_0x30fa9c(0x55e)](_0x2fbb9c,_0x19630e,_0x593530,_0x593530&&_0x593530['\x62\x6f\x64\x79']);});}}}}[_0x58d552(0x21d)](_0x1997a9,_0xcd7816=()=>{}){const _0x4bb2fa=_0x58d552,_0x4c40fa={'\x62\x54\x73\x67\x69':function(_0x5d2885,_0xaefab0,_0x243ba0,_0x3f819d){return _0x5b5639['\x4b\x55\x52\x41\x6d'](_0x5d2885,_0xaefab0,_0x243ba0,_0x3f819d);},'\x4d\x49\x55\x77\x6c':function(_0x157cd9,_0x31aad2,_0x453f43,_0x52c0ab){const _0x7cfb33=_0x42bc;return _0x5b5639[_0x7cfb33(0x57c)](_0x157cd9,_0x31aad2,_0x453f43,_0x52c0ab);}},_0x51617d={};_0x51617d['\x58\x2d\x53\x75\x72'+'\x67\x65\x2d\x53\x6b'+_0x4bb2fa(0x6d5)+'\x72\x69\x70\x74\x69'+'\x6e\x67']=!(0x25*0x99+0x23e6+-0x87*0x6e);const _0x53993d={};_0x53993d[_0x4bb2fa(0x4a6)]=!(0x58*0x9+0x42*-0x12+-0x18d*-0x1);if(_0x1997a9['\x62\x6f\x64\x79']&&_0x1997a9[_0x4bb2fa(0x4a9)+'\x72\x73']&&!_0x1997a9['\x68\x65\x61\x64\x65'+'\x72\x73']['\x43\x6f\x6e\x74\x65'+_0x4bb2fa(0x6c5)+'\x70\x65']&&(_0x1997a9[_0x4bb2fa(0x4a9)+'\x72\x73'][_0x5b5639[_0x4bb2fa(0x5c9)]]=_0x5b5639[_0x4bb2fa(0x41a)]),_0x1997a9[_0x4bb2fa(0x4a9)+'\x72\x73']&&delete _0x1997a9[_0x4bb2fa(0x4a9)+'\x72\x73'][_0x4bb2fa(0x65f)+'\x6e\x74\x2d\x4c\x65'+'\x6e\x67\x74\x68'],this['\x69\x73\x53\x75\x72'+'\x67\x65']()||this[_0x4bb2fa(0x64e)+'\x6e']())this[_0x4bb2fa(0x589)+'\x67\x65']()&&this[_0x4bb2fa(0x381)+'\x64\x52\x65\x77\x72'+_0x4bb2fa(0x2fd)]&&(_0x1997a9[_0x4bb2fa(0x4a9)+'\x72\x73']=_0x1997a9[_0x4bb2fa(0x4a9)+'\x72\x73']||{},Object['\x61\x73\x73\x69\x67'+'\x6e'](_0x1997a9[_0x4bb2fa(0x4a9)+'\x72\x73'],_0x51617d)),$httpClient[_0x4bb2fa(0x21d)](_0x1997a9,(_0x30828d,_0x26a708,_0x3f8b57)=>{const _0x1d585c=_0x4bb2fa;!_0x30828d&&_0x26a708&&(_0x26a708[_0x1d585c(0x5e4)]=_0x3f8b57,_0x26a708['\x73\x74\x61\x74\x75'+_0x1d585c(0x276)]=_0x26a708[_0x1d585c(0x5d9)+'\x73']),_0x4c40fa[_0x1d585c(0x413)](_0xcd7816,_0x30828d,_0x26a708,_0x3f8b57);});else{if(this['\x69\x73\x51\x75\x61'+'\x6e\x58']())_0x1997a9[_0x4bb2fa(0x334)+'\x64']=_0x4bb2fa(0x219),this['\x69\x73\x4e\x65\x65'+_0x4bb2fa(0x668)+_0x4bb2fa(0x2fd)]&&(_0x1997a9[_0x4bb2fa(0x1f2)]=_0x1997a9['\x6f\x70\x74\x73']||{},Object[_0x4bb2fa(0x504)+'\x6e'](_0x1997a9[_0x4bb2fa(0x1f2)],_0x53993d)),$task['\x66\x65\x74\x63\x68'](_0x1997a9)[_0x4bb2fa(0x53d)](_0x558b34=>{const _0x371b41=_0x4bb2fa,{statusCode:_0x434537,statusCode:_0x267464,headers:_0x133bf1,body:_0x3ce114}=_0x558b34,_0x2cf39e={};_0x2cf39e['\x73\x74\x61\x74\x75'+'\x73']=_0x434537,_0x2cf39e[_0x371b41(0x5d9)+_0x371b41(0x276)]=_0x267464,_0x2cf39e[_0x371b41(0x4a9)+'\x72\x73']=_0x133bf1,_0x2cf39e[_0x371b41(0x5e4)]=_0x3ce114,_0x4c40fa[_0x371b41(0x263)](_0xcd7816,null,_0x2cf39e,_0x3ce114);},_0x52ca6a=>_0xcd7816(_0x52ca6a));else{if(this[_0x4bb2fa(0x3d6)+'\x65']()){this[_0x4bb2fa(0x223)+'\x6f\x74\x45\x6e\x76'](_0x1997a9);const {url:_0x1637b6,..._0x2d8510}=_0x1997a9;this[_0x4bb2fa(0x5b3)][_0x4bb2fa(0x21d)](_0x1637b6,_0x2d8510)['\x74\x68\x65\x6e'](_0x2787c8=>{const _0xfc8ed7=_0x4bb2fa,{statusCode:_0x31f71a,statusCode:_0x5665ce,headers:_0x1683a6,body:_0x22b783}=_0x2787c8,_0xcc595e={};_0xcc595e[_0xfc8ed7(0x5d9)+'\x73']=_0x31f71a,_0xcc595e[_0xfc8ed7(0x5d9)+_0xfc8ed7(0x276)]=_0x5665ce,_0xcc595e['\x68\x65\x61\x64\x65'+'\x72\x73']=_0x1683a6,_0xcc595e[_0xfc8ed7(0x5e4)]=_0x22b783,_0x4c40fa['\x62\x54\x73\x67\x69'](_0xcd7816,null,_0xcc595e,_0x22b783);},_0x4acd24=>{const _0x12e2fe=_0x4bb2fa,{message:_0x985a7e,response:_0x25b900}=_0x4acd24;_0x5b5639[_0x12e2fe(0x2ca)](_0xcd7816,_0x985a7e,_0x25b900,_0x25b900&&_0x25b900[_0x12e2fe(0x5e4)]);});}}}}[_0x58d552(0x4c3)](_0x4afa6b){const _0x260abc=_0x58d552;let _0xcba5d1={'\x4d\x2b':_0x5b5639['\x64\x5a\x57\x69\x47'](new Date()[_0x260abc(0x47e)+_0x260abc(0x56a)](),-0x15cb+0x2238+-0xd4*0xf),'\x64\x2b':new Date()[_0x260abc(0x411)+'\x74\x65'](),'\x48\x2b':new Date()['\x67\x65\x74\x48\x6f'+_0x260abc(0x1d9)](),'\x6d\x2b':new Date()[_0x260abc(0x1e7)+_0x260abc(0x654)](),'\x73\x2b':new Date()[_0x260abc(0x518)+_0x260abc(0x410)](),'\x71\x2b':Math[_0x260abc(0x35b)](_0x5b5639[_0x260abc(0x336)](_0x5b5639[_0x260abc(0x4f3)](new Date()[_0x260abc(0x47e)+_0x260abc(0x56a)](),0x89c+-0x1cbb*-0x1+-0x2554),0x910+0x170c+-0x391*0x9)),'\x53':new Date()[_0x260abc(0x1e7)+_0x260abc(0x4e0)+'\x63\x6f\x6e\x64\x73']()};/(y+)/[_0x260abc(0x31b)](_0x4afa6b)&&(_0x4afa6b=_0x4afa6b['\x72\x65\x70\x6c\x61'+'\x63\x65'](RegExp['\x24\x31'],_0x5b5639[_0x260abc(0x4d7)](new Date()['\x67\x65\x74\x46\x75'+_0x260abc(0x4da)+'\x72'](),'')['\x73\x75\x62\x73\x74'+'\x72'](0xb63*0x2+-0x32b*-0x2+0x4*-0x746-RegExp['\x24\x31'][_0x260abc(0x2bd)+'\x68'])));for(let _0x1cc9b8 in _0xcba5d1)new RegExp(_0x5b5639['\x6a\x72\x4b\x58\x41']('\x28'+_0x1cc9b8,'\x29'))[_0x260abc(0x31b)](_0x4afa6b)&&(_0x4afa6b=_0x4afa6b['\x72\x65\x70\x6c\x61'+'\x63\x65'](RegExp['\x24\x31'],-0x47d*0x5+-0x1de8+0x1a2d*0x2==RegExp['\x24\x31'][_0x260abc(0x2bd)+'\x68']?_0xcba5d1[_0x1cc9b8]:_0x5b5639['\x6b\x58\x58\x72\x43']('\x30\x30',_0xcba5d1[_0x1cc9b8])['\x73\x75\x62\x73\x74'+'\x72'](_0x5b5639[_0x260abc(0x3c1)]('',_0xcba5d1[_0x1cc9b8])[_0x260abc(0x2bd)+'\x68'])));return _0x4afa6b;}[_0x58d552(0x238)](_0x20c0d7=_0xe7e934,_0x9ed798='',_0x5d3363='',_0xfee76d){const _0x237443=_0x58d552,_0x499584=_0x430759=>{const _0x38b34f=_0x42bc;if(!_0x430759)return _0x430759;if(_0x5b5639[_0x38b34f(0x625)](_0x5b5639[_0x38b34f(0x4a7)],typeof _0x430759))return this[_0x38b34f(0x64e)+'\x6e']()?_0x430759:this[_0x38b34f(0x459)+'\x6e\x58']()?{'\x6f\x70\x65\x6e\x2d\x75\x72\x6c':_0x430759}:this[_0x38b34f(0x589)+'\x67\x65']()?{'\x75\x72\x6c':_0x430759}:void(0x2a7*0x1+-0x1*0x16f7+0x1450);if(_0x5b5639['\x54\x57\x47\x4b\x47'](_0x5b5639[_0x38b34f(0x6d3)],typeof _0x430759)){if(this[_0x38b34f(0x64e)+'\x6e']()){let _0x5ae803=_0x430759[_0x38b34f(0x333)+'\x72\x6c']||_0x430759[_0x38b34f(0x1eb)]||_0x430759[_0x38b34f(0x488)+'\x75\x72\x6c'],_0x882b24=_0x430759[_0x38b34f(0x1cf)+_0x38b34f(0x5c3)]||_0x430759[_0x5b5639[_0x38b34f(0x323)]];const _0x2759d7={};return _0x2759d7['\x6f\x70\x65\x6e\x55'+'\x72\x6c']=_0x5ae803,_0x2759d7[_0x38b34f(0x1cf)+'\x55\x72\x6c']=_0x882b24,_0x2759d7;}if(this[_0x38b34f(0x459)+'\x6e\x58']()){let _0x999a3a=_0x430759[_0x5b5639[_0x38b34f(0x4f9)]]||_0x430759[_0x38b34f(0x1eb)]||_0x430759[_0x38b34f(0x333)+'\x72\x6c'],_0xb31513=_0x430759[_0x38b34f(0x1cf)+_0x38b34f(0x4c4)]||_0x430759[_0x38b34f(0x1cf)+_0x38b34f(0x5c3)];const _0x3ff6b5={};return _0x3ff6b5[_0x38b34f(0x488)+_0x38b34f(0x1eb)]=_0x999a3a,_0x3ff6b5['\x6d\x65\x64\x69\x61'+_0x38b34f(0x4c4)]=_0xb31513,_0x3ff6b5;}if(this[_0x38b34f(0x589)+'\x67\x65']()){let _0x5942b5=_0x430759['\x75\x72\x6c']||_0x430759[_0x38b34f(0x333)+'\x72\x6c']||_0x430759[_0x5b5639[_0x38b34f(0x4f9)]];const _0x125715={};return _0x125715['\x75\x72\x6c']=_0x5942b5,_0x125715;}}};this['\x69\x73\x4d\x75\x74'+'\x65']||(this[_0x237443(0x589)+'\x67\x65']()||this['\x69\x73\x4c\x6f\x6f'+'\x6e']()?$notification[_0x237443(0x3d9)](_0x20c0d7,_0x9ed798,_0x5d3363,_0x5b5639['\x55\x51\x63\x6f\x57'](_0x499584,_0xfee76d)):this[_0x237443(0x459)+'\x6e\x58']()&&$notify(_0x20c0d7,_0x9ed798,_0x5d3363,_0x499584(_0xfee76d)));let _0x12fa77=['',_0x5b5639[_0x237443(0x430)]];_0x12fa77[_0x237443(0x3dd)](_0x20c0d7),_0x9ed798&&_0x12fa77['\x70\x75\x73\x68'](_0x9ed798),_0x5d3363&&_0x12fa77['\x70\x75\x73\x68'](_0x5d3363),console[_0x237443(0x230)](_0x12fa77[_0x237443(0x5c4)]('\x0a')),this['\x6c\x6f\x67\x73']=this[_0x237443(0x666)][_0x237443(0x6a6)+'\x74'](_0x12fa77);}['\x6c\x6f\x67'](..._0x5c4a23){const _0x47068c=_0x58d552;_0x5c4a23[_0x47068c(0x2bd)+'\x68']>-0x1*0x91c+0x22d8+-0x19bc&&(this[_0x47068c(0x666)]=[...this[_0x47068c(0x666)],..._0x5c4a23]),console[_0x47068c(0x230)](_0x5c4a23['\x6a\x6f\x69\x6e'](this[_0x47068c(0x6c4)+_0x47068c(0x229)+'\x6f\x72']));}['\x6c\x6f\x67\x45\x72'+'\x72'](_0x5da8e6,_0x5c9cde){const _0x41276d=_0x58d552,_0x4827e4=!this[_0x41276d(0x589)+'\x67\x65']()&&!this[_0x41276d(0x459)+'\x6e\x58']()&&!this['\x69\x73\x4c\x6f\x6f'+'\x6e']();_0x4827e4?this[_0x41276d(0x230)]('','\u2757\ufe0f'+this['\x6e\x61\x6d\x65']+_0x41276d(0x255),_0x5da8e6['\x73\x74\x61\x63\x6b']):this['\x6c\x6f\x67']('','\u2757\ufe0f'+this['\x6e\x61\x6d\x65']+_0x41276d(0x255),_0x5da8e6);}['\x77\x61\x69\x74'](_0xc41075){return new Promise(_0x168ee6=>setTimeout(_0x168ee6,_0xc41075));}[_0x58d552(0x1ff)](_0x38156f={}){const _0x131c36=_0x58d552,_0x52d693=new Date()[_0x131c36(0x624)+'\x6d\x65'](),_0x4765fa=_0x5b5639['\x76\x4b\x70\x6c\x57'](_0x5b5639[_0x131c36(0x209)](_0x52d693,this[_0x131c36(0x286)+_0x131c36(0x58e)]),0x4*0x128+0x6*0x2de+0x2*-0x8f6);this[_0x131c36(0x230)]('','\ud83d\udd14'+this[_0x131c36(0x42c)]+('\x2c\x20\u7ed3\u675f\x21'+_0x131c36(0x4de))+_0x4765fa+'\x20\u79d2'),this[_0x131c36(0x230)](),(this['\x69\x73\x53\x75\x72'+'\x67\x65']()||this['\x69\x73\x51\x75\x61'+'\x6e\x58']()||this[_0x131c36(0x64e)+'\x6e']())&&_0x5b5639['\x55\x51\x63\x6f\x57']($done,_0x38156f);}}(_0xe7e934,_0x36578e);}
| 0x230)](_ |
BarRounded.tsx | import React from 'react';
import cx from 'classnames';
import { AddSVGProps } from '../types';
export type BarRoundedProps = {
/** className to apply to path element. */
className?: string;
/** reference to path element. */
innerRef?: React.Ref<SVGPathElement>;
/** left position of the bar */
x: number;
/** top position of the bar */
y: number;
/** width of the bar starting from x */
width: number;
/** height of the bar starting from y */
height: number;
/** corner radius of the bar. clamped to center of the shorter side of the bar (Math.min(width,height) / 2) */
radius: number;
/** apply corner radius to top left corner, top right corner, bottom right corner, and bottom left corner */
all?: boolean;
/** apply corner radius to top left corner, and top right corner */
top?: boolean;
/** apply corner radius to bottom right corner, and bottom left corner */
bottom?: boolean;
/** apply corner radius to top left corner, and bottom left corner */
left?: boolean;
/** apply corner radius to top right corner, and bottom right corner */
right?: boolean;
/** apply corner radius to top left corner */
topLeft?: boolean;
/** apply corner radius to top right corner */
topRight?: boolean;
/** apply corner radius to bottom left corner */
bottomLeft?: boolean;
/** apply corner radius to bottom right */
bottomRight?: boolean;
/** Optional children override. */
children?: ({ path }: { path: string }) => React.ReactNode;
};
/** Hook that returns a BarRounded path. */
export function useBarRoundedPath({
all,
bottom, | radius,
right,
top,
topLeft,
topRight,
width,
x,
y,
}: Pick<
BarRoundedProps,
| 'all'
| 'top'
| 'bottom'
| 'left'
| 'right'
| 'x'
| 'y'
| 'width'
| 'height'
| 'radius'
| 'topLeft'
| 'topRight'
| 'bottomRight'
| 'bottomLeft'
>) {
topRight = all || top || right || topRight;
bottomRight = all || bottom || right || bottomRight;
bottomLeft = all || bottom || left || bottomLeft;
topLeft = all || top || left || topLeft;
// clamp radius to center of shortest side of the rect
radius = Math.max(1, Math.min(radius, Math.min(width, height) / 2));
const diameter = 2 * radius;
const path = `M${x + radius},${y} h${width - diameter}
${topRight ? `a${radius},${radius} 0 0 1 ${radius},${radius}` : `h${radius}v${radius}`}
v${height - diameter}
${bottomRight ? `a${radius},${radius} 0 0 1 ${-radius},${radius}` : `v${radius}h${-radius}`}
h${diameter - width}
${bottomLeft ? `a${radius},${radius} 0 0 1 ${-radius},${-radius}` : `h${-radius}v${-radius}`}
v${diameter - height}
${topLeft ? `a${radius},${radius} 0 0 1 ${radius},${-radius}` : `v${-radius}h${radius}`}
z`
.split('\n')
.join('');
return path;
}
export default function BarRounded({
children,
className,
innerRef,
x,
y,
width,
height,
radius,
all = false,
top = false,
bottom = false,
left = false,
right = false,
topLeft = false,
topRight = false,
bottomLeft = false,
bottomRight = false,
...restProps
}: AddSVGProps<BarRoundedProps, SVGPathElement>) {
const path = useBarRoundedPath({
x,
y,
width,
height,
radius,
all,
top,
bottom,
left,
right,
topLeft,
topRight,
bottomLeft,
bottomRight,
});
if (children) return <>{children({ path })}</>;
return (
<path ref={innerRef} className={cx('visx-bar-rounded', className)} d={path} {...restProps} />
);
} | bottomLeft,
bottomRight,
height,
left, |
model_boot_uefi_shell_device_response.go | /*
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. The Intersight OpenAPI document defines the complete set of properties that are returned in the HTTP response. From that perspective, a client can expect that no additional properties are returned, unless these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. Some generated SDKs perform a strict validation of the HTTP response body against the OpenAPI document.
API version: 1.0.9-6484
Contact: [email protected]
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package intersight
import (
"encoding/json"
"fmt"
)
// BootUefiShellDeviceResponse - The response body of a HTTP GET request for the 'boot.UefiShellDevice' resource. The value may be one of the following types. 1. When 'tag' is specified in the URL query, the response schema is a summary of the tag usage. 1. When '$apply' is specified in the URL query, the response schema is dynamically-generated schema based on the $apply value. 1. When '$count' is specified in the URL query, the response is a simple object providing the count of the resources. 1. In all other cases, the response is a list of 'boot.UefiShellDevice' resources.
type BootUefiShellDeviceResponse struct {
BootUefiShellDeviceList *BootUefiShellDeviceList
MoAggregateTransform *MoAggregateTransform
MoDocumentCount *MoDocumentCount
MoTagSummary *MoTagSummary
}
// BootUefiShellDeviceListAsBootUefiShellDeviceResponse is a convenience function that returns BootUefiShellDeviceList wrapped in BootUefiShellDeviceResponse
func | (v *BootUefiShellDeviceList) BootUefiShellDeviceResponse {
return BootUefiShellDeviceResponse{BootUefiShellDeviceList: v}
}
// MoAggregateTransformAsBootUefiShellDeviceResponse is a convenience function that returns MoAggregateTransform wrapped in BootUefiShellDeviceResponse
func MoAggregateTransformAsBootUefiShellDeviceResponse(v *MoAggregateTransform) BootUefiShellDeviceResponse {
return BootUefiShellDeviceResponse{MoAggregateTransform: v}
}
// MoDocumentCountAsBootUefiShellDeviceResponse is a convenience function that returns MoDocumentCount wrapped in BootUefiShellDeviceResponse
func MoDocumentCountAsBootUefiShellDeviceResponse(v *MoDocumentCount) BootUefiShellDeviceResponse {
return BootUefiShellDeviceResponse{MoDocumentCount: v}
}
// MoTagSummaryAsBootUefiShellDeviceResponse is a convenience function that returns MoTagSummary wrapped in BootUefiShellDeviceResponse
func MoTagSummaryAsBootUefiShellDeviceResponse(v *MoTagSummary) BootUefiShellDeviceResponse {
return BootUefiShellDeviceResponse{MoTagSummary: v}
}
// Unmarshal JSON data into one of the pointers in the struct
func (dst *BootUefiShellDeviceResponse) UnmarshalJSON(data []byte) error {
var err error
// use discriminator value to speed up the lookup
var jsonDict map[string]interface{}
err = json.Unmarshal(data, &jsonDict)
if err != nil {
return fmt.Errorf("Failed to unmarshal JSON into map for the discriminator lookup.")
}
// check if the discriminator value is 'boot.UefiShellDevice.List'
if jsonDict["ObjectType"] == "boot.UefiShellDevice.List" {
// try to unmarshal JSON data into BootUefiShellDeviceList
err = json.Unmarshal(data, &dst.BootUefiShellDeviceList)
if err == nil {
return nil // data stored in dst.BootUefiShellDeviceList, return on the first match
} else {
dst.BootUefiShellDeviceList = nil
return fmt.Errorf("Failed to unmarshal BootUefiShellDeviceResponse as BootUefiShellDeviceList: %s", err.Error())
}
}
// check if the discriminator value is 'mo.AggregateTransform'
if jsonDict["ObjectType"] == "mo.AggregateTransform" {
// try to unmarshal JSON data into MoAggregateTransform
err = json.Unmarshal(data, &dst.MoAggregateTransform)
if err == nil {
return nil // data stored in dst.MoAggregateTransform, return on the first match
} else {
dst.MoAggregateTransform = nil
return fmt.Errorf("Failed to unmarshal BootUefiShellDeviceResponse as MoAggregateTransform: %s", err.Error())
}
}
// check if the discriminator value is 'mo.DocumentCount'
if jsonDict["ObjectType"] == "mo.DocumentCount" {
// try to unmarshal JSON data into MoDocumentCount
err = json.Unmarshal(data, &dst.MoDocumentCount)
if err == nil {
return nil // data stored in dst.MoDocumentCount, return on the first match
} else {
dst.MoDocumentCount = nil
return fmt.Errorf("Failed to unmarshal BootUefiShellDeviceResponse as MoDocumentCount: %s", err.Error())
}
}
// check if the discriminator value is 'mo.TagSummary'
if jsonDict["ObjectType"] == "mo.TagSummary" {
// try to unmarshal JSON data into MoTagSummary
err = json.Unmarshal(data, &dst.MoTagSummary)
if err == nil {
return nil // data stored in dst.MoTagSummary, return on the first match
} else {
dst.MoTagSummary = nil
return fmt.Errorf("Failed to unmarshal BootUefiShellDeviceResponse as MoTagSummary: %s", err.Error())
}
}
return nil
}
// Marshal data from the first non-nil pointers in the struct to JSON
func (src BootUefiShellDeviceResponse) MarshalJSON() ([]byte, error) {
if src.BootUefiShellDeviceList != nil {
return json.Marshal(&src.BootUefiShellDeviceList)
}
if src.MoAggregateTransform != nil {
return json.Marshal(&src.MoAggregateTransform)
}
if src.MoDocumentCount != nil {
return json.Marshal(&src.MoDocumentCount)
}
if src.MoTagSummary != nil {
return json.Marshal(&src.MoTagSummary)
}
return nil, nil // no data in oneOf schemas
}
// Get the actual instance
func (obj *BootUefiShellDeviceResponse) GetActualInstance() interface{} {
if obj.BootUefiShellDeviceList != nil {
return obj.BootUefiShellDeviceList
}
if obj.MoAggregateTransform != nil {
return obj.MoAggregateTransform
}
if obj.MoDocumentCount != nil {
return obj.MoDocumentCount
}
if obj.MoTagSummary != nil {
return obj.MoTagSummary
}
// all schemas are nil
return nil
}
type NullableBootUefiShellDeviceResponse struct {
value *BootUefiShellDeviceResponse
isSet bool
}
func (v NullableBootUefiShellDeviceResponse) Get() *BootUefiShellDeviceResponse {
return v.value
}
func (v *NullableBootUefiShellDeviceResponse) Set(val *BootUefiShellDeviceResponse) {
v.value = val
v.isSet = true
}
func (v NullableBootUefiShellDeviceResponse) IsSet() bool {
return v.isSet
}
func (v *NullableBootUefiShellDeviceResponse) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableBootUefiShellDeviceResponse(val *BootUefiShellDeviceResponse) *NullableBootUefiShellDeviceResponse {
return &NullableBootUefiShellDeviceResponse{value: val, isSet: true}
}
func (v NullableBootUefiShellDeviceResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableBootUefiShellDeviceResponse) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
| BootUefiShellDeviceListAsBootUefiShellDeviceResponse |
basic_with_user_secrets.py | """
This is taken from "Simple Usage" page in the docs:
http://sanic-jwt.readthedocs.io/en/latest/pages/simpleusage.html
"""
from sanic import Sanic, response
from sanic_jwt import exceptions
from sanic_jwt import Initialize, protected
class User:
def __init__(self, id, username, password):
self.user_id = id
self.username = username
self.password = password
def __repr__(self):
return "User(id='{}')".format(self.user_id)
def to_dict(self):
return {"user_id": self.user_id, "username": self.username}
| userid_table = {u.user_id: u for u in users}
async def authenticate(request, *args, **kwargs):
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username or not password:
raise exceptions.AuthenticationFailed("Missing username or password.")
user = username_table.get(username, None)
if user is None:
raise exceptions.AuthenticationFailed("User not found.")
if password != user.password:
raise exceptions.AuthenticationFailed("Password is incorrect.")
return user
async def retrieve_user_secret(user_id):
print(f"{user_id=}")
return f"user_id|{user_id}"
app = Sanic(__name__)
Initialize(
app,
authenticate=authenticate,
user_secret_enabled=True,
retrieve_user_secret=retrieve_user_secret,
)
@app.route("/protected")
@protected()
async def protected(request):
return response.json({"protected": True})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8888, debug=True) | users = [User(1, "user1", "abcxyz"), User(2, "user2", "abcxyz")]
username_table = {u.username: u for u in users} |
f64.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module provides constants which are specific to the implementation
//! of the `f64` floating point data type.
//!
//! *[See also the `f64` primitive type](../../std/primitive.f64.html).*
//!
//! Mathematically significant numbers are provided in the `consts` sub-module.
#![stable(feature = "rust1", since = "1.0.0")]
#![allow(missing_docs)]
#[cfg(not(test))]
use intrinsics;
#[cfg(not(test))]
use sys::cmath;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::{MIN_EXP, MAX_EXP, MIN_10_EXP};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::{MAX_10_EXP, NAN, INFINITY, NEG_INFINITY};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::{MIN, MIN_POSITIVE, MAX};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::f64::consts;
#[cfg(not(test))]
#[lang = "f64_runtime"]
impl f64 {
/// Returns the largest integer less than or equal to a number.
///
/// # Examples
///
/// ```
/// let f = 3.99_f64;
/// let g = 3.0_f64;
///
/// assert_eq!(f.floor(), 3.0);
/// assert_eq!(g.floor(), 3.0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn floor(self) -> f64 {
unsafe { intrinsics::floorf64(self) }
}
/// Returns the smallest integer greater than or equal to a number.
///
/// # Examples
///
/// ```
/// let f = 3.01_f64;
/// let g = 4.0_f64;
///
/// assert_eq!(f.ceil(), 4.0);
/// assert_eq!(g.ceil(), 4.0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn ceil(self) -> f64 {
unsafe { intrinsics::ceilf64(self) }
}
/// Returns the nearest integer to a number. Round half-way cases away from
/// `0.0`.
///
/// # Examples
///
/// ```
/// let f = 3.3_f64;
/// let g = -3.3_f64;
///
/// assert_eq!(f.round(), 3.0);
/// assert_eq!(g.round(), -3.0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn round(self) -> f64 {
unsafe { intrinsics::roundf64(self) }
}
/// Returns the integer part of a number.
///
/// # Examples
///
/// ```
/// let f = 3.3_f64;
/// let g = -3.7_f64;
///
/// assert_eq!(f.trunc(), 3.0);
/// assert_eq!(g.trunc(), -3.0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn trunc(self) -> f64 {
unsafe { intrinsics::truncf64(self) }
}
/// Returns the fractional part of a number.
///
/// # Examples
///
/// ```
/// let x = 3.5_f64;
/// let y = -3.5_f64;
/// let abs_difference_x = (x.fract() - 0.5).abs();
/// let abs_difference_y = (y.fract() - (-0.5)).abs();
///
/// assert!(abs_difference_x < 1e-10);
/// assert!(abs_difference_y < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn fract(self) -> f64 { self - self.trunc() }
/// Computes the absolute value of `self`. Returns `NAN` if the
/// number is `NAN`.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = 3.5_f64;
/// let y = -3.5_f64;
///
/// let abs_difference_x = (x.abs() - x).abs();
/// let abs_difference_y = (y.abs() - (-y)).abs();
///
/// assert!(abs_difference_x < 1e-10);
/// assert!(abs_difference_y < 1e-10);
///
/// assert!(f64::NAN.abs().is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn abs(self) -> f64 {
unsafe { intrinsics::fabsf64(self) }
}
/// Returns a number that represents the sign of `self`.
///
/// - `1.0` if the number is positive, `+0.0` or `INFINITY`
/// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
/// - `NAN` if the number is `NAN`
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let f = 3.5_f64;
///
/// assert_eq!(f.signum(), 1.0);
/// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
///
/// assert!(f64::NAN.signum().is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn signum(self) -> f64 {
if self.is_nan() {
NAN
} else {
unsafe { intrinsics::copysignf64(1.0, self) }
}
}
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
/// error, yielding a more accurate result than an unfused multiply-add.
///
/// Using `mul_add` can be more performant than an unfused multiply-add if
/// the target architecture has a dedicated `fma` CPU instruction.
///
/// # Examples
///
/// ```
/// let m = 10.0_f64;
/// let x = 4.0_f64;
/// let b = 60.0_f64;
///
/// // 100.0
/// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn mul_add(self, a: f64, b: f64) -> f64 {
unsafe { intrinsics::fmaf64(self, a, b) }
}
/// Calculates Euclidean division, the matching method for `mod_euc`.
///
/// This computes the integer `n` such that
/// `self = n * rhs + self.mod_euc(rhs)`.
/// In other words, the result is `self / rhs` rounded to the integer `n`
/// such that `self >= n * rhs`.
///
/// # Examples
///
/// ```
/// #![feature(euclidean_division)]
/// let a: f64 = 7.0;
/// let b = 4.0;
/// assert_eq!(a.div_euc(b), 1.0); // 7.0 > 4.0 * 1.0
/// assert_eq!((-a).div_euc(b), -2.0); // -7.0 >= 4.0 * -2.0
/// assert_eq!(a.div_euc(-b), -1.0); // 7.0 >= -4.0 * -1.0
/// assert_eq!((-a).div_euc(-b), 2.0); // -7.0 >= -4.0 * 2.0
/// ```
#[inline]
#[unstable(feature = "euclidean_division", issue = "49048")]
pub fn div_euc(self, rhs: f64) -> f64 {
let q = (self / rhs).trunc();
if self % rhs < 0.0 {
return if rhs > 0.0 { q - 1.0 } else { q + 1.0 }
}
q
}
/// Calculates the Euclidean modulo (self mod rhs), which is never negative.
///
/// In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
///
/// # Examples
///
/// ```
/// #![feature(euclidean_division)]
/// let a: f64 = 7.0;
/// let b = 4.0;
/// assert_eq!(a.mod_euc(b), 3.0);
/// assert_eq!((-a).mod_euc(b), 1.0);
/// assert_eq!(a.mod_euc(-b), 3.0);
/// assert_eq!((-a).mod_euc(-b), 1.0);
/// ```
#[inline]
#[unstable(feature = "euclidean_division", issue = "49048")]
pub fn mod_euc(self, rhs: f64) -> f64 {
let r = self % rhs;
if r < 0.0 {
r + rhs.abs()
} else {
r
}
}
/// Raises a number to an integer power.
///
/// Using this function is generally faster than using `powf`
///
/// # Examples
///
/// ```
/// let x = 2.0_f64;
/// let abs_difference = (x.powi(2) - x*x).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn powi(self, n: i32) -> f64 {
unsafe { intrinsics::powif64(self, n) }
}
/// Raises a number to a floating point power.
///
/// # Examples
///
/// ```
/// let x = 2.0_f64;
/// let abs_difference = (x.powf(2.0) - x*x).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn powf(self, n: f64) -> f64 {
unsafe { intrinsics::powf64(self, n) }
}
/// Takes the square root of a number.
///
/// Returns NaN if `self` is a negative number.
///
/// # Examples
///
/// ```
/// let positive = 4.0_f64;
/// let negative = -4.0_f64;
///
/// let abs_difference = (positive.sqrt() - 2.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// assert!(negative.sqrt().is_nan());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sqrt(self) -> f64 {
if self < 0.0 {
NAN
} else {
unsafe { intrinsics::sqrtf64(self) }
}
}
/// Returns `e^(self)`, (the exponential function).
///
/// # Examples
///
/// ```
/// let one = 1.0_f64;
/// // e^1
/// let e = one.exp();
///
/// // ln(e) - 1 == 0
/// let abs_difference = (e.ln() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn exp(self) -> f64 {
unsafe { intrinsics::expf64(self) }
}
/// Returns `2^(self)`.
///
/// # Examples
///
/// ```
/// let f = 2.0_f64;
///
/// // 2^2 - 4 == 0
/// let abs_difference = (f.exp2() - 4.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn exp2(self) -> f64 {
unsafe { intrinsics::exp2f64(self) }
}
/// Returns the natural logarithm of the number.
///
/// # Examples
///
/// ```
/// let one = 1.0_f64;
/// // e^1
/// let e = one.exp();
///
/// // ln(e) - 1 == 0
/// let abs_difference = (e.ln() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn ln(self) -> f64 {
self.log_wrapper(|n| { unsafe { intrinsics::logf64(n) } })
}
/// Returns the logarithm of the number with respect to an arbitrary base.
///
/// The result may not be correctly rounded owing to implementation details;
/// `self.log2()` can produce more accurate results for base 2, and
/// `self.log10()` can produce more accurate results for base 10.
///
/// # Examples
///
/// ```
/// let five = 5.0_f64;
///
/// // log5(5) - 1 == 0
/// let abs_difference = (five.log(5.0) - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
/// Returns the base 2 logarithm of the number.
///
/// # Examples
///
/// ```
/// let two = 2.0_f64;
///
/// // log2(2) - 1 == 0
/// let abs_difference = (two.log2() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn log2(self) -> f64 {
self.log_wrapper(|n| {
#[cfg(target_os = "android")]
return ::sys::android::log2f64(n);
#[cfg(not(target_os = "android"))]
return unsafe { intrinsics::log2f64(n) };
})
}
/// Returns the base 10 logarithm of the number.
///
/// # Examples
///
/// ```
/// let ten = 10.0_f64;
///
/// // log10(10) - 1 == 0
/// let abs_difference = (ten.log10() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn log10(self) -> f64 {
self.log_wrapper(|n| { unsafe { intrinsics::log10f64(n) } })
}
/// The positive difference of two numbers.
///
/// * If `self <= other`: `0:0`
/// * Else: `self - other`
///
/// # Examples
///
/// ```
/// let x = 3.0_f64;
/// let y = -3.0_f64;
///
/// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
/// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();
///
/// assert!(abs_difference_x < 1e-10);
/// assert!(abs_difference_y < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
#[rustc_deprecated(since = "1.10.0",
reason = "you probably meant `(self - other).abs()`: \
this operation is `(self - other).max(0.0)` (also \
known as `fdim` in C). If you truly need the positive \
difference, consider using that expression or the C function \
`fdim`, depending on how you wish to handle NaN (please consider \
filing an issue describing your use-case too).")]
pub fn abs_sub(self, other: f64) -> f64 {
unsafe { cmath::fdim(self, other) }
}
/// Takes the cubic root of a number.
///
/// # Examples
///
/// ```
/// let x = 8.0_f64;
///
/// // x^(1/3) - 2 == 0
/// let abs_difference = (x.cbrt() - 2.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn cbrt(self) -> f64 {
unsafe { cmath::cbrt(self) }
}
/// Calculates the length of the hypotenuse of a right-angle triangle given
/// legs of length `x` and `y`.
///
/// # Examples
///
/// ```
/// let x = 2.0_f64;
/// let y = 3.0_f64;
///
/// // sqrt(x^2 + y^2)
/// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn hypot(self, other: f64) -> f64 {
unsafe { cmath::hypot(self, other) }
}
/// Computes the sine of a number (in radians).
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = f64::consts::PI/2.0;
///
/// let abs_difference = (x.sin() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sin(self) -> f64 {
unsafe { intrinsics::sinf64(self) }
}
/// Computes the cosine of a number (in radians).
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = 2.0*f64::consts::PI;
///
/// let abs_difference = (x.cos() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn cos(self) -> f64 {
unsafe { intrinsics::cosf64(self) }
}
/// Computes the tangent of a number (in radians).
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = f64::consts::PI/4.0;
/// let abs_difference = (x.tan() - 1.0).abs();
///
/// assert!(abs_difference < 1e-14);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn tan(self) -> f64 {
unsafe { cmath::tan(self) }
}
/// Computes the arcsine of a number. Return value is in radians in
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
/// [-1, 1].
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let f = f64::consts::PI / 2.0;
///
/// // asin(sin(pi/2))
/// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn asin(self) -> f64 {
unsafe { cmath::asin(self) }
}
/// Computes the arccosine of a number. Return value is in radians in
/// the range [0, pi] or NaN if the number is outside the range
/// [-1, 1].
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let f = f64::consts::PI / 4.0;
///
/// // acos(cos(pi/4))
/// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn acos(self) -> f64 {
unsafe { cmath::acos(self) }
}
/// Computes the arctangent of a number. Return value is in radians in the
/// range [-pi/2, pi/2];
///
/// # Examples
///
/// ```
/// let f = 1.0_f64;
///
/// // atan(tan(1))
/// let abs_difference = (f.tan().atan() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn atan(self) -> f64 {
unsafe { cmath::atan(self) }
}
/// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.
///
/// * `x = 0`, `y = 0`: `0`
/// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
/// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
/// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let pi = f64::consts::PI;
/// // Positive angles measured counter-clockwise
/// // from positive x axis
/// // -pi/4 radians (45 deg clockwise)
/// let x1 = 3.0_f64;
/// let y1 = -3.0_f64;
///
/// // 3pi/4 radians (135 deg counter-clockwise)
/// let x2 = -3.0_f64;
/// let y2 = 3.0_f64;
///
/// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs();
/// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs();
///
/// assert!(abs_difference_1 < 1e-10);
/// assert!(abs_difference_2 < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn atan2(self, other: f64) -> f64 {
unsafe { cmath::atan2(self, other) }
}
/// Simultaneously computes the sine and cosine of the number, `x`. Returns
/// `(sin(x), cos(x))`.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = f64::consts::PI/4.0;
/// let f = x.sin_cos();
///
/// let abs_difference_0 = (f.0 - x.sin()).abs();
/// let abs_difference_1 = (f.1 - x.cos()).abs();
///
/// assert!(abs_difference_0 < 1e-10);
/// assert!(abs_difference_1 < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sin_cos(self) -> (f64, f64) {
(self.sin(), self.cos())
}
/// Returns `e^(self) - 1` in a way that is accurate even if the
/// number is close to zero.
///
/// # Examples
///
/// ```
/// let x = 7.0_f64;
///
/// // e^(ln(7)) - 1
/// let abs_difference = (x.ln().exp_m1() - 6.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn exp_m1(self) -> f64 {
unsafe { cmath::expm1(self) }
}
/// Returns `ln(1+n)` (natural logarithm) more accurately than if
/// the operations were performed separately.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let x = f64::consts::E - 1.0;
///
/// // ln(1 + (e - 1)) == ln(e) == 1
/// let abs_difference = (x.ln_1p() - 1.0).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn ln_1p(self) -> f64 {
unsafe { cmath::log1p(self) }
}
/// Hyperbolic sine function.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let e = f64::consts::E;
/// let x = 1.0_f64;
///
/// let f = x.sinh();
/// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
/// let g = (e*e - 1.0)/(2.0*e);
/// let abs_difference = (f - g).abs();
///
/// assert!(abs_difference < 1e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sinh(self) -> f64 {
unsafe { cmath::sinh(self) }
}
/// Hyperbolic cosine function.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let e = f64::consts::E;
/// let x = 1.0_f64;
/// let f = x.cosh();
/// // Solving cosh() at 1 gives this result
/// let g = (e*e + 1.0)/(2.0*e);
/// let abs_difference = (f - g).abs();
///
/// // Same result
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn cosh(self) -> f64 {
unsafe { cmath::cosh(self) }
}
/// Hyperbolic tangent function.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let e = f64::consts::E;
/// let x = 1.0_f64;
///
/// let f = x.tanh();
/// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
/// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2));
/// let abs_difference = (f - g).abs();
///
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn tanh(self) -> f64 {
unsafe { cmath::tanh(self) }
}
/// Inverse hyperbolic sine function.
///
/// # Examples
///
/// ```
/// let x = 1.0_f64;
/// let f = x.sinh().asinh();
///
/// let abs_difference = (f - x).abs();
///
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn asinh(self) -> f64 {
if self == NEG_INFINITY {
NEG_INFINITY
} else {
(self + ((self * self) + 1.0).sqrt()).ln()
}
}
/// Inverse hyperbolic cosine function.
///
/// # Examples
///
/// ```
/// let x = 1.0_f64;
/// let f = x.cosh().acosh();
///
/// let abs_difference = (f - x).abs();
///
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn acosh(self) -> f64 {
match self {
x if x < 1.0 => NAN,
x => (x + ((x * x) - 1.0).sqrt()).ln(),
}
}
/// Inverse hyperbolic tangent function.
///
/// # Examples
///
/// ```
/// use std::f64;
///
/// let e = f64::consts::E;
/// let f = e.tanh().atanh();
///
/// let abs_difference = (f - e).abs();
///
/// assert!(abs_difference < 1.0e-10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn atanh(self) -> f64 {
0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
}
// Solaris/Illumos requires a wrapper around log, log2, and log10 functions
// because of their non-standard behavior (e.g. log(-n) returns -Inf instead
// of expected NaN).
fn log_wrapper<F: Fn(f64) -> f64>(self, log_fn: F) -> f64 {
if !cfg!(target_os = "solaris") {
log_fn(self)
} else {
if self.is_finite() {
if self > 0.0 {
log_fn(self)
} else if self == 0.0 {
NEG_INFINITY // log(0) = -Inf
} else {
NAN // log(-n) = NaN
}
} else if self.is_nan() {
self // log(NaN) = NaN
} else if self > 0.0 {
self // log(Inf) = Inf
} else {
NAN // log(-Inf) = NaN
}
}
}
}
#[cfg(test)]
mod tests {
use f64;
use f64::*;
use num::*;
use num::FpCategory as Fp;
#[test]
fn test_num_f64() {
test_num(10f64, 2f64);
}
#[test]
fn test_min_nan() {
assert_eq!(NAN.min(2.0), 2.0);
assert_eq!(2.0f64.min(NAN), 2.0);
}
#[test]
fn test_max_nan() {
assert_eq!(NAN.max(2.0), 2.0);
assert_eq!(2.0f64.max(NAN), 2.0);
}
#[test]
fn test_nan() {
let nan: f64 = NAN;
assert!(nan.is_nan());
assert!(!nan.is_infinite());
assert!(!nan.is_finite());
assert!(!nan.is_normal());
assert!(nan.is_sign_positive());
assert!(!nan.is_sign_negative());
assert_eq!(Fp::Nan, nan.classify());
}
#[test]
fn test_infinity() {
let inf: f64 = INFINITY;
assert!(inf.is_infinite());
assert!(!inf.is_finite());
assert!(inf.is_sign_positive());
assert!(!inf.is_sign_negative());
assert!(!inf.is_nan());
assert!(!inf.is_normal());
assert_eq!(Fp::Infinite, inf.classify());
}
#[test]
fn test_neg_infinity() {
let neg_inf: f64 = NEG_INFINITY;
assert!(neg_inf.is_infinite());
assert!(!neg_inf.is_finite());
assert!(!neg_inf.is_sign_positive());
assert!(neg_inf.is_sign_negative());
assert!(!neg_inf.is_nan());
assert!(!neg_inf.is_normal());
assert_eq!(Fp::Infinite, neg_inf.classify());
}
#[test]
fn test_zero() {
let zero: f64 = 0.0f64;
assert_eq!(0.0, zero);
assert!(!zero.is_infinite());
assert!(zero.is_finite());
assert!(zero.is_sign_positive());
assert!(!zero.is_sign_negative());
assert!(!zero.is_nan());
assert!(!zero.is_normal());
assert_eq!(Fp::Zero, zero.classify());
}
#[test]
fn test_neg_zero() {
let neg_zero: f64 = -0.0;
assert_eq!(0.0, neg_zero);
assert!(!neg_zero.is_infinite());
assert!(neg_zero.is_finite());
assert!(!neg_zero.is_sign_positive());
assert!(neg_zero.is_sign_negative());
assert!(!neg_zero.is_nan());
assert!(!neg_zero.is_normal());
assert_eq!(Fp::Zero, neg_zero.classify());
}
#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630
#[test]
fn test_one() {
let one: f64 = 1.0f64;
assert_eq!(1.0, one);
assert!(!one.is_infinite());
assert!(one.is_finite());
assert!(one.is_sign_positive());
assert!(!one.is_sign_negative());
assert!(!one.is_nan());
assert!(one.is_normal());
assert_eq!(Fp::Normal, one.classify());
}
#[test]
fn test_is_nan() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert!(nan.is_nan());
assert!(!0.0f64.is_nan());
assert!(!5.3f64.is_nan());
assert!(!(-10.732f64).is_nan());
assert!(!inf.is_nan());
assert!(!neg_inf.is_nan());
}
#[test]
fn test_is_infinite() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert!(!nan.is_infinite());
assert!(inf.is_infinite());
assert!(neg_inf.is_infinite());
assert!(!0.0f64.is_infinite());
assert!(!42.8f64.is_infinite());
assert!(!(-109.2f64).is_infinite());
}
#[test]
fn test_is_finite() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert!(!nan.is_finite());
assert!(!inf.is_finite());
assert!(!neg_inf.is_finite());
assert!(0.0f64.is_finite());
assert!(42.8f64.is_finite());
assert!((-109.2f64).is_finite());
}
#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630
#[test]
fn test_is_normal() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let zero: f64 = 0.0f64;
let neg_zero: f64 = -0.0;
assert!(!nan.is_normal());
assert!(!inf.is_normal());
assert!(!neg_inf.is_normal());
assert!(!zero.is_normal());
assert!(!neg_zero.is_normal());
assert!(1f64.is_normal());
assert!(1e-307f64.is_normal());
assert!(!1e-308f64.is_normal());
}
#[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630
#[test]
fn test_classify() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let zero: f64 = 0.0f64;
let neg_zero: f64 = -0.0;
assert_eq!(nan.classify(), Fp::Nan);
assert_eq!(inf.classify(), Fp::Infinite);
assert_eq!(neg_inf.classify(), Fp::Infinite);
assert_eq!(zero.classify(), Fp::Zero);
assert_eq!(neg_zero.classify(), Fp::Zero);
assert_eq!(1e-307f64.classify(), Fp::Normal);
assert_eq!(1e-308f64.classify(), Fp::Subnormal);
}
#[test]
fn test_floor() {
assert_approx_eq!(1.0f64.floor(), 1.0f64);
assert_approx_eq!(1.3f64.floor(), 1.0f64);
assert_approx_eq!(1.5f64.floor(), 1.0f64);
assert_approx_eq!(1.7f64.floor(), 1.0f64);
assert_approx_eq!(0.0f64.floor(), 0.0f64);
assert_approx_eq!((-0.0f64).floor(), -0.0f64);
assert_approx_eq!((-1.0f64).floor(), -1.0f64);
assert_approx_eq!((-1.3f64).floor(), -2.0f64);
assert_approx_eq!((-1.5f64).floor(), -2.0f64);
assert_approx_eq!((-1.7f64).floor(), -2.0f64);
}
#[test]
fn | () {
assert_approx_eq!(1.0f64.ceil(), 1.0f64);
assert_approx_eq!(1.3f64.ceil(), 2.0f64);
assert_approx_eq!(1.5f64.ceil(), 2.0f64);
assert_approx_eq!(1.7f64.ceil(), 2.0f64);
assert_approx_eq!(0.0f64.ceil(), 0.0f64);
assert_approx_eq!((-0.0f64).ceil(), -0.0f64);
assert_approx_eq!((-1.0f64).ceil(), -1.0f64);
assert_approx_eq!((-1.3f64).ceil(), -1.0f64);
assert_approx_eq!((-1.5f64).ceil(), -1.0f64);
assert_approx_eq!((-1.7f64).ceil(), -1.0f64);
}
#[test]
fn test_round() {
assert_approx_eq!(1.0f64.round(), 1.0f64);
assert_approx_eq!(1.3f64.round(), 1.0f64);
assert_approx_eq!(1.5f64.round(), 2.0f64);
assert_approx_eq!(1.7f64.round(), 2.0f64);
assert_approx_eq!(0.0f64.round(), 0.0f64);
assert_approx_eq!((-0.0f64).round(), -0.0f64);
assert_approx_eq!((-1.0f64).round(), -1.0f64);
assert_approx_eq!((-1.3f64).round(), -1.0f64);
assert_approx_eq!((-1.5f64).round(), -2.0f64);
assert_approx_eq!((-1.7f64).round(), -2.0f64);
}
#[test]
fn test_trunc() {
assert_approx_eq!(1.0f64.trunc(), 1.0f64);
assert_approx_eq!(1.3f64.trunc(), 1.0f64);
assert_approx_eq!(1.5f64.trunc(), 1.0f64);
assert_approx_eq!(1.7f64.trunc(), 1.0f64);
assert_approx_eq!(0.0f64.trunc(), 0.0f64);
assert_approx_eq!((-0.0f64).trunc(), -0.0f64);
assert_approx_eq!((-1.0f64).trunc(), -1.0f64);
assert_approx_eq!((-1.3f64).trunc(), -1.0f64);
assert_approx_eq!((-1.5f64).trunc(), -1.0f64);
assert_approx_eq!((-1.7f64).trunc(), -1.0f64);
}
#[test]
fn test_fract() {
assert_approx_eq!(1.0f64.fract(), 0.0f64);
assert_approx_eq!(1.3f64.fract(), 0.3f64);
assert_approx_eq!(1.5f64.fract(), 0.5f64);
assert_approx_eq!(1.7f64.fract(), 0.7f64);
assert_approx_eq!(0.0f64.fract(), 0.0f64);
assert_approx_eq!((-0.0f64).fract(), -0.0f64);
assert_approx_eq!((-1.0f64).fract(), -0.0f64);
assert_approx_eq!((-1.3f64).fract(), -0.3f64);
assert_approx_eq!((-1.5f64).fract(), -0.5f64);
assert_approx_eq!((-1.7f64).fract(), -0.7f64);
}
#[test]
fn test_abs() {
assert_eq!(INFINITY.abs(), INFINITY);
assert_eq!(1f64.abs(), 1f64);
assert_eq!(0f64.abs(), 0f64);
assert_eq!((-0f64).abs(), 0f64);
assert_eq!((-1f64).abs(), 1f64);
assert_eq!(NEG_INFINITY.abs(), INFINITY);
assert_eq!((1f64/NEG_INFINITY).abs(), 0f64);
assert!(NAN.abs().is_nan());
}
#[test]
fn test_signum() {
assert_eq!(INFINITY.signum(), 1f64);
assert_eq!(1f64.signum(), 1f64);
assert_eq!(0f64.signum(), 1f64);
assert_eq!((-0f64).signum(), -1f64);
assert_eq!((-1f64).signum(), -1f64);
assert_eq!(NEG_INFINITY.signum(), -1f64);
assert_eq!((1f64/NEG_INFINITY).signum(), -1f64);
assert!(NAN.signum().is_nan());
}
#[test]
fn test_is_sign_positive() {
assert!(INFINITY.is_sign_positive());
assert!(1f64.is_sign_positive());
assert!(0f64.is_sign_positive());
assert!(!(-0f64).is_sign_positive());
assert!(!(-1f64).is_sign_positive());
assert!(!NEG_INFINITY.is_sign_positive());
assert!(!(1f64/NEG_INFINITY).is_sign_positive());
assert!(NAN.is_sign_positive());
assert!(!(-NAN).is_sign_positive());
}
#[test]
fn test_is_sign_negative() {
assert!(!INFINITY.is_sign_negative());
assert!(!1f64.is_sign_negative());
assert!(!0f64.is_sign_negative());
assert!((-0f64).is_sign_negative());
assert!((-1f64).is_sign_negative());
assert!(NEG_INFINITY.is_sign_negative());
assert!((1f64/NEG_INFINITY).is_sign_negative());
assert!(!NAN.is_sign_negative());
assert!((-NAN).is_sign_negative());
}
#[test]
fn test_mul_add() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_approx_eq!(12.3f64.mul_add(4.5, 6.7), 62.05);
assert_approx_eq!((-12.3f64).mul_add(-4.5, -6.7), 48.65);
assert_approx_eq!(0.0f64.mul_add(8.9, 1.2), 1.2);
assert_approx_eq!(3.4f64.mul_add(-0.0, 5.6), 5.6);
assert!(nan.mul_add(7.8, 9.0).is_nan());
assert_eq!(inf.mul_add(7.8, 9.0), inf);
assert_eq!(neg_inf.mul_add(7.8, 9.0), neg_inf);
assert_eq!(8.9f64.mul_add(inf, 3.2), inf);
assert_eq!((-3.2f64).mul_add(2.4, neg_inf), neg_inf);
}
#[test]
fn test_recip() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(1.0f64.recip(), 1.0);
assert_eq!(2.0f64.recip(), 0.5);
assert_eq!((-0.4f64).recip(), -2.5);
assert_eq!(0.0f64.recip(), inf);
assert!(nan.recip().is_nan());
assert_eq!(inf.recip(), 0.0);
assert_eq!(neg_inf.recip(), 0.0);
}
#[test]
fn test_powi() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(1.0f64.powi(1), 1.0);
assert_approx_eq!((-3.1f64).powi(2), 9.61);
assert_approx_eq!(5.9f64.powi(-2), 0.028727);
assert_eq!(8.3f64.powi(0), 1.0);
assert!(nan.powi(2).is_nan());
assert_eq!(inf.powi(3), inf);
assert_eq!(neg_inf.powi(2), inf);
}
#[test]
fn test_powf() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(1.0f64.powf(1.0), 1.0);
assert_approx_eq!(3.4f64.powf(4.5), 246.408183);
assert_approx_eq!(2.7f64.powf(-3.2), 0.041652);
assert_approx_eq!((-3.1f64).powf(2.0), 9.61);
assert_approx_eq!(5.9f64.powf(-2.0), 0.028727);
assert_eq!(8.3f64.powf(0.0), 1.0);
assert!(nan.powf(2.0).is_nan());
assert_eq!(inf.powf(2.0), inf);
assert_eq!(neg_inf.powf(3.0), neg_inf);
}
#[test]
fn test_sqrt_domain() {
assert!(NAN.sqrt().is_nan());
assert!(NEG_INFINITY.sqrt().is_nan());
assert!((-1.0f64).sqrt().is_nan());
assert_eq!((-0.0f64).sqrt(), -0.0);
assert_eq!(0.0f64.sqrt(), 0.0);
assert_eq!(1.0f64.sqrt(), 1.0);
assert_eq!(INFINITY.sqrt(), INFINITY);
}
#[test]
fn test_exp() {
assert_eq!(1.0, 0.0f64.exp());
assert_approx_eq!(2.718282, 1.0f64.exp());
assert_approx_eq!(148.413159, 5.0f64.exp());
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(inf, inf.exp());
assert_eq!(0.0, neg_inf.exp());
assert!(nan.exp().is_nan());
}
#[test]
fn test_exp2() {
assert_eq!(32.0, 5.0f64.exp2());
assert_eq!(1.0, 0.0f64.exp2());
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(inf, inf.exp2());
assert_eq!(0.0, neg_inf.exp2());
assert!(nan.exp2().is_nan());
}
#[test]
fn test_ln() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_approx_eq!(1.0f64.exp().ln(), 1.0);
assert!(nan.ln().is_nan());
assert_eq!(inf.ln(), inf);
assert!(neg_inf.ln().is_nan());
assert!((-2.3f64).ln().is_nan());
assert_eq!((-0.0f64).ln(), neg_inf);
assert_eq!(0.0f64.ln(), neg_inf);
assert_approx_eq!(4.0f64.ln(), 1.386294);
}
#[test]
fn test_log() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(10.0f64.log(10.0), 1.0);
assert_approx_eq!(2.3f64.log(3.5), 0.664858);
assert_eq!(1.0f64.exp().log(1.0f64.exp()), 1.0);
assert!(1.0f64.log(1.0).is_nan());
assert!(1.0f64.log(-13.9).is_nan());
assert!(nan.log(2.3).is_nan());
assert_eq!(inf.log(10.0), inf);
assert!(neg_inf.log(8.8).is_nan());
assert!((-2.3f64).log(0.1).is_nan());
assert_eq!((-0.0f64).log(2.0), neg_inf);
assert_eq!(0.0f64.log(7.0), neg_inf);
}
#[test]
fn test_log2() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_approx_eq!(10.0f64.log2(), 3.321928);
assert_approx_eq!(2.3f64.log2(), 1.201634);
assert_approx_eq!(1.0f64.exp().log2(), 1.442695);
assert!(nan.log2().is_nan());
assert_eq!(inf.log2(), inf);
assert!(neg_inf.log2().is_nan());
assert!((-2.3f64).log2().is_nan());
assert_eq!((-0.0f64).log2(), neg_inf);
assert_eq!(0.0f64.log2(), neg_inf);
}
#[test]
fn test_log10() {
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(10.0f64.log10(), 1.0);
assert_approx_eq!(2.3f64.log10(), 0.361728);
assert_approx_eq!(1.0f64.exp().log10(), 0.434294);
assert_eq!(1.0f64.log10(), 0.0);
assert!(nan.log10().is_nan());
assert_eq!(inf.log10(), inf);
assert!(neg_inf.log10().is_nan());
assert!((-2.3f64).log10().is_nan());
assert_eq!((-0.0f64).log10(), neg_inf);
assert_eq!(0.0f64.log10(), neg_inf);
}
#[test]
fn test_to_degrees() {
let pi: f64 = consts::PI;
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(0.0f64.to_degrees(), 0.0);
assert_approx_eq!((-5.8f64).to_degrees(), -332.315521);
assert_eq!(pi.to_degrees(), 180.0);
assert!(nan.to_degrees().is_nan());
assert_eq!(inf.to_degrees(), inf);
assert_eq!(neg_inf.to_degrees(), neg_inf);
}
#[test]
fn test_to_radians() {
let pi: f64 = consts::PI;
let nan: f64 = NAN;
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
assert_eq!(0.0f64.to_radians(), 0.0);
assert_approx_eq!(154.6f64.to_radians(), 2.698279);
assert_approx_eq!((-332.31f64).to_radians(), -5.799903);
assert_eq!(180.0f64.to_radians(), pi);
assert!(nan.to_radians().is_nan());
assert_eq!(inf.to_radians(), inf);
assert_eq!(neg_inf.to_radians(), neg_inf);
}
#[test]
fn test_asinh() {
assert_eq!(0.0f64.asinh(), 0.0f64);
assert_eq!((-0.0f64).asinh(), -0.0f64);
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(inf.asinh(), inf);
assert_eq!(neg_inf.asinh(), neg_inf);
assert!(nan.asinh().is_nan());
assert_approx_eq!(2.0f64.asinh(), 1.443635475178810342493276740273105f64);
assert_approx_eq!((-2.0f64).asinh(), -1.443635475178810342493276740273105f64);
}
#[test]
fn test_acosh() {
assert_eq!(1.0f64.acosh(), 0.0f64);
assert!(0.999f64.acosh().is_nan());
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(inf.acosh(), inf);
assert!(neg_inf.acosh().is_nan());
assert!(nan.acosh().is_nan());
assert_approx_eq!(2.0f64.acosh(), 1.31695789692481670862504634730796844f64);
assert_approx_eq!(3.0f64.acosh(), 1.76274717403908605046521864995958461f64);
}
#[test]
fn test_atanh() {
assert_eq!(0.0f64.atanh(), 0.0f64);
assert_eq!((-0.0f64).atanh(), -0.0f64);
let inf: f64 = INFINITY;
let neg_inf: f64 = NEG_INFINITY;
let nan: f64 = NAN;
assert_eq!(1.0f64.atanh(), inf);
assert_eq!((-1.0f64).atanh(), neg_inf);
assert!(2f64.atanh().atanh().is_nan());
assert!((-2f64).atanh().atanh().is_nan());
assert!(inf.atanh().is_nan());
assert!(neg_inf.atanh().is_nan());
assert!(nan.atanh().is_nan());
assert_approx_eq!(0.5f64.atanh(), 0.54930614433405484569762261846126285f64);
assert_approx_eq!((-0.5f64).atanh(), -0.54930614433405484569762261846126285f64);
}
#[test]
fn test_real_consts() {
use super::consts;
let pi: f64 = consts::PI;
let frac_pi_2: f64 = consts::FRAC_PI_2;
let frac_pi_3: f64 = consts::FRAC_PI_3;
let frac_pi_4: f64 = consts::FRAC_PI_4;
let frac_pi_6: f64 = consts::FRAC_PI_6;
let frac_pi_8: f64 = consts::FRAC_PI_8;
let frac_1_pi: f64 = consts::FRAC_1_PI;
let frac_2_pi: f64 = consts::FRAC_2_PI;
let frac_2_sqrtpi: f64 = consts::FRAC_2_SQRT_PI;
let sqrt2: f64 = consts::SQRT_2;
let frac_1_sqrt2: f64 = consts::FRAC_1_SQRT_2;
let e: f64 = consts::E;
let log2_e: f64 = consts::LOG2_E;
let log10_e: f64 = consts::LOG10_E;
let ln_2: f64 = consts::LN_2;
let ln_10: f64 = consts::LN_10;
assert_approx_eq!(frac_pi_2, pi / 2f64);
assert_approx_eq!(frac_pi_3, pi / 3f64);
assert_approx_eq!(frac_pi_4, pi / 4f64);
assert_approx_eq!(frac_pi_6, pi / 6f64);
assert_approx_eq!(frac_pi_8, pi / 8f64);
assert_approx_eq!(frac_1_pi, 1f64 / pi);
assert_approx_eq!(frac_2_pi, 2f64 / pi);
assert_approx_eq!(frac_2_sqrtpi, 2f64 / pi.sqrt());
assert_approx_eq!(sqrt2, 2f64.sqrt());
assert_approx_eq!(frac_1_sqrt2, 1f64 / 2f64.sqrt());
assert_approx_eq!(log2_e, e.log2());
assert_approx_eq!(log10_e, e.log10());
assert_approx_eq!(ln_2, 2f64.ln());
assert_approx_eq!(ln_10, 10f64.ln());
}
#[test]
fn test_float_bits_conv() {
assert_eq!((1f64).to_bits(), 0x3ff0000000000000);
assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
assert_eq!((1337f64).to_bits(), 0x4094e40000000000);
assert_eq!((-14.25f64).to_bits(), 0xc02c800000000000);
assert_approx_eq!(f64::from_bits(0x3ff0000000000000), 1.0);
assert_approx_eq!(f64::from_bits(0x4029000000000000), 12.5);
assert_approx_eq!(f64::from_bits(0x4094e40000000000), 1337.0);
assert_approx_eq!(f64::from_bits(0xc02c800000000000), -14.25);
// Check that NaNs roundtrip their bits regardless of signalingness
// 0xA is 0b1010; 0x5 is 0b0101 -- so these two together clobbers all the mantissa bits
let masked_nan1 = f64::NAN.to_bits() ^ 0x000A_AAAA_AAAA_AAAA;
let masked_nan2 = f64::NAN.to_bits() ^ 0x0005_5555_5555_5555;
assert!(f64::from_bits(masked_nan1).is_nan());
assert!(f64::from_bits(masked_nan2).is_nan());
assert_eq!(f64::from_bits(masked_nan1).to_bits(), masked_nan1);
assert_eq!(f64::from_bits(masked_nan2).to_bits(), masked_nan2);
}
}
| test_ceil |
SlotData.ts | /******************************************************************************
* Spine Runtimes Software License
* Version 2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
namespace pixi_spine.core {
export class | {
index: number;
name: string;
boneData: BoneData;
color = new Color(1, 1, 1, 1);
darkColor: Color;
attachmentName: string;
blendMode: BlendMode;
constructor (index: number, name: string, boneData: BoneData) {
if (index < 0) throw new Error("index must be >= 0.");
if (name == null) throw new Error("name cannot be null.");
if (boneData == null) throw new Error("boneData cannot be null.");
this.index = index;
this.name = name;
this.boneData = boneData;
}
}
}
| SlotData |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.