file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
main.rs | use std::collections::HashSet;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::iter::FromIterator;
use std::time::Instant;
fn is_reacting(a: char, b: char) -> bool |
fn process_reaction(chars: &[char]) -> Vec<char> {
chars.iter().fold(Vec::new(), |mut new_chars, c| {
if is_reacting(*c, *new_chars.last().unwrap_or(&'!')) {
new_chars.pop();
} else {
new_chars.push(*c);
}
new_chars
})
}
fn collapsed_reaction(chars: &[char]) -> Vec<char> {
let units: HashSet<char> = HashSet::from_iter(chars.iter().map(|c| c.to_ascii_lowercase()));
units
.iter()
.map(|u| {
let collapsed: Vec<char> = Vec::from_iter(
chars
.iter()
.cloned()
.filter(|x| !u.eq_ignore_ascii_case(&x)),
);
process_reaction(collapsed.as_slice())
}).min_by_key(|r| r.len())
.expect("or not")
}
fn main() {
const FNAME: &str = "input.txt";
let file = File::open(FNAME).expect(&format!("Couldn't open {}", FNAME));
let reader = BufReader::new(&file);
let line: String = reader.lines().filter_map(|l| l.ok()).next().unwrap();
let chars: Vec<char> = Vec::from_iter(line.chars());
let t1 = Instant::now();
let reacted = process_reaction(chars.as_slice());
let t2 = Instant::now();
println!("{}", reacted.len());
println!("{:?}", t2 - t1);
let t3 = Instant::now();
let collapsed = collapsed_reaction(reacted.as_slice());
let t4 = Instant::now();
println!("{}", collapsed.len());
println!("{:?}", t4 - t3);
}
| {
// apparently aa doens't react
a.eq_ignore_ascii_case(&b) && a != b
} |
http.go | package vault
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"github.com/golang/glog"
"github.com/open-horizon/anax/agreementbot/secrets"
"github.com/open-horizon/anax/config"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"time"
)
// Retry intervals when connecting to the vault
const EX_MAX_RETRY = 10
const EX_RETRY_INTERVAL = 2
type ErrorResponse struct {
Errors []string `json:"errors"`
}
type LoginBody struct {
Id string `json:"id"`
Token string `json:"token"`
}
type LoginAuthResponse struct {
ClientToken string `json:"client_token"`
Accessor string `json:"accessor"`
Policies []string `json:"policies"`
TokenPolicies []string `json:"token_policies"`
Metadata map[string]string `json:"metadata"`
LeaseDuration int `json:"lease_duration"`
Renewable bool `json:"renewable"`
EntityId string `json:"entity_id"`
TokenType string `json:"token_type"`
Orphan bool `json:"orphan"`
}
type LoginResponse struct {
ReqId string `json:"request_id"`
LeaseId string `json:"lease_id"`
Renewable bool `json:"renewable"`
Auth LoginAuthResponse `json:"auth"`
}
type RenewBody struct {
Token string `json:"token"`
}
type SecretCreateRequest struct {
Options map[string]string `json:"options,omitempty"`
Data secrets.SecretDetails `json:"data"`
}
type ListSecretResponse struct {
Data SecretMetadata `json:"data"`
}
type KeyData struct {
Keys []string `json:"keys"`
}
type ListSecretsResponse struct {
Data KeyData `json:"data"`
}
type SecretData struct {
Data secrets.SecretDetails `json:"data"`
}
type GetSecretResponse struct {
Data SecretData `json:"data"`
}
type SecretMetadata struct {
CreationTime string `json:"created_time"` // Has format 2018-03-22T02:24:06.945319214Z
UpdateTime string `json:"updated_time"`
}
// Create an https connection, using a supplied SSL CA certificate.
func (vs *AgbotVaultSecrets) newHTTPClient(cfg *config.HorizonConfig) (*http.Client, error) {
// Consume the openhorizon hub certificate
var err error
var caBytes []byte
var tlsConf tls.Config
if _, err = os.Stat(cfg.GetVaultCertPath()); err == nil {
caBytes, err = ioutil.ReadFile(cfg.GetVaultCertPath())
if err != nil {
return nil, errors.New(fmt.Sprintf("unable to read %v, error %v", cfg.GetVaultCertPath(), err))
}
// Setup the TLS config if there is a cert.
tlsConf.InsecureSkipVerify = false
// Do not allow negotiation to previous versions of TLS.
tlsConf.MinVersion = tls.VersionTLS12
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(caBytes)
tlsConf.RootCAs = certPool
tlsConf.BuildNameToCertificate()
}
return &http.Client{
// remember that this timouet is for the whole request, including
// body reading. This means that you must set the timeout according
// to the total payload size you expect
Timeout: time.Second * time.Duration(20),
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 60 * time.Second,
KeepAlive: 120 * time.Second,
}).Dial,
ResponseHeaderTimeout: 20 * time.Second,
ExpectContinueTimeout: 8 * time.Second,
MaxIdleConns: 20,
IdleConnTimeout: 120 * time.Second,
TLSClientConfig: &tlsConf,
},
}, nil
}
// Common function to invoke the Vault API with builtin retry logic.
func (vs *AgbotVaultSecrets) invokeVaultWithRetry(token string, url string, method string, body interface{}) (*http.Response, error) {
var currRetry int
var resp *http.Response
var err error
for currRetry = EX_MAX_RETRY; currRetry > 0; {
resp, err = vs.invokeVault(token, url, method, body)
// Log the HTTP response code.
if resp == nil {
glog.Warningf(vaultPluginLogString("received nil response from vault"))
}
if resp != nil {
glog.V(3).Infof(vaultPluginLogString(fmt.Sprintf("received HTTP code: %d", resp.StatusCode)))
}
if err == nil {
break
}
// If the invocation resulted in a retryable network error, log it and retry the exchange invocation.
if isTransportError(resp, err) {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
// Log the transport error and retry
glog.Warningf(vaultPluginLogString("received transport error, retry..."))
currRetry--
time.Sleep(time.Duration(EX_RETRY_INTERVAL) * time.Second)
} else if token == "" && resp != nil && resp.StatusCode == http.StatusForbidden {
// The agbot failed to authenticate, something must have happened to the agbot's token, so login again to get a new token.
glog.Warningf(vaultPluginLogString("unexpected agbot token expiration, logging in again"))
err := vs.Login()
if err != nil {
glog.Warningf(vaultPluginLogString(fmt.Sprintf("error logging in trying to recover expired token: %v", err)))
}
// Decrement the retry count so that we dont accidentally loop forever.
currRetry--
// No need to delay the retry because this error was not a transport problem.
} else {
return resp, err
}
}
if currRetry == 0 {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
return resp, errors.New(fmt.Sprintf("unable to invoke %v %v in the vault, exceeded %v retries", url, method, EX_MAX_RETRY))
}
return resp, err
}
// Common function to invoke the Vault API.
func (vs *AgbotVaultSecrets) invokeVault(token string, url string, method string, body interface{}) (*http.Response, error) {
apiMsg := fmt.Sprintf("%v %v", method, url)
var requestBody io.Reader
if body != nil {
jsonBytes, err := json.Marshal(body)
if err != nil {
return nil, errors.New(fmt.Sprintf("failed to marshal body %s for %s, error: %v", body, apiMsg, err))
}
requestBody = bytes.NewBuffer(jsonBytes)
}
// Create an outgoing HTTP request for the vault.
req, err := http.NewRequest(method, url, requestBody)
if err != nil {
return nil, errors.New(fmt.Sprintf("unable to create HTTP request for %v, error %v", apiMsg, err))
}
if token != "" {
req.Header.Add("X-Vault-Token", token)
}
req.Close = true
// Send the request to the vault.
resp, err := vs.httpClient.Do(req)
if err != nil {
return nil, errors.New(fmt.Sprintf("unable to send HTTP request for %v, error %v", apiMsg, err))
} else {
// NOTE: 500, 502, 503 are the only server error status codes returned by the vault API
// https://www.vaultproject.io/api#http-status-codes
if resp.StatusCode < 500 {
vs.lastVaultInteraction = uint64(time.Now().Unix())
}
return resp, nil
}
}
// Return true if an exchange invocation resulted in an error that is retryable. In general, errors which
// result from network level problems can be retried due the transient nature of these errors, especially
// if the exchange is under heavy load.
func | (pResp *http.Response, err error) bool {
if err != nil {
if strings.Contains(err.Error(), ": EOF") {
return true
}
l_error_string := strings.ToLower(err.Error())
if strings.Contains(l_error_string, "time") && strings.Contains(l_error_string, "out") {
return true
} else if strings.Contains(l_error_string, "connection") && (strings.Contains(l_error_string, "refused") || strings.Contains(l_error_string, "reset")) {
return true
}
}
if pResp != nil {
if pResp.StatusCode == http.StatusBadGateway {
// 502: bad gateway error
return true
} else if pResp.StatusCode == http.StatusGatewayTimeout {
// 504: gateway timeout
return true
} else if pResp.StatusCode == http.StatusServiceUnavailable {
//503: service unavailable
return true
}
}
return false
}
| isTransportError |
eval_object_test.ts | /**
* Copyright 2018 The Lovefield Project 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 * as chai from 'chai';
import {ErrorCode, Type} from '../../lib/base/enum';
import {EvalRegistry, EvalType} from '../../lib/base/eval';
import {TestUtil} from '../../testing/test_util';
const assert = chai.assert;
describe('EvalObject', () => {
let registry: EvalRegistry;
| before(() => {
registry = new EvalRegistry();
});
it('eq', () => {
const evaluationFn = registry.getEvaluator(Type.OBJECT, EvalType.EQ);
const obj1 = null as unknown as object;
const obj2 = {};
assert.isTrue(evaluationFn(obj1, null));
assert.isFalse(evaluationFn(obj2, null));
// 550: where() clause includes an invalid predicate.
TestUtil.assertThrowsError(ErrorCode.INVALID_PREDICATE, () =>
evaluationFn({}, {})
);
});
it('neq', () => {
const evaluationFn = registry.getEvaluator(Type.OBJECT, EvalType.NEQ);
const obj1 = null as unknown as object;
const obj2 = {};
assert.isFalse(evaluationFn(obj1, null));
assert.isTrue(evaluationFn(obj2, null));
// 550: where() clause includes an invalid predicate.
TestUtil.assertThrowsError(ErrorCode.INVALID_PREDICATE, () =>
evaluationFn({}, {})
);
});
}); | |
users_table.rs | // Copyright 2021 Datafuse Labs.
//
// 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.
use common_base::base::tokio;
use common_exception::Result;
use common_meta_types::AuthInfo;
use common_meta_types::AuthType;
use common_meta_types::UserGrantSet;
use common_meta_types::UserInfo;
use common_meta_types::UserOption;
use common_meta_types::UserQuota;
use databend_query::storages::system::UsersTable;
use databend_query::storages::ToReadDataSourcePlan;
use futures::TryStreamExt;
use pretty_assertions::assert_eq;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_users_table() -> Result<()> | {
let ctx = crate::tests::create_query_context().await?;
let tenant = ctx.get_tenant();
ctx.get_settings().set_max_threads(2)?;
let auth_data = AuthInfo::None;
ctx.get_user_manager()
.add_user(
&tenant,
UserInfo {
auth_info: auth_data,
name: "test".to_string(),
hostname: "localhost".to_string(),
grants: UserGrantSet::empty(),
quota: UserQuota::no_limit(),
option: UserOption::default(),
},
false,
)
.await?;
let auth_data = AuthInfo::new(AuthType::Sha256Password, &Some("123456789".to_string()));
assert!(auth_data.is_ok());
ctx.get_user_manager()
.add_user(
&tenant,
UserInfo {
auth_info: auth_data.unwrap(),
name: "test1".to_string(),
hostname: "%".to_string(),
grants: UserGrantSet::empty(),
quota: UserQuota::no_limit(),
option: UserOption::default(),
},
false,
)
.await?;
let table = UsersTable::create(1);
let source_plan = table.read_plan(ctx.clone(), None).await?;
let stream = table.read(ctx, &source_plan).await?;
let result = stream.try_collect::<Vec<_>>().await?;
let block = &result[0];
assert_eq!(block.num_columns(), 4);
let expected = vec![
"+-------+-----------+-----------------+------------------------------------------------------------------+",
"| name | hostname | auth_type | auth_string |",
"+-------+-----------+-----------------+------------------------------------------------------------------+",
"| test | localhost | no_password | |",
"| test1 | % | sha256_password | 15e2b0d3c33891ebb0f1ef609ec419420c20e320ce94c65fbc8c3312448eb225 |",
"+-------+-----------+-----------------+------------------------------------------------------------------+",
];
common_datablocks::assert_blocks_sorted_eq(expected, result.as_slice());
Ok(())
} |
|
main.rs | #![deny(
unused_qualifications,
clippy::all,
unused_qualifications,
unused_import_braces,
// unused_lifetimes, // TODO: Enable. Seems buggy?
unreachable_pub,
trivial_numeric_casts,
rustdoc,
missing_debug_implementations,
missing_copy_implementations,
deprecated_in_future,
meta_variable_misuse,
non_ascii_idents,
rust_2018_compatibility,
rust_2018_idioms,
future_incompatible,
nonstandard_style
)]
#![allow(missing_doc_code_examples)] // TODO: Document everything properly
pub mod checks;
pub mod client_data;
pub mod commands;
pub mod config;
pub mod database;
pub mod logger;
pub mod util;
use crate::{
client_data::ClientData,
commands::*,
config::{
ActivityKind,
Config,
Severity,
},
database::Database,
};
use log::{
error,
info,
warn,
};
use serenity::{
client::bridge::gateway::ShardManager,
framework::standard::{
help_commands,
macros::{
group,
help,
},
Args,
CommandGroup,
CommandResult,
DispatchError,
HelpOptions,
Reason,
StandardFramework,
},
futures::future::BoxFuture,
model::prelude::*,
prelude::*,
FutureExt,
};
use std::{
collections::HashSet,
sync::Arc,
};
use tokio::runtime::Builder as RuntimeBuilder;
struct | ;
#[serenity::async_trait]
impl EventHandler for Handler {
async fn ready(&self, ctx: Context, ready: Ready) {
let data_lock = ctx.data.read().await;
let client_data = data_lock
.get::<ClientDataKey>()
.expect("missing client data");
let config = client_data.config.clone();
drop(data_lock);
if let (Some(status), Some(kind)) = (config.status_name(), config.status_type()) {
match kind {
ActivityKind::Listening => {
ctx.set_activity(Activity::listening(status)).await;
}
ActivityKind::Streaming => {
ctx.set_activity(Activity::streaming(status, config.status_url().unwrap()))
.await;
}
ActivityKind::Playing => {
ctx.set_activity(Activity::playing(status)).await;
}
}
}
info!("Logged in as '{}'", ready.user.name);
}
async fn resume(&self, _ctx: Context, _resumed: ResumedEvent) {
warn!("Resumed connection");
}
async fn message(&self, ctx: Context, msg: Message) {
let data_lock = ctx.data.read().await;
let client_data = data_lock
.get::<ClientDataKey>()
.expect("missing client data");
let reddit_embed_data = client_data.reddit_embed_data.clone();
drop(data_lock);
if let Err(e) = reddit_embed_data.process_msg(&ctx, &msg).await {
error!("Failed to generate reddit embed: {}", e);
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ClientDataKey;
impl TypeMapKey for ClientDataKey {
type Value = ClientData;
}
#[help]
async fn help(
ctx: &Context,
msg: &Message,
args: Args,
help_options: &'static HelpOptions,
groups: &[&'static CommandGroup],
owners: HashSet<UserId>,
) -> CommandResult {
let _ = help_commands::with_embeds(ctx, msg, args, help_options, groups, owners)
.await
.is_some();
Ok(())
}
#[group]
#[commands(
ping,
nekos,
r6stats,
r6tracker,
rule34,
system,
quizizz,
fml,
zalgo,
shift,
reddit_embed,
invite,
vaporwave,
cmd,
latency,
uwuify,
cache_stats,
insta_dl,
deviantart,
urban,
xkcd,
tic_tac_toe
)]
struct General;
async fn handle_ctrl_c(shard_manager: Arc<Mutex<ShardManager>>) {
match tokio::signal::ctrl_c().await {
Ok(_) => {
info!("Shutting down...");
info!("Stopping Client...");
shard_manager.lock().await.shutdown_all().await;
}
Err(e) => {
warn!("Failed to set Ctrl-C handler: {}", e);
// The default "kill everything" handler is probably still installed, so this isn't a problem?
}
};
}
fn after_handler<'fut>(
_ctx: &'fut Context,
_msg: &'fut Message,
command_name: &'fut str,
command_result: CommandResult,
) -> BoxFuture<'fut, ()> {
async move {
if let Err(e) = command_result {
error!("Failed to process command '{}': {}", command_name, e);
}
}
.boxed()
}
fn unrecognised_command_handler<'fut>(
ctx: &'fut Context,
msg: &'fut Message,
command_name: &'fut str,
) -> BoxFuture<'fut, ()> {
async move {
let _ = msg
.channel_id
.say(
&ctx.http,
format!("Could not find command '{}'", command_name),
)
.await
.is_ok();
}
.boxed()
}
fn process_dispatch_error<'fut>(
ctx: &'fut Context,
msg: &'fut Message,
error: DispatchError,
) -> BoxFuture<'fut, ()> {
process_dispatch_error_future(ctx, msg, error).boxed()
}
async fn process_dispatch_error_future<'fut>(
ctx: &'fut Context,
msg: &'fut Message,
error: DispatchError,
) {
match error {
DispatchError::Ratelimited(s) => {
let _ = msg
.channel_id
.say(
&ctx.http,
format!("Wait {} seconds to use that command again", s.as_secs()),
)
.await
.is_ok();
}
DispatchError::NotEnoughArguments { min, given } => {
let _ = msg
.channel_id
.say(
&ctx.http,
format!(
"Expected at least {} argument(s) for this command, but only got {}",
min, given
),
)
.await
.is_ok();
}
DispatchError::TooManyArguments { max, given } => {
let response_str = format!("Expected no more than {} argument(s) for this command, but got {}. Try using quotation marks if your argument has spaces.",
max, given
);
let _ = msg.channel_id.say(&ctx.http, response_str).await.is_ok();
}
DispatchError::CheckFailed(check_name, reason) => match reason {
Reason::User(user_reason_str) => {
let _ = msg.channel_id.say(&ctx.http, user_reason_str).await.is_ok();
}
_ => {
let _ = msg
.channel_id
.say(
&ctx.http,
format!("{} check failed: {:#?}", check_name, reason),
)
.await
.is_ok();
}
},
e => {
let _ = msg
.channel_id
.say(&ctx.http, format!("Unhandled Dispatch Error: {:?}", e))
.await
.is_ok();
}
};
}
/// Main Entry
fn main() {
let log_file_writer = match crate::logger::setup() {
Ok(file) => file,
Err(e) => {
error!("Failed to init logger: {}", e);
return;
}
};
info!("Loading `config.toml`...");
let mut config = match Config::load_from_path("./config.toml".as_ref()) {
Ok(c) => c,
Err(e) => {
error!("Failed to load `./config.toml`: {}", e);
return;
}
};
info!("Validating config.toml...");
let errors = config.validate();
let mut error_count = 0;
for e in errors {
match e.severity() {
Severity::Warn => {
warn!("Validation Warning: {}", e.error());
}
Severity::Error => {
error!("Validation Error: {}", e.error());
error_count += 1;
}
}
}
if error_count != 0 {
error!("Validation failed with {} errors.", error_count);
return;
}
info!("Opening data directory...");
let data_dir = config.data_dir();
let db_path = data_dir.join("pikadick.sqlite");
if data_dir.is_file() {
error!("Failed to create or open data directory, the path is a file.");
return;
}
let missing_data_dir = !data_dir.exists();
if missing_data_dir {
info!("Data directory does not exist. Creating...");
if let Err(e) = std::fs::create_dir_all(&data_dir) {
error!("Failed to create data directory: {}", e);
return;
};
} else if data_dir.is_dir() {
info!("Data directory already exists.");
}
info!("Initalizing File Logger...");
let log_file = match std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(data_dir.join("log.txt"))
{
Ok(f) => f,
Err(e) => {
error!("Failed to initalize file logger: {}", e);
return;
}
};
if let Err(e) = log_file_writer.init(log_file) {
error!("Failed to initalize file logger: {}", e);
return;
}
drop(log_file_writer);
info!("Starting Tokio Runtime...");
let tokio_rt = match RuntimeBuilder::new_multi_thread()
.enable_all()
.thread_name("pikadick-tokio-worker")
.build()
{
Ok(rt) => rt,
Err(e) => {
error!("Failed to start Tokio Runtime: {}", e);
return;
}
};
tokio_rt.block_on(async {
info!("Opening database...");
let db = match Database::new(&db_path, missing_data_dir).await {
Ok(db) => db,
Err(e) => {
error!("Failed to open database: {}", e);
return;
}
};
let uppercase_prefix = config.prefix().to_uppercase();
let framework = StandardFramework::new()
.configure(|c| {
c.prefixes(&[config.prefix(), &uppercase_prefix])
.case_insensitivity(true)
})
.help(&HELP)
.group(&GENERAL_GROUP)
// .bucket("nekos", |b| b.delay(1)) // TODO: Consider better ratelimit strategy
.bucket("r6stats", |b| b.delay(7))
.await
.bucket("r6tracker", |b| b.delay(7))
.await
.bucket("system", |b| b.delay(30))
.await
.bucket("quizizz", |b| b.delay(10))
.await
.bucket("insta-dl", |b| b.delay(10))
.await
.after(after_handler)
.unrecognised_command(unrecognised_command_handler)
.on_dispatch_error(process_dispatch_error);
info!("Using prefix '{}'", config.prefix());
let mut client = match Client::builder(config.token())
.event_handler(Handler)
.framework(framework)
.await
{
Ok(c) => c,
Err(e) => {
error!("Failed to create client: {}", e);
return;
}
};
let client_data = match ClientData::init(client.shard_manager.clone(), config, db).await {
Ok(c) => {
// Add all post-init client data changes here
c.enabled_check_data.add_groups(&[&GENERAL_GROUP]);
c
}
Err(e) => {
error!("Client Data Initialization failed: {}", e);
return;
}
};
{
let mut data = client.data.write().await;
data.insert::<ClientDataKey>(client_data);
}
info!("Logging in...");
tokio::spawn(handle_ctrl_c(client.shard_manager.clone()));
if let Err(why) = client.start().await {
error!("Error while running client: {}", why);
}
drop(client);
});
info!("Stopping Tokio Runtime...");
// TODO: Add a timeout to always shut down properly / Can i report when this fails?
// tokio_rt.shutdown_timeout(TOKIO_RT_SHUTDOWN_DURATION);
// Avoid using shutdown_timeout. Blocked on: https://github.com/tokio-rs/tokio/issues/2314
drop(tokio_rt);
info!("Successful Shutdown");
}
| Handler |
date.rs | // This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! ISO 8601 calendar date without timezone.
#[cfg(any(feature = "alloc", feature = "std", test))]
use core::borrow::Borrow;
use core::{str, fmt};
use core::ops::{Add, Sub, AddAssign, SubAssign};
use num_traits::ToPrimitive;
use oldtime::Duration as OldDuration;
use {Weekday, Datelike};
use div::div_mod_floor;
use naive::{NaiveTime, NaiveDateTime, IsoWeek};
use format::{Item, Numeric, Pad};
use format::{parse, Parsed, ParseError, ParseResult, StrftimeItems};
#[cfg(any(feature = "alloc", feature = "std", test))]
use format::DelayedFormat;
use super::isoweek;
use super::internals::{self, DateImpl, Of, Mdf, YearFlags};
const MAX_YEAR: i32 = internals::MAX_YEAR;
const MIN_YEAR: i32 = internals::MIN_YEAR;
// MAX_YEAR-12-31 minus 0000-01-01
// = ((MAX_YEAR+1)-01-01 minus 0001-01-01) + (0001-01-01 minus 0000-01-01) - 1 day
// = ((MAX_YEAR+1)-01-01 minus 0001-01-01) + 365 days
// = MAX_YEAR * 365 + (# of leap years from 0001 to MAX_YEAR) + 365 days
#[cfg(test)] // only used for testing
const MAX_DAYS_FROM_YEAR_0: i32 = MAX_YEAR * 365 +
MAX_YEAR / 4 -
MAX_YEAR / 100 +
MAX_YEAR / 400 + 365;
// MIN_YEAR-01-01 minus 0000-01-01
// = (MIN_YEAR+400n+1)-01-01 minus (400n+1)-01-01
// = ((MIN_YEAR+400n+1)-01-01 minus 0001-01-01) - ((400n+1)-01-01 minus 0001-01-01)
// = ((MIN_YEAR+400n+1)-01-01 minus 0001-01-01) - 146097n days
//
// n is set to 1000 for convenience.
#[cfg(test)] // only used for testing
const MIN_DAYS_FROM_YEAR_0: i32 = (MIN_YEAR + 400_000) * 365 +
(MIN_YEAR + 400_000) / 4 -
(MIN_YEAR + 400_000) / 100 +
(MIN_YEAR + 400_000) / 400 - 146097_000;
#[cfg(test)] // only used for testing, but duplicated in naive::datetime
const MAX_BITS: usize = 44;
/// ISO 8601 calendar date without timezone.
/// Allows for every [proleptic Gregorian date](#calendar-date)
/// from Jan 1, 262145 BCE to Dec 31, 262143 CE.
/// Also supports the conversion from ISO 8601 ordinal and week date.
///
/// # Calendar Date
///
/// The ISO 8601 **calendar date** follows the proleptic Gregorian calendar.
/// It is like a normal civil calendar but note some slight differences:
///
/// * Dates before the Gregorian calendar's inception in 1582 are defined via the extrapolation.
/// Be careful, as historical dates are often noted in the Julian calendar and others
/// and the transition to Gregorian may differ across countries (as late as early 20C).
///
/// (Some example: Both Shakespeare from Britain and Cervantes from Spain seemingly died
/// on the same calendar date---April 23, 1616---but in the different calendar.
/// Britain used the Julian calendar at that time, so Shakespeare's death is later.)
///
/// * ISO 8601 calendars has the year 0, which is 1 BCE (a year before 1 CE).
/// If you need a typical BCE/BC and CE/AD notation for year numbers,
/// use the [`Datelike::year_ce`](../trait.Datelike.html#method.year_ce) method.
///
/// # Week Date
///
/// The ISO 8601 **week date** is a triple of year number, week number
/// and [day of the week](../enum.Weekday.html) with the following rules:
///
/// * A week consists of Monday through Sunday, and is always numbered within some year.
/// The week number ranges from 1 to 52 or 53 depending on the year.
///
/// * The week 1 of given year is defined as the first week containing January 4 of that year,
/// or equivalently, the first week containing four or more days in that year.
///
/// * The year number in the week date may *not* correspond to the actual Gregorian year.
/// For example, January 3, 2016 (Sunday) was on the last (53rd) week of 2015.
///
/// Chrono's date types default to the ISO 8601 [calendar date](#calendar-date),
/// but [`Datelike::iso_week`](../trait.Datelike.html#tymethod.iso_week) and
/// [`Datelike::weekday`](../trait.Datelike.html#tymethod.weekday) methods
/// can be used to get the corresponding week date.
///
/// # Ordinal Date
///
/// The ISO 8601 **ordinal date** is a pair of year number and day of the year ("ordinal").
/// The ordinal number ranges from 1 to 365 or 366 depending on the year.
/// The year number is same to that of the [calendar date](#calendar-date).
///
/// This is currently the internal format of Chrono's date types.
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Copy, Clone)]
pub struct NaiveDate {
ymdf: DateImpl, // (year << 13) | of
}
/// The minimum possible `NaiveDate` (January 1, 262145 BCE).
pub const MIN_DATE: NaiveDate = NaiveDate { ymdf: (MIN_YEAR << 13) | (1 << 4) | 0o07 /*FE*/ };
/// The maximum possible `NaiveDate` (December 31, 262143 CE).
pub const MAX_DATE: NaiveDate = NaiveDate { ymdf: (MAX_YEAR << 13) | (365 << 4) | 0o17 /*F*/ };
// as it is hard to verify year flags in `MIN_DATE` and `MAX_DATE`,
// we use a separate run-time test.
#[test]
fn test_date_bounds() {
let calculated_min = NaiveDate::from_ymd(MIN_YEAR, 1, 1);
let calculated_max = NaiveDate::from_ymd(MAX_YEAR, 12, 31);
assert!(MIN_DATE == calculated_min,
"`MIN_DATE` should have a year flag {:?}", calculated_min.of().flags());
assert!(MAX_DATE == calculated_max,
"`MAX_DATE` should have a year flag {:?}", calculated_max.of().flags());
// let's also check that the entire range do not exceed 2^44 seconds
// (sometimes used for bounding `Duration` against overflow)
let maxsecs = MAX_DATE.signed_duration_since(MIN_DATE).num_seconds();
let maxsecs = maxsecs + 86401; // also take care of DateTime
assert!(maxsecs < (1 << MAX_BITS),
"The entire `NaiveDate` range somehow exceeds 2^{} seconds", MAX_BITS);
}
impl NaiveDate {
/// Makes a new `NaiveDate` from year and packed ordinal-flags, with a verification.
fn from_of(year: i32, of: Of) -> Option<NaiveDate> {
if year >= MIN_YEAR && year <= MAX_YEAR && of.valid() {
let Of(of) = of;
Some(NaiveDate { ymdf: (year << 13) | (of as DateImpl) })
} else {
None
}
}
/// Makes a new `NaiveDate` from year and packed month-day-flags, with a verification.
fn from_mdf(year: i32, mdf: Mdf) -> Option<NaiveDate> {
NaiveDate::from_of(year, mdf.to_of())
}
/// Makes a new `NaiveDate` from the [calendar date](#calendar-date)
/// (year, month and day).
///
/// Panics on the out-of-range date, invalid month and/or day.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike, Weekday};
///
/// let d = NaiveDate::from_ymd(2015, 3, 14);
/// assert_eq!(d.year(), 2015);
/// assert_eq!(d.month(), 3);
/// assert_eq!(d.day(), 14);
/// assert_eq!(d.ordinal(), 73); // day of year
/// assert_eq!(d.iso_week().year(), 2015);
/// assert_eq!(d.iso_week().week(), 11);
/// assert_eq!(d.weekday(), Weekday::Sat);
/// assert_eq!(d.num_days_from_ce(), 735671); // days since January 1, 1 CE
/// ~~~~
pub fn from_ymd(year: i32, month: u32, day: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(year, month, day).expect("invalid or out-of-range date")
}
/// Makes a new `NaiveDate` from the [calendar date](#calendar-date)
/// (year, month and day).
///
/// Returns `None` on the out-of-range date, invalid month and/or day.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let from_ymd_opt = NaiveDate::from_ymd_opt;
///
/// assert!(from_ymd_opt(2015, 3, 14).is_some());
/// assert!(from_ymd_opt(2015, 0, 14).is_none());
/// assert!(from_ymd_opt(2015, 2, 29).is_none());
/// assert!(from_ymd_opt(-4, 2, 29).is_some()); // 5 BCE is a leap year
/// assert!(from_ymd_opt(400000, 1, 1).is_none());
/// assert!(from_ymd_opt(-400000, 1, 1).is_none());
/// ~~~~
pub fn from_ymd_opt(year: i32, month: u32, day: u32) -> Option<NaiveDate> {
let flags = YearFlags::from_year(year);
NaiveDate::from_mdf(year, Mdf::new(month, day, flags))
}
/// Makes a new `NaiveDate` from the [ordinal date](#ordinal-date)
/// (year and day of the year).
///
/// Panics on the out-of-range date and/or invalid day of year.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike, Weekday};
///
/// let d = NaiveDate::from_yo(2015, 73);
/// assert_eq!(d.ordinal(), 73);
/// assert_eq!(d.year(), 2015);
/// assert_eq!(d.month(), 3);
/// assert_eq!(d.day(), 14);
/// assert_eq!(d.iso_week().year(), 2015);
/// assert_eq!(d.iso_week().week(), 11);
/// assert_eq!(d.weekday(), Weekday::Sat);
/// assert_eq!(d.num_days_from_ce(), 735671); // days since January 1, 1 CE
/// ~~~~
pub fn from_yo(year: i32, ordinal: u32) -> NaiveDate {
NaiveDate::from_yo_opt(year, ordinal).expect("invalid or out-of-range date")
}
/// Makes a new `NaiveDate` from the [ordinal date](#ordinal-date)
/// (year and day of the year).
///
/// Returns `None` on the out-of-range date and/or invalid day of year.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let from_yo_opt = NaiveDate::from_yo_opt;
///
/// assert!(from_yo_opt(2015, 100).is_some());
/// assert!(from_yo_opt(2015, 0).is_none());
/// assert!(from_yo_opt(2015, 365).is_some());
/// assert!(from_yo_opt(2015, 366).is_none());
/// assert!(from_yo_opt(-4, 366).is_some()); // 5 BCE is a leap year
/// assert!(from_yo_opt(400000, 1).is_none());
/// assert!(from_yo_opt(-400000, 1).is_none());
/// ~~~~
pub fn from_yo_opt(year: i32, ordinal: u32) -> Option<NaiveDate> {
let flags = YearFlags::from_year(year);
NaiveDate::from_of(year, Of::new(ordinal, flags))
}
/// Makes a new `NaiveDate` from the [ISO week date](#week-date)
/// (year, week number and day of the week).
/// The resulting `NaiveDate` may have a different year from the input year.
///
/// Panics on the out-of-range date and/or invalid week number.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike, Weekday};
///
/// let d = NaiveDate::from_isoywd(2015, 11, Weekday::Sat);
/// assert_eq!(d.iso_week().year(), 2015);
/// assert_eq!(d.iso_week().week(), 11);
/// assert_eq!(d.weekday(), Weekday::Sat);
/// assert_eq!(d.year(), 2015);
/// assert_eq!(d.month(), 3);
/// assert_eq!(d.day(), 14);
/// assert_eq!(d.ordinal(), 73); // day of year
/// assert_eq!(d.num_days_from_ce(), 735671); // days since January 1, 1 CE
/// ~~~~
pub fn from_isoywd(year: i32, week: u32, weekday: Weekday) -> NaiveDate {
NaiveDate::from_isoywd_opt(year, week, weekday).expect("invalid or out-of-range date")
}
/// Makes a new `NaiveDate` from the [ISO week date](#week-date)
/// (year, week number and day of the week).
/// The resulting `NaiveDate` may have a different year from the input year.
///
/// Returns `None` on the out-of-range date and/or invalid week number.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Weekday};
///
/// let from_ymd = NaiveDate::from_ymd;
/// let from_isoywd_opt = NaiveDate::from_isoywd_opt;
///
/// assert_eq!(from_isoywd_opt(2015, 0, Weekday::Sun), None);
/// assert_eq!(from_isoywd_opt(2015, 10, Weekday::Sun), Some(from_ymd(2015, 3, 8)));
/// assert_eq!(from_isoywd_opt(2015, 30, Weekday::Mon), Some(from_ymd(2015, 7, 20)));
/// assert_eq!(from_isoywd_opt(2015, 60, Weekday::Mon), None);
///
/// assert_eq!(from_isoywd_opt(400000, 10, Weekday::Fri), None);
/// assert_eq!(from_isoywd_opt(-400000, 10, Weekday::Sat), None);
/// ~~~~
///
/// The year number of ISO week date may differ from that of the calendar date.
///
/// ~~~~
/// # use chrono::{NaiveDate, Weekday};
/// # let from_ymd = NaiveDate::from_ymd;
/// # let from_isoywd_opt = NaiveDate::from_isoywd_opt;
/// // Mo Tu We Th Fr Sa Su
/// // 2014-W52 22 23 24 25 26 27 28 has 4+ days of new year,
/// // 2015-W01 29 30 31 1 2 3 4 <- so this is the first week
/// assert_eq!(from_isoywd_opt(2014, 52, Weekday::Sun), Some(from_ymd(2014, 12, 28)));
/// assert_eq!(from_isoywd_opt(2014, 53, Weekday::Mon), None);
/// assert_eq!(from_isoywd_opt(2015, 1, Weekday::Mon), Some(from_ymd(2014, 12, 29)));
///
/// // 2015-W52 21 22 23 24 25 26 27 has 4+ days of old year,
/// // 2015-W53 28 29 30 31 1 2 3 <- so this is the last week
/// // 2016-W01 4 5 6 7 8 9 10
/// assert_eq!(from_isoywd_opt(2015, 52, Weekday::Sun), Some(from_ymd(2015, 12, 27)));
/// assert_eq!(from_isoywd_opt(2015, 53, Weekday::Sun), Some(from_ymd(2016, 1, 3)));
/// assert_eq!(from_isoywd_opt(2015, 54, Weekday::Mon), None);
/// assert_eq!(from_isoywd_opt(2016, 1, Weekday::Mon), Some(from_ymd(2016, 1, 4)));
/// ~~~~
pub fn from_isoywd_opt(year: i32, week: u32, weekday: Weekday) -> Option<NaiveDate> {
let flags = YearFlags::from_year(year);
let nweeks = flags.nisoweeks();
if 1 <= week && week <= nweeks {
// ordinal = week ordinal - delta
let weekord = week * 7 + weekday as u32;
let delta = flags.isoweek_delta();
if weekord <= delta { // ordinal < 1, previous year
let prevflags = YearFlags::from_year(year - 1);
NaiveDate::from_of(year - 1, Of::new(weekord + prevflags.ndays() - delta,
prevflags))
} else {
let ordinal = weekord - delta;
let ndays = flags.ndays();
if ordinal <= ndays { // this year
NaiveDate::from_of(year, Of::new(ordinal, flags))
} else { // ordinal > ndays, next year
let nextflags = YearFlags::from_year(year + 1);
NaiveDate::from_of(year + 1, Of::new(ordinal - ndays, nextflags))
}
}
} else {
None
}
}
/// Makes a new `NaiveDate` from a day's number in the proleptic Gregorian calendar, with
/// January 1, 1 being day 1.
///
/// Panics if the date is out of range.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike, Weekday};
///
/// let d = NaiveDate::from_num_days_from_ce(735671);
/// assert_eq!(d.num_days_from_ce(), 735671); // days since January 1, 1 CE
/// assert_eq!(d.year(), 2015);
/// assert_eq!(d.month(), 3);
/// assert_eq!(d.day(), 14);
/// assert_eq!(d.ordinal(), 73); // day of year
/// assert_eq!(d.iso_week().year(), 2015);
/// assert_eq!(d.iso_week().week(), 11);
/// assert_eq!(d.weekday(), Weekday::Sat);
/// ~~~~
///
/// While not directly supported by Chrono,
/// it is easy to convert from the Julian day number
/// (January 1, 4713 BCE in the *Julian* calendar being Day 0)
/// to Gregorian with this method.
/// (Note that this panics when `jd` is out of range.)
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// fn jd_to_date(jd: i32) -> NaiveDate {
/// // keep in mind that the Julian day number is 0-based
/// // while this method requires an 1-based number.
/// NaiveDate::from_num_days_from_ce(jd - 1721425)
/// }
///
/// // January 1, 4713 BCE in Julian = November 24, 4714 BCE in Gregorian
/// assert_eq!(jd_to_date(0), NaiveDate::from_ymd(-4713, 11, 24));
///
/// assert_eq!(jd_to_date(1721426), NaiveDate::from_ymd(1, 1, 1));
/// assert_eq!(jd_to_date(2450000), NaiveDate::from_ymd(1995, 10, 9));
/// assert_eq!(jd_to_date(2451545), NaiveDate::from_ymd(2000, 1, 1));
/// ~~~~
#[inline]
pub fn from_num_days_from_ce(days: i32) -> NaiveDate {
NaiveDate::from_num_days_from_ce_opt(days).expect("out-of-range date")
}
/// Makes a new `NaiveDate` from a day's number in the proleptic Gregorian calendar, with
/// January 1, 1 being day 1.
///
/// Returns `None` if the date is out of range.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let from_ndays_opt = NaiveDate::from_num_days_from_ce_opt;
/// let from_ymd = NaiveDate::from_ymd;
///
/// assert_eq!(from_ndays_opt(730_000), Some(from_ymd(1999, 9, 3)));
/// assert_eq!(from_ndays_opt(1), Some(from_ymd(1, 1, 1)));
/// assert_eq!(from_ndays_opt(0), Some(from_ymd(0, 12, 31)));
/// assert_eq!(from_ndays_opt(-1), Some(from_ymd(0, 12, 30)));
/// assert_eq!(from_ndays_opt(100_000_000), None);
/// assert_eq!(from_ndays_opt(-100_000_000), None);
/// ~~~~
pub fn from_num_days_from_ce_opt(days: i32) -> Option<NaiveDate> {
let days = days + 365; // make December 31, 1 BCE equal to day 0
let (year_div_400, cycle) = div_mod_floor(days, 146_097);
let (year_mod_400, ordinal) = internals::cycle_to_yo(cycle as u32);
let flags = YearFlags::from_year_mod_400(year_mod_400 as i32);
NaiveDate::from_of(year_div_400 * 400 + year_mod_400 as i32,
Of::new(ordinal, flags))
}
/// Makes a new `NaiveDate` by counting the number of occurances of a particular day-of-week
/// since the beginning of the given month. For instance, if you want the 2nd Friday of March
/// 2017, you would use `NaiveDate::from_weekday_of_month(2017, 3, Weekday::Fri, 2)`.
///
/// # Panics
///
/// The resulting `NaiveDate` is guaranteed to be in `month`. If `n` is larger than the number
/// of `weekday` in `month` (eg. the 6th Friday of March 2017) then this function will panic.
///
/// `n` is 1-indexed. Passing `n=0` will cause a panic.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Weekday};
///
/// let from_weekday_of_month = NaiveDate::from_weekday_of_month;
/// let from_ymd = NaiveDate::from_ymd;
///
/// assert_eq!(from_weekday_of_month(2018, 8, Weekday::Wed, 1), from_ymd(2018, 8, 1));
/// assert_eq!(from_weekday_of_month(2018, 8, Weekday::Fri, 1), from_ymd(2018, 8, 3));
/// assert_eq!(from_weekday_of_month(2018, 8, Weekday::Tue, 2), from_ymd(2018, 8, 14));
/// assert_eq!(from_weekday_of_month(2018, 8, Weekday::Fri, 4), from_ymd(2018, 8, 24));
/// assert_eq!(from_weekday_of_month(2018, 8, Weekday::Fri, 5), from_ymd(2018, 8, 31));
/// ~~~~
pub fn from_weekday_of_month(year: i32, month: u32, weekday: Weekday, n: u8) -> NaiveDate {
NaiveDate::from_weekday_of_month_opt(year, month, weekday, n).expect("out-of-range date")
}
/// Makes a new `NaiveDate` by counting the number of occurances of a particular day-of-week
/// since the beginning of the given month. For instance, if you want the 2nd Friday of March
/// 2017, you would use `NaiveDate::from_weekday_of_month(2017, 3, Weekday::Fri, 2)`. `n` is 1-indexed.
///
/// ~~~~
/// use chrono::{NaiveDate, Weekday};
/// assert_eq!(NaiveDate::from_weekday_of_month_opt(2017, 3, Weekday::Fri, 2),
/// NaiveDate::from_ymd_opt(2017, 3, 10))
/// ~~~~
///
/// Returns `None` if `n` out-of-range; ie. if `n` is larger than the number of `weekday` in
/// `month` (eg. the 6th Friday of March 2017), or if `n == 0`.
pub fn from_weekday_of_month_opt(year: i32, month: u32, weekday: Weekday, n: u8) -> Option<NaiveDate> {
if n == 0 { return None; }
let first = NaiveDate::from_ymd(year, month, 1).weekday();
let first_to_dow = (7 + weekday.number_from_monday() - first.number_from_monday()) % 7;
let day = (u32::from(n) - 1) * 7 + first_to_dow + 1;
NaiveDate::from_ymd_opt(year, month, day)
}
/// Parses a string with the specified format string and returns a new `NaiveDate`.
/// See the [`format::strftime` module](../format/strftime/index.html)
/// on the supported escape sequences.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let parse_from_str = NaiveDate::parse_from_str;
///
/// assert_eq!(parse_from_str("2015-09-05", "%Y-%m-%d"),
/// Ok(NaiveDate::from_ymd(2015, 9, 5)));
/// assert_eq!(parse_from_str("5sep2015", "%d%b%Y"),
/// Ok(NaiveDate::from_ymd(2015, 9, 5)));
/// ~~~~
///
/// Time and offset is ignored for the purpose of parsing.
///
/// ~~~~
/// # use chrono::NaiveDate;
/// # let parse_from_str = NaiveDate::parse_from_str;
/// assert_eq!(parse_from_str("2014-5-17T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
/// Ok(NaiveDate::from_ymd(2014, 5, 17)));
/// ~~~~
///
/// Out-of-bound dates or insufficient fields are errors.
///
/// ~~~~
/// # use chrono::NaiveDate;
/// # let parse_from_str = NaiveDate::parse_from_str;
/// assert!(parse_from_str("2015/9", "%Y/%m").is_err());
/// assert!(parse_from_str("2015/9/31", "%Y/%m/%d").is_err());
/// ~~~~
///
/// All parsed fields should be consistent to each other, otherwise it's an error.
///
/// ~~~~
/// # use chrono::NaiveDate;
/// # let parse_from_str = NaiveDate::parse_from_str;
/// assert!(parse_from_str("Sat, 09 Aug 2013", "%a, %d %b %Y").is_err());
/// ~~~~
pub fn parse_from_str(s: &str, fmt: &str) -> ParseResult<NaiveDate> {
let mut parsed = Parsed::new();
parse(&mut parsed, s, StrftimeItems::new(fmt))?;
parsed.to_naive_date()
}
/// Makes a new `NaiveDateTime` from the current date and given `NaiveTime`.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, NaiveTime, NaiveDateTime};
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
/// let t = NaiveTime::from_hms_milli(12, 34, 56, 789);
///
/// let dt: NaiveDateTime = d.and_time(t);
/// assert_eq!(dt.date(), d);
/// assert_eq!(dt.time(), t);
/// ~~~~
#[inline]
pub fn and_time(&self, time: NaiveTime) -> NaiveDateTime {
NaiveDateTime::new(*self, time)
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute and second.
///
/// No [leap second](./struct.NaiveTime.html#leap-second-handling) is allowed here;
/// use `NaiveDate::and_hms_*` methods with a subsecond parameter instead.
///
/// Panics on invalid hour, minute and/or second.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, NaiveDateTime, Datelike, Timelike, Weekday};
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
///
/// let dt: NaiveDateTime = d.and_hms(12, 34, 56);
/// assert_eq!(dt.year(), 2015);
/// assert_eq!(dt.weekday(), Weekday::Wed);
/// assert_eq!(dt.second(), 56);
/// ~~~~
#[inline]
pub fn and_hms(&self, hour: u32, min: u32, sec: u32) -> NaiveDateTime {
self.and_hms_opt(hour, min, sec).expect("invalid time")
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute and second.
///
/// No [leap second](./struct.NaiveTime.html#leap-second-handling) is allowed here;
/// use `NaiveDate::and_hms_*_opt` methods with a subsecond parameter instead.
///
/// Returns `None` on invalid hour, minute and/or second.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
/// assert!(d.and_hms_opt(12, 34, 56).is_some());
/// assert!(d.and_hms_opt(12, 34, 60).is_none()); // use `and_hms_milli_opt` instead
/// assert!(d.and_hms_opt(12, 60, 56).is_none());
/// assert!(d.and_hms_opt(24, 34, 56).is_none());
/// ~~~~
#[inline]
pub fn and_hms_opt(&self, hour: u32, min: u32, sec: u32) -> Option<NaiveDateTime> {
NaiveTime::from_hms_opt(hour, min, sec).map(|time| self.and_time(time))
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and millisecond.
///
/// The millisecond part can exceed 1,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Panics on invalid hour, minute, second and/or millisecond.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, NaiveDateTime, Datelike, Timelike, Weekday};
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
///
/// let dt: NaiveDateTime = d.and_hms_milli(12, 34, 56, 789);
/// assert_eq!(dt.year(), 2015);
/// assert_eq!(dt.weekday(), Weekday::Wed);
/// assert_eq!(dt.second(), 56);
/// assert_eq!(dt.nanosecond(), 789_000_000);
/// ~~~~
#[inline]
pub fn and_hms_milli(&self, hour: u32, min: u32, sec: u32, milli: u32) -> NaiveDateTime {
self.and_hms_milli_opt(hour, min, sec, milli).expect("invalid time")
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and millisecond.
///
/// The millisecond part can exceed 1,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Returns `None` on invalid hour, minute, second and/or millisecond.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
/// assert!(d.and_hms_milli_opt(12, 34, 56, 789).is_some());
/// assert!(d.and_hms_milli_opt(12, 34, 59, 1_789).is_some()); // leap second
/// assert!(d.and_hms_milli_opt(12, 34, 59, 2_789).is_none());
/// assert!(d.and_hms_milli_opt(12, 34, 60, 789).is_none());
/// assert!(d.and_hms_milli_opt(12, 60, 56, 789).is_none());
/// assert!(d.and_hms_milli_opt(24, 34, 56, 789).is_none());
/// ~~~~
#[inline]
pub fn and_hms_milli_opt(&self, hour: u32, min: u32, sec: u32,
milli: u32) -> Option<NaiveDateTime> {
NaiveTime::from_hms_milli_opt(hour, min, sec, milli).map(|time| self.and_time(time))
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and microsecond.
///
/// The microsecond part can exceed 1,000,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Panics on invalid hour, minute, second and/or microsecond.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, NaiveDateTime, Datelike, Timelike, Weekday};
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
///
/// let dt: NaiveDateTime = d.and_hms_micro(12, 34, 56, 789_012);
/// assert_eq!(dt.year(), 2015);
/// assert_eq!(dt.weekday(), Weekday::Wed);
/// assert_eq!(dt.second(), 56);
/// assert_eq!(dt.nanosecond(), 789_012_000);
/// ~~~~
#[inline]
pub fn and_hms_micro(&self, hour: u32, min: u32, sec: u32, micro: u32) -> NaiveDateTime {
self.and_hms_micro_opt(hour, min, sec, micro).expect("invalid time")
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and microsecond.
///
/// The microsecond part can exceed 1,000,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Returns `None` on invalid hour, minute, second and/or microsecond.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
/// assert!(d.and_hms_micro_opt(12, 34, 56, 789_012).is_some());
/// assert!(d.and_hms_micro_opt(12, 34, 59, 1_789_012).is_some()); // leap second
/// assert!(d.and_hms_micro_opt(12, 34, 59, 2_789_012).is_none());
/// assert!(d.and_hms_micro_opt(12, 34, 60, 789_012).is_none());
/// assert!(d.and_hms_micro_opt(12, 60, 56, 789_012).is_none());
/// assert!(d.and_hms_micro_opt(24, 34, 56, 789_012).is_none());
/// ~~~~
#[inline]
pub fn and_hms_micro_opt(&self, hour: u32, min: u32, sec: u32,
micro: u32) -> Option<NaiveDateTime> {
NaiveTime::from_hms_micro_opt(hour, min, sec, micro).map(|time| self.and_time(time))
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and nanosecond.
///
/// The nanosecond part can exceed 1,000,000,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Panics on invalid hour, minute, second and/or nanosecond.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, NaiveDateTime, Datelike, Timelike, Weekday};
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
///
/// let dt: NaiveDateTime = d.and_hms_nano(12, 34, 56, 789_012_345);
/// assert_eq!(dt.year(), 2015);
/// assert_eq!(dt.weekday(), Weekday::Wed);
/// assert_eq!(dt.second(), 56);
/// assert_eq!(dt.nanosecond(), 789_012_345);
/// ~~~~
#[inline]
pub fn and_hms_nano(&self, hour: u32, min: u32, sec: u32, nano: u32) -> NaiveDateTime {
self.and_hms_nano_opt(hour, min, sec, nano).expect("invalid time")
}
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and nanosecond.
///
/// The nanosecond part can exceed 1,000,000,000
/// in order to represent the [leap second](./struct.NaiveTime.html#leap-second-handling).
///
/// Returns `None` on invalid hour, minute, second and/or nanosecond.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd(2015, 6, 3);
/// assert!(d.and_hms_nano_opt(12, 34, 56, 789_012_345).is_some());
/// assert!(d.and_hms_nano_opt(12, 34, 59, 1_789_012_345).is_some()); // leap second
/// assert!(d.and_hms_nano_opt(12, 34, 59, 2_789_012_345).is_none());
/// assert!(d.and_hms_nano_opt(12, 34, 60, 789_012_345).is_none());
/// assert!(d.and_hms_nano_opt(12, 60, 56, 789_012_345).is_none());
/// assert!(d.and_hms_nano_opt(24, 34, 56, 789_012_345).is_none());
/// ~~~~
#[inline]
pub fn and_hms_nano_opt(&self, hour: u32, min: u32, sec: u32,
nano: u32) -> Option<NaiveDateTime> {
NaiveTime::from_hms_nano_opt(hour, min, sec, nano).map(|time| self.and_time(time))
}
/// Returns the packed month-day-flags.
#[inline]
fn mdf(&self) -> Mdf {
self.of().to_mdf()
}
/// Returns the packed ordinal-flags.
#[inline]
fn of(&self) -> Of {
Of((self.ymdf & 0b1_1111_1111_1111) as u32)
}
/// Makes a new `NaiveDate` with the packed month-day-flags changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
#[inline]
fn with_mdf(&self, mdf: Mdf) -> Option<NaiveDate> {
self.with_of(mdf.to_of())
}
/// Makes a new `NaiveDate` with the packed ordinal-flags changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
#[inline]
fn with_of(&self, of: Of) -> Option<NaiveDate> {
if of.valid() {
let Of(of) = of;
Some(NaiveDate { ymdf: (self.ymdf & !0b1_1111_1111_1111) | of as DateImpl })
} else {
None
}
}
/// Makes a new `NaiveDate` for the next calendar date.
///
/// Panics when `self` is the last representable date.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// assert_eq!(NaiveDate::from_ymd(2015, 6, 3).succ(), NaiveDate::from_ymd(2015, 6, 4));
/// assert_eq!(NaiveDate::from_ymd(2015, 6, 30).succ(), NaiveDate::from_ymd(2015, 7, 1));
/// assert_eq!(NaiveDate::from_ymd(2015, 12, 31).succ(), NaiveDate::from_ymd(2016, 1, 1));
/// ~~~~
#[inline]
pub fn succ(&self) -> NaiveDate {
self.succ_opt().expect("out of bound")
}
/// Makes a new `NaiveDate` for the next calendar date.
///
/// Returns `None` when `self` is the last representable date.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
/// use chrono::naive::MAX_DATE;
///
/// assert_eq!(NaiveDate::from_ymd(2015, 6, 3).succ_opt(),
/// Some(NaiveDate::from_ymd(2015, 6, 4)));
/// assert_eq!(MAX_DATE.succ_opt(), None);
/// ~~~~
#[inline]
pub fn succ_opt(&self) -> Option<NaiveDate> {
self.with_of(self.of().succ()).or_else(|| NaiveDate::from_ymd_opt(self.year() + 1, 1, 1))
}
/// Makes a new `NaiveDate` for the previous calendar date.
///
/// Panics when `self` is the first representable date.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// assert_eq!(NaiveDate::from_ymd(2015, 6, 3).pred(), NaiveDate::from_ymd(2015, 6, 2));
/// assert_eq!(NaiveDate::from_ymd(2015, 6, 1).pred(), NaiveDate::from_ymd(2015, 5, 31));
/// assert_eq!(NaiveDate::from_ymd(2015, 1, 1).pred(), NaiveDate::from_ymd(2014, 12, 31));
/// ~~~~
#[inline]
pub fn pred(&self) -> NaiveDate {
self.pred_opt().expect("out of bound")
}
/// Makes a new `NaiveDate` for the previous calendar date.
///
/// Returns `None` when `self` is the first representable date.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
/// use chrono::naive::MIN_DATE;
///
/// assert_eq!(NaiveDate::from_ymd(2015, 6, 3).pred_opt(),
/// Some(NaiveDate::from_ymd(2015, 6, 2)));
/// assert_eq!(MIN_DATE.pred_opt(), None);
/// ~~~~
#[inline]
pub fn pred_opt(&self) -> Option<NaiveDate> {
self.with_of(self.of().pred()).or_else(|| NaiveDate::from_ymd_opt(self.year() - 1, 12, 31))
}
/// Adds the `days` part of given `Duration` to the current date.
///
/// Returns `None` when it will result in overflow.
///
/// # Example
///
/// ~~~~
/// # extern crate chrono; fn main() {
/// use chrono::{NaiveDate, Duration};
/// use chrono::naive::MAX_DATE;
///
/// let d = NaiveDate::from_ymd(2015, 9, 5);
/// assert_eq!(d.checked_add_signed(Duration::days(40)),
/// Some(NaiveDate::from_ymd(2015, 10, 15)));
/// assert_eq!(d.checked_add_signed(Duration::days(-40)),
/// Some(NaiveDate::from_ymd(2015, 7, 27)));
/// assert_eq!(d.checked_add_signed(Duration::days(1_000_000_000)), None);
/// assert_eq!(d.checked_add_signed(Duration::days(-1_000_000_000)), None);
/// assert_eq!(MAX_DATE.checked_add_signed(Duration::days(1)), None);
/// # }
/// ~~~~
pub fn checked_add_signed(self, rhs: OldDuration) -> Option<NaiveDate> {
let year = self.year();
let (mut year_div_400, year_mod_400) = div_mod_floor(year, 400);
let cycle = internals::yo_to_cycle(year_mod_400 as u32, self.of().ordinal());
let cycle = try_opt!((cycle as i32).checked_add(try_opt!(rhs.num_days().to_i32())));
let (cycle_div_400y, cycle) = div_mod_floor(cycle, 146_097);
year_div_400 += cycle_div_400y;
let (year_mod_400, ordinal) = internals::cycle_to_yo(cycle as u32);
let flags = YearFlags::from_year_mod_400(year_mod_400 as i32);
NaiveDate::from_of(year_div_400 * 400 + year_mod_400 as i32,
Of::new(ordinal, flags))
}
/// Subtracts the `days` part of given `Duration` from the current date.
///
/// Returns `None` when it will result in overflow.
///
/// # Example
///
/// ~~~~
/// # extern crate chrono; fn main() {
/// use chrono::{NaiveDate, Duration};
/// use chrono::naive::MIN_DATE;
///
/// let d = NaiveDate::from_ymd(2015, 9, 5);
/// assert_eq!(d.checked_sub_signed(Duration::days(40)),
/// Some(NaiveDate::from_ymd(2015, 7, 27)));
/// assert_eq!(d.checked_sub_signed(Duration::days(-40)),
/// Some(NaiveDate::from_ymd(2015, 10, 15)));
/// assert_eq!(d.checked_sub_signed(Duration::days(1_000_000_000)), None);
/// assert_eq!(d.checked_sub_signed(Duration::days(-1_000_000_000)), None);
/// assert_eq!(MIN_DATE.checked_sub_signed(Duration::days(1)), None);
/// # }
/// ~~~~
pub fn checked_sub_signed(self, rhs: OldDuration) -> Option<NaiveDate> {
let year = self.year();
let (mut year_div_400, year_mod_400) = div_mod_floor(year, 400);
let cycle = internals::yo_to_cycle(year_mod_400 as u32, self.of().ordinal());
let cycle = try_opt!((cycle as i32).checked_sub(try_opt!(rhs.num_days().to_i32())));
let (cycle_div_400y, cycle) = div_mod_floor(cycle, 146_097);
year_div_400 += cycle_div_400y;
let (year_mod_400, ordinal) = internals::cycle_to_yo(cycle as u32);
let flags = YearFlags::from_year_mod_400(year_mod_400 as i32);
NaiveDate::from_of(year_div_400 * 400 + year_mod_400 as i32,
Of::new(ordinal, flags))
}
/// Subtracts another `NaiveDate` from the current date.
/// Returns a `Duration` of integral numbers.
///
/// This does not overflow or underflow at all,
/// as all possible output fits in the range of `Duration`.
///
/// # Example
///
/// ~~~~
/// # extern crate chrono; fn main() {
/// use chrono::{NaiveDate, Duration};
///
/// let from_ymd = NaiveDate::from_ymd;
/// let since = NaiveDate::signed_duration_since;
///
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2014, 1, 1)), Duration::zero());
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2013, 12, 31)), Duration::days(1));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2014, 1, 2)), Duration::days(-1));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2013, 9, 23)), Duration::days(100));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2013, 1, 1)), Duration::days(365));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(2010, 1, 1)), Duration::days(365*4 + 1));
/// assert_eq!(since(from_ymd(2014, 1, 1), from_ymd(1614, 1, 1)), Duration::days(365*400 + 97));
/// # }
/// ~~~~
pub fn signed_duration_since(self, rhs: NaiveDate) -> OldDuration {
let year1 = self.year();
let year2 = rhs.year();
let (year1_div_400, year1_mod_400) = div_mod_floor(year1, 400);
let (year2_div_400, year2_mod_400) = div_mod_floor(year2, 400);
let cycle1 = i64::from(internals::yo_to_cycle(year1_mod_400 as u32, self.of().ordinal()));
let cycle2 = i64::from(internals::yo_to_cycle(year2_mod_400 as u32, rhs.of().ordinal()));
OldDuration::days((i64::from(year1_div_400) - i64::from(year2_div_400)) * 146_097 +
(cycle1 - cycle2))
}
/// Formats the date with the specified formatting items.
/// Otherwise it is same to the ordinary `format` method.
///
/// The `Iterator` of items should be `Clone`able,
/// since the resulting `DelayedFormat` value may be formatted multiple times.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
/// use chrono::format::strftime::StrftimeItems;
///
/// let fmt = StrftimeItems::new("%Y-%m-%d");
/// let d = NaiveDate::from_ymd(2015, 9, 5);
/// assert_eq!(d.format_with_items(fmt.clone()).to_string(), "2015-09-05");
/// assert_eq!(d.format("%Y-%m-%d").to_string(), "2015-09-05");
/// ~~~~
///
/// The resulting `DelayedFormat` can be formatted directly via the `Display` trait.
///
/// ~~~~
/// # use chrono::NaiveDate;
/// # use chrono::format::strftime::StrftimeItems;
/// # let fmt = StrftimeItems::new("%Y-%m-%d").clone();
/// # let d = NaiveDate::from_ymd(2015, 9, 5);
/// assert_eq!(format!("{}", d.format_with_items(fmt)), "2015-09-05");
/// ~~~~
#[cfg(any(feature = "alloc", feature = "std", test))]
#[inline]
pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
where I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>> {
DelayedFormat::new(Some(*self), None, items)
}
/// Formats the date with the specified format string.
/// See the [`format::strftime` module](../format/strftime/index.html)
/// on the supported escape sequences.
///
/// This returns a `DelayedFormat`,
/// which gets converted to a string only when actual formatting happens.
/// You may use the `to_string` method to get a `String`,
/// or just feed it into `print!` and other formatting macros.
/// (In this way it avoids the redundant memory allocation.)
///
/// A wrong format string does *not* issue an error immediately.
/// Rather, converting or formatting the `DelayedFormat` fails.
/// You are recommended to immediately use `DelayedFormat` for this reason.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd(2015, 9, 5);
/// assert_eq!(d.format("%Y-%m-%d").to_string(), "2015-09-05");
/// assert_eq!(d.format("%A, %-d %B, %C%y").to_string(), "Saturday, 5 September, 2015");
/// ~~~~
///
/// The resulting `DelayedFormat` can be formatted directly via the `Display` trait.
///
/// ~~~~
/// # use chrono::NaiveDate;
/// # let d = NaiveDate::from_ymd(2015, 9, 5);
/// assert_eq!(format!("{}", d.format("%Y-%m-%d")), "2015-09-05");
/// assert_eq!(format!("{}", d.format("%A, %-d %B, %C%y")), "Saturday, 5 September, 2015");
/// ~~~~
#[cfg(any(feature = "alloc", feature = "std", test))]
#[inline]
pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
self.format_with_items(StrftimeItems::new(fmt))
}
}
impl Datelike for NaiveDate {
/// Returns the year number in the [calendar date](#calendar-date).
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).year(), 2015);
/// assert_eq!(NaiveDate::from_ymd(-308, 3, 14).year(), -308); // 309 BCE
/// ~~~~
#[inline]
fn year(&self) -> i32 {
self.ymdf >> 13
}
/// Returns the month number starting from 1.
///
/// The return value ranges from 1 to 12.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).month(), 9);
/// assert_eq!(NaiveDate::from_ymd(-308, 3, 14).month(), 3);
/// ~~~~
#[inline]
fn month(&self) -> u32 {
self.mdf().month()
}
/// Returns the month number starting from 0.
///
/// The return value ranges from 0 to 11.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).month0(), 8);
/// assert_eq!(NaiveDate::from_ymd(-308, 3, 14).month0(), 2);
/// ~~~~
#[inline]
fn month0(&self) -> u32 {
self.mdf().month() - 1
}
/// Returns the day of month starting from 1.
///
/// The return value ranges from 1 to 31. (The last day of month differs by months.)
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).day(), 8);
/// assert_eq!(NaiveDate::from_ymd(-308, 3, 14).day(), 14);
/// ~~~~
///
/// Combined with [`NaiveDate::pred`](#method.pred),
/// one can determine the number of days in a particular month.
/// (Note that this panics when `year` is out of range.)
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// fn ndays_in_month(year: i32, month: u32) -> u32 {
/// // the first day of the next month...
/// let (y, m) = if month == 12 { (year + 1, 1) } else { (year, month + 1) };
/// let d = NaiveDate::from_ymd(y, m, 1);
///
/// // ...is preceded by the last day of the original month
/// d.pred().day()
/// }
///
/// assert_eq!(ndays_in_month(2015, 8), 31);
/// assert_eq!(ndays_in_month(2015, 9), 30);
/// assert_eq!(ndays_in_month(2015, 12), 31);
/// assert_eq!(ndays_in_month(2016, 2), 29);
/// assert_eq!(ndays_in_month(2017, 2), 28);
/// ~~~~
#[inline]
fn day(&self) -> u32 {
self.mdf().day()
}
/// Returns the day of month starting from 0.
///
/// The return value ranges from 0 to 30. (The last day of month differs by months.)
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).day0(), 7);
/// assert_eq!(NaiveDate::from_ymd(-308, 3, 14).day0(), 13);
/// ~~~~
#[inline]
fn day0(&self) -> u32 {
self.mdf().day() - 1
}
/// Returns the day of year starting from 1.
///
/// The return value ranges from 1 to 366. (The last day of year differs by years.)
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).ordinal(), 251);
/// assert_eq!(NaiveDate::from_ymd(-308, 3, 14).ordinal(), 74);
/// ~~~~
///
/// Combined with [`NaiveDate::pred`](#method.pred),
/// one can determine the number of days in a particular year.
/// (Note that this panics when `year` is out of range.)
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// fn ndays_in_year(year: i32) -> u32 {
/// // the first day of the next year...
/// let d = NaiveDate::from_ymd(year + 1, 1, 1);
///
/// // ...is preceded by the last day of the original year
/// d.pred().ordinal()
/// }
///
/// assert_eq!(ndays_in_year(2015), 365);
/// assert_eq!(ndays_in_year(2016), 366);
/// assert_eq!(ndays_in_year(2017), 365);
/// assert_eq!(ndays_in_year(2000), 366);
/// assert_eq!(ndays_in_year(2100), 365);
/// ~~~~
#[inline]
fn ordinal(&self) -> u32 {
self.of().ordinal()
}
/// Returns the day of year starting from 0.
///
/// The return value ranges from 0 to 365. (The last day of year differs by years.)
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).ordinal0(), 250);
/// assert_eq!(NaiveDate::from_ymd(-308, 3, 14).ordinal0(), 73);
/// ~~~~
#[inline]
fn ordinal0(&self) -> u32 {
self.of().ordinal() - 1
}
/// Returns the day of week.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike, Weekday};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).weekday(), Weekday::Tue);
/// assert_eq!(NaiveDate::from_ymd(-308, 3, 14).weekday(), Weekday::Fri);
/// ~~~~
#[inline]
fn weekday(&self) -> Weekday {
self.of().weekday()
}
#[inline]
fn iso_week(&self) -> IsoWeek {
isoweek::iso_week_from_yof(self.year(), self.of())
}
/// Makes a new `NaiveDate` with the year number changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_year(2016),
/// Some(NaiveDate::from_ymd(2016, 9, 8)));
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_year(-308),
/// Some(NaiveDate::from_ymd(-308, 9, 8)));
/// ~~~~
///
/// A leap day (February 29) is a good example that this method can return `None`.
///
/// ~~~~
/// # use chrono::{NaiveDate, Datelike};
/// assert!(NaiveDate::from_ymd(2016, 2, 29).with_year(2015).is_none());
/// assert!(NaiveDate::from_ymd(2016, 2, 29).with_year(2020).is_some());
/// ~~~~
#[inline]
fn with_year(&self, year: i32) -> Option<NaiveDate> {
// we need to operate with `mdf` since we should keep the month and day number as is
let mdf = self.mdf();
// adjust the flags as needed
let flags = YearFlags::from_year(year);
let mdf = mdf.with_flags(flags);
NaiveDate::from_mdf(year, mdf)
}
/// Makes a new `NaiveDate` with the month number (starting from 1) changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_month(10),
/// Some(NaiveDate::from_ymd(2015, 10, 8)));
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_month(13), None); // no month 13
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 30).with_month(2), None); // no February 30
/// ~~~~
#[inline]
fn with_month(&self, month: u32) -> Option<NaiveDate> {
self.with_mdf(self.mdf().with_month(month))
}
/// Makes a new `NaiveDate` with the month number (starting from 0) changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_month0(9),
/// Some(NaiveDate::from_ymd(2015, 10, 8)));
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_month0(12), None); // no month 13
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 30).with_month0(1), None); // no February 30
/// ~~~~
#[inline]
fn with_month0(&self, month0: u32) -> Option<NaiveDate> {
self.with_mdf(self.mdf().with_month(month0 + 1))
}
/// Makes a new `NaiveDate` with the day of month (starting from 1) changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_day(30),
/// Some(NaiveDate::from_ymd(2015, 9, 30)));
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_day(31),
/// None); // no September 31
/// ~~~~
#[inline]
fn with_day(&self, day: u32) -> Option<NaiveDate> {
self.with_mdf(self.mdf().with_day(day))
}
/// Makes a new `NaiveDate` with the day of month (starting from 0) changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_day0(29),
/// Some(NaiveDate::from_ymd(2015, 9, 30)));
/// assert_eq!(NaiveDate::from_ymd(2015, 9, 8).with_day0(30),
/// None); // no September 31
/// ~~~~
#[inline]
fn with_day0(&self, day0: u32) -> Option<NaiveDate> {
self.with_mdf(self.mdf().with_day(day0 + 1))
}
/// Makes a new `NaiveDate` with the day of year (starting from 1) changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 1, 1).with_ordinal(60),
/// Some(NaiveDate::from_ymd(2015, 3, 1)));
/// assert_eq!(NaiveDate::from_ymd(2015, 1, 1).with_ordinal(366),
/// None); // 2015 had only 365 days
///
/// assert_eq!(NaiveDate::from_ymd(2016, 1, 1).with_ordinal(60),
/// Some(NaiveDate::from_ymd(2016, 2, 29)));
/// assert_eq!(NaiveDate::from_ymd(2016, 1, 1).with_ordinal(366),
/// Some(NaiveDate::from_ymd(2016, 12, 31)));
/// ~~~~
#[inline]
fn with_ordinal(&self, ordinal: u32) -> Option<NaiveDate> {
self.with_of(self.of().with_ordinal(ordinal))
}
/// Makes a new `NaiveDate` with the day of year (starting from 0) changed.
///
/// Returns `None` when the resulting `NaiveDate` would be invalid.
///
/// # Example
///
/// ~~~~
/// use chrono::{NaiveDate, Datelike};
///
/// assert_eq!(NaiveDate::from_ymd(2015, 1, 1).with_ordinal0(59),
/// Some(NaiveDate::from_ymd(2015, 3, 1)));
/// assert_eq!(NaiveDate::from_ymd(2015, 1, 1).with_ordinal0(365),
/// None); // 2015 had only 365 days
///
/// assert_eq!(NaiveDate::from_ymd(2016, 1, 1).with_ordinal0(59),
/// Some(NaiveDate::from_ymd(2016, 2, 29)));
/// assert_eq!(NaiveDate::from_ymd(2016, 1, 1).with_ordinal0(365),
/// Some(NaiveDate::from_ymd(2016, 12, 31)));
/// ~~~~
#[inline]
fn with_ordinal0(&self, ordinal0: u32) -> Option<NaiveDate> {
self.with_of(self.of().with_ordinal(ordinal0 + 1))
}
}
/// An addition of `Duration` to `NaiveDate` discards the fractional days,
/// rounding to the closest integral number of days towards `Duration::zero()`.
///
/// Panics on underflow or overflow.
/// Use [`NaiveDate::checked_add_signed`](#method.checked_add_signed) to detect that.
///
/// # Example
///
/// ~~~~
/// # extern crate chrono; fn main() {
/// use chrono::{NaiveDate, Duration};
///
/// let from_ymd = NaiveDate::from_ymd;
///
/// assert_eq!(from_ymd(2014, 1, 1) + Duration::zero(), from_ymd(2014, 1, 1));
/// assert_eq!(from_ymd(2014, 1, 1) + Duration::seconds(86399), from_ymd(2014, 1, 1));
/// assert_eq!(from_ymd(2014, 1, 1) + Duration::seconds(-86399), from_ymd(2014, 1, 1));
/// assert_eq!(from_ymd(2014, 1, 1) + Duration::days(1), from_ymd(2014, 1, 2));
/// assert_eq!(from_ymd(2014, 1, 1) + Duration::days(-1), from_ymd(2013, 12, 31));
/// assert_eq!(from_ymd(2014, 1, 1) + Duration::days(364), from_ymd(2014, 12, 31));
/// assert_eq!(from_ymd(2014, 1, 1) + Duration::days(365*4 + 1), from_ymd(2018, 1, 1));
/// assert_eq!(from_ymd(2014, 1, 1) + Duration::days(365*400 + 97), from_ymd(2414, 1, 1));
/// # }
/// ~~~~
impl Add<OldDuration> for NaiveDate {
type Output = NaiveDate;
#[inline]
fn add(self, rhs: OldDuration) -> NaiveDate {
self.checked_add_signed(rhs).expect("`NaiveDate + Duration` overflowed")
}
}
impl AddAssign<OldDuration> for NaiveDate {
#[inline]
fn add_assign(&mut self, rhs: OldDuration) {
*self = self.add(rhs);
}
}
/// A subtraction of `Duration` from `NaiveDate` discards the fractional days,
/// rounding to the closest integral number of days towards `Duration::zero()`.
/// It is same to the addition with a negated `Duration`.
///
/// Panics on underflow or overflow.
/// Use [`NaiveDate::checked_sub_signed`](#method.checked_sub_signed) to detect that.
///
/// # Example
///
/// ~~~~
/// # extern crate chrono; fn main() {
/// use chrono::{NaiveDate, Duration};
///
/// let from_ymd = NaiveDate::from_ymd;
///
/// assert_eq!(from_ymd(2014, 1, 1) - Duration::zero(), from_ymd(2014, 1, 1));
/// assert_eq!(from_ymd(2014, 1, 1) - Duration::seconds(86399), from_ymd(2014, 1, 1));
/// assert_eq!(from_ymd(2014, 1, 1) - Duration::seconds(-86399), from_ymd(2014, 1, 1));
/// assert_eq!(from_ymd(2014, 1, 1) - Duration::days(1), from_ymd(2013, 12, 31));
/// assert_eq!(from_ymd(2014, 1, 1) - Duration::days(-1), from_ymd(2014, 1, 2));
/// assert_eq!(from_ymd(2014, 1, 1) - Duration::days(364), from_ymd(2013, 1, 2));
/// assert_eq!(from_ymd(2014, 1, 1) - Duration::days(365*4 + 1), from_ymd(2010, 1, 1));
/// assert_eq!(from_ymd(2014, 1, 1) - Duration::days(365*400 + 97), from_ymd(1614, 1, 1));
/// # }
/// ~~~~
impl Sub<OldDuration> for NaiveDate {
type Output = NaiveDate;
#[inline]
fn sub(self, rhs: OldDuration) -> NaiveDate {
self.checked_sub_signed(rhs).expect("`NaiveDate - Duration` overflowed")
}
}
impl SubAssign<OldDuration> for NaiveDate {
#[inline]
fn sub_assign(&mut self, rhs: OldDuration) {
*self = self.sub(rhs);
}
}
/// Subtracts another `NaiveDate` from the current date.
/// Returns a `Duration` of integral numbers.
///
/// This does not overflow or underflow at all,
/// as all possible output fits in the range of `Duration`.
///
/// The implementation is a wrapper around
/// [`NaiveDate::signed_duration_since`](#method.signed_duration_since).
///
/// # Example
///
/// ~~~~
/// # extern crate chrono; fn main() {
/// use chrono::{NaiveDate, Duration};
///
/// let from_ymd = NaiveDate::from_ymd;
///
/// assert_eq!(from_ymd(2014, 1, 1) - from_ymd(2014, 1, 1), Duration::zero());
/// assert_eq!(from_ymd(2014, 1, 1) - from_ymd(2013, 12, 31), Duration::days(1));
/// assert_eq!(from_ymd(2014, 1, 1) - from_ymd(2014, 1, 2), Duration::days(-1));
/// assert_eq!(from_ymd(2014, 1, 1) - from_ymd(2013, 9, 23), Duration::days(100));
/// assert_eq!(from_ymd(2014, 1, 1) - from_ymd(2013, 1, 1), Duration::days(365));
/// assert_eq!(from_ymd(2014, 1, 1) - from_ymd(2010, 1, 1), Duration::days(365*4 + 1));
/// assert_eq!(from_ymd(2014, 1, 1) - from_ymd(1614, 1, 1), Duration::days(365*400 + 97));
/// # }
/// ~~~~
impl Sub<NaiveDate> for NaiveDate {
type Output = OldDuration;
#[inline]
fn sub(self, rhs: NaiveDate) -> OldDuration {
self.signed_duration_since(rhs)
}
}
/// The `Debug` output of the naive date `d` is same to
/// [`d.format("%Y-%m-%d")`](../format/strftime/index.html).
///
/// The string printed can be readily parsed via the `parse` method on `str`.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// assert_eq!(format!("{:?}", NaiveDate::from_ymd(2015, 9, 5)), "2015-09-05");
/// assert_eq!(format!("{:?}", NaiveDate::from_ymd( 0, 1, 1)), "0000-01-01");
/// assert_eq!(format!("{:?}", NaiveDate::from_ymd(9999, 12, 31)), "9999-12-31");
/// ~~~~
///
/// ISO 8601 requires an explicit sign for years before 1 BCE or after 9999 CE.
///
/// ~~~~
/// # use chrono::NaiveDate;
/// assert_eq!(format!("{:?}", NaiveDate::from_ymd( -1, 1, 1)), "-0001-01-01");
/// assert_eq!(format!("{:?}", NaiveDate::from_ymd(10000, 12, 31)), "+10000-12-31");
/// ~~~~
impl fmt::Debug for NaiveDate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let year = self.year();
let mdf = self.mdf();
if 0 <= year && year <= 9999 {
write!(f, "{:04}-{:02}-{:02}", year, mdf.month(), mdf.day())
} else {
// ISO 8601 requires the explicit sign for out-of-range years
write!(f, "{:+05}-{:02}-{:02}", year, mdf.month(), mdf.day())
}
}
}
/// The `Display` output of the naive date `d` is same to
/// [`d.format("%Y-%m-%d")`](../format/strftime/index.html).
///
/// The string printed can be readily parsed via the `parse` method on `str`.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// assert_eq!(format!("{}", NaiveDate::from_ymd(2015, 9, 5)), "2015-09-05");
/// assert_eq!(format!("{}", NaiveDate::from_ymd( 0, 1, 1)), "0000-01-01");
/// assert_eq!(format!("{}", NaiveDate::from_ymd(9999, 12, 31)), "9999-12-31");
/// ~~~~
///
/// ISO 8601 requires an explicit sign for years before 1 BCE or after 9999 CE.
///
/// ~~~~
/// # use chrono::NaiveDate;
/// assert_eq!(format!("{}", NaiveDate::from_ymd( -1, 1, 1)), "-0001-01-01");
/// assert_eq!(format!("{}", NaiveDate::from_ymd(10000, 12, 31)), "+10000-12-31");
/// ~~~~
impl fmt::Display for NaiveDate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) }
}
/// Parsing a `str` into a `NaiveDate` uses the same format,
/// [`%Y-%m-%d`](../format/strftime/index.html), as in `Debug` and `Display`.
///
/// # Example
///
/// ~~~~
/// use chrono::NaiveDate;
///
/// let d = NaiveDate::from_ymd(2015, 9, 18);
/// assert_eq!("2015-09-18".parse::<NaiveDate>(), Ok(d));
///
/// let d = NaiveDate::from_ymd(12345, 6, 7);
/// assert_eq!("+12345-6-7".parse::<NaiveDate>(), Ok(d));
///
/// assert!("foo".parse::<NaiveDate>().is_err());
/// ~~~~
impl str::FromStr for NaiveDate {
type Err = ParseError;
fn from_str(s: &str) -> ParseResult<NaiveDate> {
const ITEMS: &'static [Item<'static>] = &[
Item::Numeric(Numeric::Year, Pad::Zero),
Item::Space(""), Item::Literal("-"),
Item::Numeric(Numeric::Month, Pad::Zero),
Item::Space(""), Item::Literal("-"),
Item::Numeric(Numeric::Day, Pad::Zero),
Item::Space(""),
];
let mut parsed = Parsed::new();
parse(&mut parsed, s, ITEMS.iter())?;
parsed.to_naive_date()
}
}
#[cfg(all(test, any(feature = "rustc-serialize", feature = "serde")))]
fn test_encodable_json<F, E>(to_string: F)
where F: Fn(&NaiveDate) -> Result<String, E>, E: ::std::fmt::Debug
{
assert_eq!(to_string(&NaiveDate::from_ymd(2014, 7, 24)).ok(),
Some(r#""2014-07-24""#.into()));
assert_eq!(to_string(&NaiveDate::from_ymd(0, 1, 1)).ok(),
Some(r#""0000-01-01""#.into()));
assert_eq!(to_string(&NaiveDate::from_ymd(-1, 12, 31)).ok(),
Some(r#""-0001-12-31""#.into()));
assert_eq!(to_string(&MIN_DATE).ok(),
Some(r#""-262144-01-01""#.into()));
assert_eq!(to_string(&MAX_DATE).ok(),
Some(r#""+262143-12-31""#.into()));
}
#[cfg(all(test, any(feature = "rustc-serialize", feature = "serde")))]
fn test_decodable_json<F, E>(from_str: F)
where F: Fn(&str) -> Result<NaiveDate, E>, E: ::std::fmt::Debug
{
use std::{i32, i64};
assert_eq!(from_str(r#""2016-07-08""#).ok(), Some(NaiveDate::from_ymd(2016, 7, 8)));
assert_eq!(from_str(r#""2016-7-8""#).ok(), Some(NaiveDate::from_ymd(2016, 7, 8)));
assert_eq!(from_str(r#""+002016-07-08""#).ok(), Some(NaiveDate::from_ymd(2016, 7, 8)));
assert_eq!(from_str(r#""0000-01-01""#).ok(), Some(NaiveDate::from_ymd(0, 1, 1)));
assert_eq!(from_str(r#""0-1-1""#).ok(), Some(NaiveDate::from_ymd(0, 1, 1)));
assert_eq!(from_str(r#""-0001-12-31""#).ok(), Some(NaiveDate::from_ymd(-1, 12, 31)));
assert_eq!(from_str(r#""-262144-01-01""#).ok(), Some(MIN_DATE));
assert_eq!(from_str(r#""+262143-12-31""#).ok(), Some(MAX_DATE));
// bad formats
assert!(from_str(r#""""#).is_err());
assert!(from_str(r#""20001231""#).is_err());
assert!(from_str(r#""2000-00-00""#).is_err());
assert!(from_str(r#""2000-02-30""#).is_err());
assert!(from_str(r#""2001-02-29""#).is_err());
assert!(from_str(r#""2002-002-28""#).is_err());
assert!(from_str(r#""yyyy-mm-dd""#).is_err());
assert!(from_str(r#"0"#).is_err());
assert!(from_str(r#"20.01"#).is_err());
assert!(from_str(&i32::MIN.to_string()).is_err());
assert!(from_str(&i32::MAX.to_string()).is_err());
assert!(from_str(&i64::MIN.to_string()).is_err());
assert!(from_str(&i64::MAX.to_string()).is_err());
assert!(from_str(r#"{}"#).is_err());
// pre-0.3.0 rustc-serialize format is now invalid
assert!(from_str(r#"{"ymdf":20}"#).is_err());
assert!(from_str(r#"null"#).is_err());
}
#[cfg(feature = "rustc-serialize")]
mod rustc_serialize {
use super::NaiveDate;
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
impl Encodable for NaiveDate {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
format!("{:?}", self).encode(s)
}
}
impl Decodable for NaiveDate {
fn decode<D: Decoder>(d: &mut D) -> Result<NaiveDate, D::Error> {
d.read_str()?.parse().map_err(|_| d.error("invalid date"))
}
}
#[cfg(test)] use rustc_serialize::json;
#[test]
fn test_encodable() {
super::test_encodable_json(json::encode);
}
#[test]
fn test_decodable() {
super::test_decodable_json(json::decode);
}
}
#[cfg(feature = "serde")]
mod serde {
use core::fmt;
use super::NaiveDate;
use serdelib::{ser, de};
// TODO not very optimized for space (binary formats would want something better)
impl ser::Serialize for NaiveDate {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer
{
struct FormatWrapped<'a, D: 'a> {
inner: &'a D
}
impl<'a, D: fmt::Debug> fmt::Display for FormatWrapped<'a, D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
serializer.collect_str(&FormatWrapped { inner: &self })
}
}
struct NaiveDateVisitor;
impl<'de> de::Visitor<'de> for NaiveDateVisitor {
type Value = NaiveDate;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result
{
write!(formatter, "a formatted date string")
}
#[cfg(any(feature = "std", test))]
fn visit_str<E>(self, value: &str) -> Result<NaiveDate, E>
where E: de::Error
{
value.parse().map_err(E::custom)
}
#[cfg(not(any(feature = "std", test)))]
fn visit_str<E>(self, value: &str) -> Result<NaiveDate, E>
where E: de::Error
{
value.parse().map_err(E::custom)
}
}
impl<'de> de::Deserialize<'de> for NaiveDate {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: de::Deserializer<'de>
{
deserializer.deserialize_str(NaiveDateVisitor)
}
}
#[cfg(test)] extern crate serde_json;
#[cfg(test)] extern crate bincode;
#[test]
fn test_serde_serialize() {
super::test_encodable_json(self::serde_json::to_string);
}
#[test]
fn test_serde_deserialize() {
super::test_decodable_json(|input| self::serde_json::from_str(&input));
}
#[test]
fn test_serde_bincode() {
// Bincode is relevant to test separately from JSON because
// it is not self-describing.
use self::bincode::{Infinite, serialize, deserialize};
let d = NaiveDate::from_ymd(2014, 7, 24);
let encoded = serialize(&d, Infinite).unwrap();
let decoded: NaiveDate = deserialize(&encoded).unwrap();
assert_eq!(d, decoded);
}
}
#[cfg(test)]
mod tests {
use super::NaiveDate;
use super::{MIN_DATE, MIN_YEAR, MIN_DAYS_FROM_YEAR_0};
use super::{MAX_DATE, MAX_YEAR, MAX_DAYS_FROM_YEAR_0};
use {Datelike, Weekday};
use std::{i32, u32};
use oldtime::Duration;
#[test]
fn test_date_from_ymd() {
let ymd_opt = |y,m,d| NaiveDate::from_ymd_opt(y, m, d);
assert!(ymd_opt(2012, 0, 1).is_none());
assert!(ymd_opt(2012, 1, 1).is_some());
assert!(ymd_opt(2012, 2, 29).is_some());
assert!(ymd_opt(2014, 2, 29).is_none());
assert!(ymd_opt(2014, 3, 0).is_none());
assert!(ymd_opt(2014, 3, 1).is_some());
assert!(ymd_opt(2014, 3, 31).is_some());
assert!(ymd_opt(2014, 3, 32).is_none());
assert!(ymd_opt(2014, 12, 31).is_some());
assert!(ymd_opt(2014, 13, 1).is_none());
}
#[test]
fn test_date_from_yo() {
let yo_opt = |y,o| NaiveDate::from_yo_opt(y, o);
let ymd = |y,m,d| NaiveDate::from_ymd(y, m, d);
assert_eq!(yo_opt(2012, 0), None);
assert_eq!(yo_opt(2012, 1), Some(ymd(2012, 1, 1)));
assert_eq!(yo_opt(2012, 2), Some(ymd(2012, 1, 2)));
assert_eq!(yo_opt(2012, 32), Some(ymd(2012, 2, 1)));
assert_eq!(yo_opt(2012, 60), Some(ymd(2012, 2, 29)));
assert_eq!(yo_opt(2012, 61), Some(ymd(2012, 3, 1)));
assert_eq!(yo_opt(2012, 100), Some(ymd(2012, 4, 9)));
assert_eq!(yo_opt(2012, 200), Some(ymd(2012, 7, 18)));
assert_eq!(yo_opt(2012, 300), Some(ymd(2012, 10, 26)));
assert_eq!(yo_opt(2012, 366), Some(ymd(2012, 12, 31)));
assert_eq!(yo_opt(2012, 367), None);
assert_eq!(yo_opt(2014, 0), None);
assert_eq!(yo_opt(2014, 1), Some(ymd(2014, 1, 1)));
assert_eq!(yo_opt(2014, 2), Some(ymd(2014, 1, 2)));
assert_eq!(yo_opt(2014, 32), Some(ymd(2014, 2, 1)));
assert_eq!(yo_opt(2014, 59), Some(ymd(2014, 2, 28)));
assert_eq!(yo_opt(2014, 60), Some(ymd(2014, 3, 1)));
assert_eq!(yo_opt(2014, 100), Some(ymd(2014, 4, 10)));
assert_eq!(yo_opt(2014, 200), Some(ymd(2014, 7, 19)));
assert_eq!(yo_opt(2014, 300), Some(ymd(2014, 10, 27)));
assert_eq!(yo_opt(2014, 365), Some(ymd(2014, 12, 31)));
assert_eq!(yo_opt(2014, 366), None);
}
#[test]
fn test_date_from_isoywd() {
let isoywd_opt = |y,w,d| NaiveDate::from_isoywd_opt(y, w, d);
let ymd = |y,m,d| NaiveDate::from_ymd(y, m, d);
assert_eq!(isoywd_opt(2004, 0, Weekday::Sun), None);
assert_eq!(isoywd_opt(2004, 1, Weekday::Mon), Some(ymd(2003, 12, 29)));
assert_eq!(isoywd_opt(2004, 1, Weekday::Sun), Some(ymd(2004, 1, 4)));
assert_eq!(isoywd_opt(2004, 2, Weekday::Mon), Some(ymd(2004, 1, 5)));
assert_eq!(isoywd_opt(2004, 2, Weekday::Sun), Some(ymd(2004, 1, 11)));
assert_eq!(isoywd_opt(2004, 52, Weekday::Mon), Some(ymd(2004, 12, 20)));
assert_eq!(isoywd_opt(2004, 52, Weekday::Sun), Some(ymd(2004, 12, 26)));
assert_eq!(isoywd_opt(2004, 53, Weekday::Mon), Some(ymd(2004, 12, 27)));
assert_eq!(isoywd_opt(2004, 53, Weekday::Sun), Some(ymd(2005, 1, 2)));
assert_eq!(isoywd_opt(2004, 54, Weekday::Mon), None);
assert_eq!(isoywd_opt(2011, 0, Weekday::Sun), None);
assert_eq!(isoywd_opt(2011, 1, Weekday::Mon), Some(ymd(2011, 1, 3)));
assert_eq!(isoywd_opt(2011, 1, Weekday::Sun), Some(ymd(2011, 1, 9)));
assert_eq!(isoywd_opt(2011, 2, Weekday::Mon), Some(ymd(2011, 1, 10)));
assert_eq!(isoywd_opt(2011, 2, Weekday::Sun), Some(ymd(2011, 1, 16)));
assert_eq!(isoywd_opt(2018, 51, Weekday::Mon), Some(ymd(2018, 12, 17)));
assert_eq!(isoywd_opt(2018, 51, Weekday::Sun), Some(ymd(2018, 12, 23)));
assert_eq!(isoywd_opt(2018, 52, Weekday::Mon), Some(ymd(2018, 12, 24)));
assert_eq!(isoywd_opt(2018, 52, Weekday::Sun), Some(ymd(2018, 12, 30)));
assert_eq!(isoywd_opt(2018, 53, Weekday::Mon), None);
}
#[test]
fn test_date_from_isoywd_and_iso_week() {
for year in 2000..2401 {
for week in 1..54 {
for &weekday in [Weekday::Mon, Weekday::Tue, Weekday::Wed, Weekday::Thu,
Weekday::Fri, Weekday::Sat, Weekday::Sun].iter() {
let d = NaiveDate::from_isoywd_opt(year, week, weekday);
if d.is_some() {
let d = d.unwrap();
assert_eq!(d.weekday(), weekday);
let w = d.iso_week();
assert_eq!(w.year(), year);
assert_eq!(w.week(), week);
}
}
}
}
for year in 2000..2401 {
for month in 1..13 {
for day in 1..32 {
let d = NaiveDate::from_ymd_opt(year, month, day);
if d.is_some() {
let d = d.unwrap();
let w = d.iso_week();
let d_ = NaiveDate::from_isoywd(w.year(), w.week(), d.weekday());
assert_eq!(d, d_);
}
}
}
}
}
#[test]
fn test_date_from_num_days_from_ce() {
let from_ndays_from_ce = |days| NaiveDate::from_num_days_from_ce_opt(days);
assert_eq!(from_ndays_from_ce(1), Some(NaiveDate::from_ymd(1, 1, 1)));
assert_eq!(from_ndays_from_ce(2), Some(NaiveDate::from_ymd(1, 1, 2)));
assert_eq!(from_ndays_from_ce(31), Some(NaiveDate::from_ymd(1, 1, 31)));
assert_eq!(from_ndays_from_ce(32), Some(NaiveDate::from_ymd(1, 2, 1)));
assert_eq!(from_ndays_from_ce(59), Some(NaiveDate::from_ymd(1, 2, 28)));
assert_eq!(from_ndays_from_ce(60), Some(NaiveDate::from_ymd(1, 3, 1)));
assert_eq!(from_ndays_from_ce(365), Some(NaiveDate::from_ymd(1, 12, 31)));
assert_eq!(from_ndays_from_ce(365*1 + 1), Some(NaiveDate::from_ymd(2, 1, 1)));
assert_eq!(from_ndays_from_ce(365*2 + 1), Some(NaiveDate::from_ymd(3, 1, 1)));
assert_eq!(from_ndays_from_ce(365*3 + 1), Some(NaiveDate::from_ymd(4, 1, 1)));
assert_eq!(from_ndays_from_ce(365*4 + 2), Some(NaiveDate::from_ymd(5, 1, 1)));
assert_eq!(from_ndays_from_ce(146097 + 1), Some(NaiveDate::from_ymd(401, 1, 1)));
assert_eq!(from_ndays_from_ce(146097*5 + 1), Some(NaiveDate::from_ymd(2001, 1, 1)));
assert_eq!(from_ndays_from_ce(719163), Some(NaiveDate::from_ymd(1970, 1, 1)));
assert_eq!(from_ndays_from_ce(0), Some(NaiveDate::from_ymd(0, 12, 31))); // 1 BCE
assert_eq!(from_ndays_from_ce(-365), Some(NaiveDate::from_ymd(0, 1, 1)));
assert_eq!(from_ndays_from_ce(-366), Some(NaiveDate::from_ymd(-1, 12, 31))); // 2 BCE
for days in (-9999..10001).map(|x| x * 100) {
assert_eq!(from_ndays_from_ce(days).map(|d| d.num_days_from_ce()), Some(days));
}
assert_eq!(from_ndays_from_ce(MIN_DATE.num_days_from_ce()), Some(MIN_DATE));
assert_eq!(from_ndays_from_ce(MIN_DATE.num_days_from_ce() - 1), None);
assert_eq!(from_ndays_from_ce(MAX_DATE.num_days_from_ce()), Some(MAX_DATE));
assert_eq!(from_ndays_from_ce(MAX_DATE.num_days_from_ce() + 1), None);
}
#[test]
fn test_date_from_weekday_of_month_opt() { | let ymwd = |y,m,w,n| NaiveDate::from_weekday_of_month_opt(y,m,w,n);
assert_eq!(ymwd(2018, 8, Weekday::Tue, 0), None);
assert_eq!(ymwd(2018, 8, Weekday::Wed, 1), Some(NaiveDate::from_ymd(2018, 8, 1)));
assert_eq!(ymwd(2018, 8, Weekday::Thu, 1), Some(NaiveDate::from_ymd(2018, 8, 2)));
assert_eq!(ymwd(2018, 8, Weekday::Sun, 1), Some(NaiveDate::from_ymd(2018, 8, 5)));
assert_eq!(ymwd(2018, 8, Weekday::Mon, 1), Some(NaiveDate::from_ymd(2018, 8, 6)));
assert_eq!(ymwd(2018, 8, Weekday::Tue, 1), Some(NaiveDate::from_ymd(2018, 8, 7)));
assert_eq!(ymwd(2018, 8, Weekday::Wed, 2), Some(NaiveDate::from_ymd(2018, 8, 8)));
assert_eq!(ymwd(2018, 8, Weekday::Sun, 2), Some(NaiveDate::from_ymd(2018, 8, 12)));
assert_eq!(ymwd(2018, 8, Weekday::Thu, 3), Some(NaiveDate::from_ymd(2018, 8, 16)));
assert_eq!(ymwd(2018, 8, Weekday::Thu, 4), Some(NaiveDate::from_ymd(2018, 8, 23)));
assert_eq!(ymwd(2018, 8, Weekday::Thu, 5), Some(NaiveDate::from_ymd(2018, 8, 30)));
assert_eq!(ymwd(2018, 8, Weekday::Fri, 5), Some(NaiveDate::from_ymd(2018, 8, 31)));
assert_eq!(ymwd(2018, 8, Weekday::Sat, 5), None);
}
#[test]
fn test_date_fields() {
fn check(year: i32, month: u32, day: u32, ordinal: u32) {
let d1 = NaiveDate::from_ymd(year, month, day);
assert_eq!(d1.year(), year);
assert_eq!(d1.month(), month);
assert_eq!(d1.day(), day);
assert_eq!(d1.ordinal(), ordinal);
let d2 = NaiveDate::from_yo(year, ordinal);
assert_eq!(d2.year(), year);
assert_eq!(d2.month(), month);
assert_eq!(d2.day(), day);
assert_eq!(d2.ordinal(), ordinal);
assert_eq!(d1, d2);
}
check(2012, 1, 1, 1);
check(2012, 1, 2, 2);
check(2012, 2, 1, 32);
check(2012, 2, 29, 60);
check(2012, 3, 1, 61);
check(2012, 4, 9, 100);
check(2012, 7, 18, 200);
check(2012, 10, 26, 300);
check(2012, 12, 31, 366);
check(2014, 1, 1, 1);
check(2014, 1, 2, 2);
check(2014, 2, 1, 32);
check(2014, 2, 28, 59);
check(2014, 3, 1, 60);
check(2014, 4, 10, 100);
check(2014, 7, 19, 200);
check(2014, 10, 27, 300);
check(2014, 12, 31, 365);
}
#[test]
fn test_date_weekday() {
assert_eq!(NaiveDate::from_ymd(1582, 10, 15).weekday(), Weekday::Fri);
// May 20, 1875 = ISO 8601 reference date
assert_eq!(NaiveDate::from_ymd(1875, 5, 20).weekday(), Weekday::Thu);
assert_eq!(NaiveDate::from_ymd(2000, 1, 1).weekday(), Weekday::Sat);
}
#[test]
fn test_date_with_fields() {
let d = NaiveDate::from_ymd(2000, 2, 29);
assert_eq!(d.with_year(-400), Some(NaiveDate::from_ymd(-400, 2, 29)));
assert_eq!(d.with_year(-100), None);
assert_eq!(d.with_year(1600), Some(NaiveDate::from_ymd(1600, 2, 29)));
assert_eq!(d.with_year(1900), None);
assert_eq!(d.with_year(2000), Some(NaiveDate::from_ymd(2000, 2, 29)));
assert_eq!(d.with_year(2001), None);
assert_eq!(d.with_year(2004), Some(NaiveDate::from_ymd(2004, 2, 29)));
assert_eq!(d.with_year(i32::MAX), None);
let d = NaiveDate::from_ymd(2000, 4, 30);
assert_eq!(d.with_month(0), None);
assert_eq!(d.with_month(1), Some(NaiveDate::from_ymd(2000, 1, 30)));
assert_eq!(d.with_month(2), None);
assert_eq!(d.with_month(3), Some(NaiveDate::from_ymd(2000, 3, 30)));
assert_eq!(d.with_month(4), Some(NaiveDate::from_ymd(2000, 4, 30)));
assert_eq!(d.with_month(12), Some(NaiveDate::from_ymd(2000, 12, 30)));
assert_eq!(d.with_month(13), None);
assert_eq!(d.with_month(u32::MAX), None);
let d = NaiveDate::from_ymd(2000, 2, 8);
assert_eq!(d.with_day(0), None);
assert_eq!(d.with_day(1), Some(NaiveDate::from_ymd(2000, 2, 1)));
assert_eq!(d.with_day(29), Some(NaiveDate::from_ymd(2000, 2, 29)));
assert_eq!(d.with_day(30), None);
assert_eq!(d.with_day(u32::MAX), None);
let d = NaiveDate::from_ymd(2000, 5, 5);
assert_eq!(d.with_ordinal(0), None);
assert_eq!(d.with_ordinal(1), Some(NaiveDate::from_ymd(2000, 1, 1)));
assert_eq!(d.with_ordinal(60), Some(NaiveDate::from_ymd(2000, 2, 29)));
assert_eq!(d.with_ordinal(61), Some(NaiveDate::from_ymd(2000, 3, 1)));
assert_eq!(d.with_ordinal(366), Some(NaiveDate::from_ymd(2000, 12, 31)));
assert_eq!(d.with_ordinal(367), None);
assert_eq!(d.with_ordinal(u32::MAX), None);
}
#[test]
fn test_date_num_days_from_ce() {
assert_eq!(NaiveDate::from_ymd(1, 1, 1).num_days_from_ce(), 1);
for year in -9999..10001 {
assert_eq!(NaiveDate::from_ymd(year, 1, 1).num_days_from_ce(),
NaiveDate::from_ymd(year - 1, 12, 31).num_days_from_ce() + 1);
}
}
#[test]
fn test_date_succ() {
let ymd = |y,m,d| NaiveDate::from_ymd(y, m, d);
assert_eq!(ymd(2014, 5, 6).succ_opt(), Some(ymd(2014, 5, 7)));
assert_eq!(ymd(2014, 5, 31).succ_opt(), Some(ymd(2014, 6, 1)));
assert_eq!(ymd(2014, 12, 31).succ_opt(), Some(ymd(2015, 1, 1)));
assert_eq!(ymd(2016, 2, 28).succ_opt(), Some(ymd(2016, 2, 29)));
assert_eq!(ymd(MAX_DATE.year(), 12, 31).succ_opt(), None);
}
#[test]
fn test_date_pred() {
let ymd = |y,m,d| NaiveDate::from_ymd(y, m, d);
assert_eq!(ymd(2016, 3, 1).pred_opt(), Some(ymd(2016, 2, 29)));
assert_eq!(ymd(2015, 1, 1).pred_opt(), Some(ymd(2014, 12, 31)));
assert_eq!(ymd(2014, 6, 1).pred_opt(), Some(ymd(2014, 5, 31)));
assert_eq!(ymd(2014, 5, 7).pred_opt(), Some(ymd(2014, 5, 6)));
assert_eq!(ymd(MIN_DATE.year(), 1, 1).pred_opt(), None);
}
#[test]
fn test_date_add() {
fn check((y1,m1,d1): (i32, u32, u32), rhs: Duration, ymd: Option<(i32, u32, u32)>) {
let lhs = NaiveDate::from_ymd(y1, m1, d1);
let sum = ymd.map(|(y,m,d)| NaiveDate::from_ymd(y, m, d));
assert_eq!(lhs.checked_add_signed(rhs), sum);
assert_eq!(lhs.checked_sub_signed(-rhs), sum);
}
check((2014, 1, 1), Duration::zero(), Some((2014, 1, 1)));
check((2014, 1, 1), Duration::seconds(86399), Some((2014, 1, 1)));
// always round towards zero
check((2014, 1, 1), Duration::seconds(-86399), Some((2014, 1, 1)));
check((2014, 1, 1), Duration::days(1), Some((2014, 1, 2)));
check((2014, 1, 1), Duration::days(-1), Some((2013, 12, 31)));
check((2014, 1, 1), Duration::days(364), Some((2014, 12, 31)));
check((2014, 1, 1), Duration::days(365*4 + 1), Some((2018, 1, 1)));
check((2014, 1, 1), Duration::days(365*400 + 97), Some((2414, 1, 1)));
check((-7, 1, 1), Duration::days(365*12 + 3), Some((5, 1, 1)));
// overflow check
check((0, 1, 1), Duration::days(MAX_DAYS_FROM_YEAR_0 as i64), Some((MAX_YEAR, 12, 31)));
check((0, 1, 1), Duration::days(MAX_DAYS_FROM_YEAR_0 as i64 + 1), None);
check((0, 1, 1), Duration::max_value(), None);
check((0, 1, 1), Duration::days(MIN_DAYS_FROM_YEAR_0 as i64), Some((MIN_YEAR, 1, 1)));
check((0, 1, 1), Duration::days(MIN_DAYS_FROM_YEAR_0 as i64 - 1), None);
check((0, 1, 1), Duration::min_value(), None);
}
#[test]
fn test_date_sub() {
fn check((y1,m1,d1): (i32, u32, u32), (y2,m2,d2): (i32, u32, u32), diff: Duration) {
let lhs = NaiveDate::from_ymd(y1, m1, d1);
let rhs = NaiveDate::from_ymd(y2, m2, d2);
assert_eq!(lhs.signed_duration_since(rhs), diff);
assert_eq!(rhs.signed_duration_since(lhs), -diff);
}
check((2014, 1, 1), (2014, 1, 1), Duration::zero());
check((2014, 1, 2), (2014, 1, 1), Duration::days(1));
check((2014, 12, 31), (2014, 1, 1), Duration::days(364));
check((2015, 1, 3), (2014, 1, 1), Duration::days(365 + 2));
check((2018, 1, 1), (2014, 1, 1), Duration::days(365*4 + 1));
check((2414, 1, 1), (2014, 1, 1), Duration::days(365*400 + 97));
check((MAX_YEAR, 12, 31), (0, 1, 1), Duration::days(MAX_DAYS_FROM_YEAR_0 as i64));
check((MIN_YEAR, 1, 1), (0, 1, 1), Duration::days(MIN_DAYS_FROM_YEAR_0 as i64));
}
#[test]
fn test_date_addassignment() {
let ymd = NaiveDate::from_ymd;
let mut date = ymd(2016, 10, 1);
date += Duration::days(10);
assert_eq!(date, ymd(2016, 10, 11));
date += Duration::days(30);
assert_eq!(date, ymd(2016, 11, 10));
}
#[test]
fn test_date_subassignment() {
let ymd = NaiveDate::from_ymd;
let mut date = ymd(2016, 10, 11);
date -= Duration::days(10);
assert_eq!(date, ymd(2016, 10, 1));
date -= Duration::days(2);
assert_eq!(date, ymd(2016, 9, 29));
}
#[test]
fn test_date_fmt() {
assert_eq!(format!("{:?}", NaiveDate::from_ymd(2012, 3, 4)), "2012-03-04");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(0, 3, 4)), "0000-03-04");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(-307, 3, 4)), "-0307-03-04");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(12345, 3, 4)), "+12345-03-04");
assert_eq!(NaiveDate::from_ymd(2012, 3, 4).to_string(), "2012-03-04");
assert_eq!(NaiveDate::from_ymd(0, 3, 4).to_string(), "0000-03-04");
assert_eq!(NaiveDate::from_ymd(-307, 3, 4).to_string(), "-0307-03-04");
assert_eq!(NaiveDate::from_ymd(12345, 3, 4).to_string(), "+12345-03-04");
// the format specifier should have no effect on `NaiveTime`
assert_eq!(format!("{:+30?}", NaiveDate::from_ymd(1234, 5, 6)), "1234-05-06");
assert_eq!(format!("{:30?}", NaiveDate::from_ymd(12345, 6, 7)), "+12345-06-07");
}
#[test]
fn test_date_from_str() {
// valid cases
let valid = [
"-0000000123456-1-2",
" -123456 - 1 - 2 ",
"-12345-1-2",
"-1234-12-31",
"-7-6-5",
"350-2-28",
"360-02-29",
"0360-02-29",
"2015-2 -18",
"+70-2-18",
"+70000-2-18",
"+00007-2-18",
];
for &s in &valid {
let d = match s.parse::<NaiveDate>() {
Ok(d) => d,
Err(e) => panic!("parsing `{}` has failed: {}", s, e)
};
let s_ = format!("{:?}", d);
// `s` and `s_` may differ, but `s.parse()` and `s_.parse()` must be same
let d_ = match s_.parse::<NaiveDate>() {
Ok(d) => d,
Err(e) => panic!("`{}` is parsed into `{:?}`, but reparsing that has failed: {}",
s, d, e)
};
assert!(d == d_, "`{}` is parsed into `{:?}`, but reparsed result \
`{:?}` does not match", s, d, d_);
}
// some invalid cases
// since `ParseErrorKind` is private, all we can do is to check if there was an error
assert!("".parse::<NaiveDate>().is_err());
assert!("x".parse::<NaiveDate>().is_err());
assert!("2014".parse::<NaiveDate>().is_err());
assert!("2014-01".parse::<NaiveDate>().is_err());
assert!("2014-01-00".parse::<NaiveDate>().is_err());
assert!("2014-13-57".parse::<NaiveDate>().is_err());
assert!("9999999-9-9".parse::<NaiveDate>().is_err()); // out-of-bounds
}
#[test]
fn test_date_parse_from_str() {
let ymd = |y,m,d| NaiveDate::from_ymd(y,m,d);
assert_eq!(NaiveDate::parse_from_str("2014-5-7T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
Ok(ymd(2014, 5, 7))); // ignore time and offset
assert_eq!(NaiveDate::parse_from_str("2015-W06-1=2015-033", "%G-W%V-%u = %Y-%j"),
Ok(ymd(2015, 2, 2)));
assert_eq!(NaiveDate::parse_from_str("Fri, 09 Aug 13", "%a, %d %b %y"),
Ok(ymd(2013, 8, 9)));
assert!(NaiveDate::parse_from_str("Sat, 09 Aug 2013", "%a, %d %b %Y").is_err());
assert!(NaiveDate::parse_from_str("2014-57", "%Y-%m-%d").is_err());
assert!(NaiveDate::parse_from_str("2014", "%Y").is_err()); // insufficient
}
#[test]
fn test_date_format() {
let d = NaiveDate::from_ymd(2012, 3, 4);
assert_eq!(d.format("%Y,%C,%y,%G,%g").to_string(), "2012,20,12,2012,12");
assert_eq!(d.format("%m,%b,%h,%B").to_string(), "03,Mar,Mar,March");
assert_eq!(d.format("%d,%e").to_string(), "04, 4");
assert_eq!(d.format("%U,%W,%V").to_string(), "10,09,09");
assert_eq!(d.format("%a,%A,%w,%u").to_string(), "Sun,Sunday,0,7");
assert_eq!(d.format("%j").to_string(), "064"); // since 2012 is a leap year
assert_eq!(d.format("%D,%x").to_string(), "03/04/12,03/04/12");
assert_eq!(d.format("%F").to_string(), "2012-03-04");
assert_eq!(d.format("%v").to_string(), " 4-Mar-2012");
assert_eq!(d.format("%t%n%%%n%t").to_string(), "\t\n%\n\t");
// non-four-digit years
assert_eq!(NaiveDate::from_ymd(12345, 1, 1).format("%Y").to_string(), "+12345");
assert_eq!(NaiveDate::from_ymd(1234, 1, 1).format("%Y").to_string(), "1234");
assert_eq!(NaiveDate::from_ymd(123, 1, 1).format("%Y").to_string(), "0123");
assert_eq!(NaiveDate::from_ymd(12, 1, 1).format("%Y").to_string(), "0012");
assert_eq!(NaiveDate::from_ymd(1, 1, 1).format("%Y").to_string(), "0001");
assert_eq!(NaiveDate::from_ymd(0, 1, 1).format("%Y").to_string(), "0000");
assert_eq!(NaiveDate::from_ymd(-1, 1, 1).format("%Y").to_string(), "-0001");
assert_eq!(NaiveDate::from_ymd(-12, 1, 1).format("%Y").to_string(), "-0012");
assert_eq!(NaiveDate::from_ymd(-123, 1, 1).format("%Y").to_string(), "-0123");
assert_eq!(NaiveDate::from_ymd(-1234, 1, 1).format("%Y").to_string(), "-1234");
assert_eq!(NaiveDate::from_ymd(-12345, 1, 1).format("%Y").to_string(), "-12345");
// corner cases
assert_eq!(NaiveDate::from_ymd(2007, 12, 31).format("%G,%g,%U,%W,%V").to_string(),
"2008,08,53,53,01");
assert_eq!(NaiveDate::from_ymd(2010, 1, 3).format("%G,%g,%U,%W,%V").to_string(),
"2009,09,01,00,53");
}
} | |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use log::LevelFilter;
use move_command_line_common::files::{extension_equals, find_filenames, MOVE_EXTENSION};
use move_lang::shared::NumericalAddress;
use std::{collections::BTreeMap, path::PathBuf};
#[cfg(test)]
mod tests;
pub mod utils;
pub mod natives;
const MODULES_DIR: &str = "sources";
const NURSERY_DIR: &str = "nursery";
const DOCS_DIR: &str = "docs";
const NURSERY_DOCS_DIR: &str = "nursery/docs";
const ERRMAP_FILE: &str = "error_description.errmap";
const REFERENCES_TEMPLATE: &str = "doc_templates/references.md";
const OVERVIEW_TEMPLATE: &str = "doc_templates/overview.md";
pub fn unit_testing_files() -> Vec<String> {
vec![path_in_crate("sources/UnitTest.move")]
.into_iter()
.map(|p| p.into_os_string().into_string().unwrap())
.collect()
}
pub fn path_in_crate<S>(relative: S) -> PathBuf
where
S: Into<String>,
{
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(relative.into());
path
}
pub fn move_stdlib_modules_full_path() -> String {
format!("{}/{}", env!("CARGO_MANIFEST_DIR"), MODULES_DIR)
}
pub fn move_stdlib_docs_full_path() -> String {
format!("{}/{}", env!("CARGO_MANIFEST_DIR"), DOCS_DIR)
}
pub fn move_nursery_docs_full_path() -> String {
format!("{}/{}", env!("CARGO_MANIFEST_DIR"), NURSERY_DOCS_DIR)
}
pub fn move_stdlib_errmap_full_path() -> String {
format!("{}/{}", env!("CARGO_MANIFEST_DIR"), ERRMAP_FILE)
}
pub fn move_stdlib_files() -> Vec<String> {
let path = path_in_crate(MODULES_DIR);
find_filenames(&[path], |p| extension_equals(p, MOVE_EXTENSION)).unwrap()
}
pub fn move_nursery_files() -> Vec<String> |
pub fn move_stdlib_named_addresses() -> BTreeMap<String, NumericalAddress> {
let mapping = [("Std", "0x1")];
mapping
.iter()
.map(|(name, addr)| (name.to_string(), NumericalAddress::parse_str(addr).unwrap()))
.collect()
}
pub fn build_doc(
output_path: &str,
doc_path: &str,
templates: Vec<String>,
references_file: Option<String>,
sources: &[String],
dep_paths: Vec<String>,
with_diagram: bool,
named_addresses: BTreeMap<String, NumericalAddress>,
) {
let options = move_prover::cli::Options {
move_sources: sources.to_vec(),
move_deps: dep_paths,
move_named_address_values: move_prover::cli::named_addresses_for_options(&named_addresses),
verbosity_level: LevelFilter::Warn,
run_docgen: true,
docgen: move_docgen::DocgenOptions {
root_doc_templates: templates,
references_file,
doc_path: vec![doc_path.to_string()],
output_directory: output_path.to_string(),
include_dep_diagrams: with_diagram,
include_call_diagrams: with_diagram,
..Default::default()
},
..Default::default()
};
options.setup_logging_for_test();
move_prover::run_move_prover_errors_to_stderr(options).unwrap();
}
pub fn build_stdlib_doc(output_path: &str) {
build_doc(
output_path,
"",
vec![path_in_crate(OVERVIEW_TEMPLATE)
.to_string_lossy()
.to_string()],
Some(
path_in_crate(REFERENCES_TEMPLATE)
.to_string_lossy()
.to_string(),
),
move_stdlib_files().as_slice(),
vec![],
false,
move_stdlib_named_addresses(),
)
}
pub fn build_nursery_doc(output_path: &str) {
build_doc(
output_path,
"",
vec![],
None,
move_nursery_files().as_slice(),
vec![move_stdlib_modules_full_path()],
false,
move_stdlib_named_addresses(),
)
}
pub fn build_error_code_map(output_path: &str) {
let options = move_prover::cli::Options {
move_sources: crate::move_stdlib_files(),
move_deps: vec![],
verbosity_level: LevelFilter::Warn,
run_errmapgen: true,
move_named_address_values: move_prover::cli::named_addresses_for_options(
&move_stdlib_named_addresses(),
),
errmapgen: move_errmapgen::ErrmapOptions {
output_file: output_path.to_string(),
..Default::default()
},
..Default::default()
};
options.setup_logging_for_test();
move_prover::run_move_prover_errors_to_stderr(options).unwrap();
}
const ERROR_DESCRIPTIONS: &[u8] = include_bytes!("../error_description.errmap");
pub fn error_descriptions() -> &'static [u8] {
ERROR_DESCRIPTIONS
}
| {
let path = path_in_crate(NURSERY_DIR);
find_filenames(&[path], |p| extension_equals(p, MOVE_EXTENSION)).unwrap()
} |
mutable.rs | use std::{iter::FromIterator, sync::Arc};
use crate::{
array::{specification::check_offsets, Array, MutableArray, Offset, TryExtend, TryPush},
bitmap::MutableBitmap,
buffer::MutableBuffer,
datatypes::DataType,
error::{ArrowError, Result},
trusted_len::TrustedLen,
};
use super::BinaryArray;
/// The Arrow's equivalent to `Vec<Option<Vec<u8>>>`.
/// Converting a [`MutableBinaryArray`] into a [`BinaryArray`] is `O(1)`.
/// # Implementation
/// This struct does not allocate a validity until one is required (i.e. push a null to it).
#[derive(Debug)]
pub struct MutableBinaryArray<O: Offset> {
data_type: DataType,
offsets: MutableBuffer<O>,
values: MutableBuffer<u8>,
validity: Option<MutableBitmap>,
}
impl<O: Offset> From<MutableBinaryArray<O>> for BinaryArray<O> {
fn from(other: MutableBinaryArray<O>) -> Self {
BinaryArray::<O>::from_data(
other.data_type,
other.offsets.into(),
other.values.into(),
other.validity.map(|x| x.into()),
)
}
}
impl<O: Offset> Default for MutableBinaryArray<O> {
fn default() -> Self {
Self::new()
}
}
impl<O: Offset> MutableBinaryArray<O> {
/// Creates a new empty [`MutableBinaryArray`].
/// # Implementation
/// This allocates a [`MutableBuffer`] of one element
pub fn new() -> Self {
Self::with_capacity(0)
}
/// The canonical method to create a [`MutableBinaryArray`] out of low-end APIs.
/// # Panics
/// This function panics iff:
/// * The `offsets` and `values` are inconsistent
/// * The validity is not `None` and its length is different from `offsets`'s length minus one.
pub fn from_data(
data_type: DataType,
offsets: MutableBuffer<O>,
values: MutableBuffer<u8>,
validity: Option<MutableBitmap>,
) -> Self {
check_offsets(&offsets, values.len());
if let Some(ref validity) = validity {
assert_eq!(offsets.len() - 1, validity.len());
}
if data_type.to_physical_type() != Self::default_data_type().to_physical_type() {
panic!("MutableBinaryArray can only be initialized with DataType::Binary or DataType::LargeBinary")
}
Self {
data_type,
offsets,
values,
validity,
}
}
fn default_data_type() -> DataType {
BinaryArray::<O>::default_data_type()
}
/// Creates a new [`MutableBinaryArray`] with capacity for `capacity` values.
/// # Implementation
/// This does not allocate the validity.
pub fn with_capacity(capacity: usize) -> Self {
let mut offsets = MutableBuffer::<O>::with_capacity(capacity + 1);
offsets.push(O::default());
Self {
data_type: BinaryArray::<O>::default_data_type(),
offsets,
values: MutableBuffer::<u8>::new(),
validity: None,
}
} | if let Some(x) = self.validity.as_mut() {
x.reserve(additional)
}
}
#[inline]
fn last_offset(&self) -> O {
*self.offsets.last().unwrap()
}
/// Pushes a new element to the array.
/// # Panic
/// This operation panics iff the length of all values (in bytes) exceeds `O` maximum value.
pub fn push<T: AsRef<[u8]>>(&mut self, value: Option<T>) {
self.try_push(value).unwrap()
}
fn try_from_iter<P: AsRef<[u8]>, I: IntoIterator<Item = Option<P>>>(iter: I) -> Result<Self> {
let iterator = iter.into_iter();
let (lower, _) = iterator.size_hint();
let mut primitive = Self::with_capacity(lower);
for item in iterator {
primitive.try_push(item.as_ref())?
}
Ok(primitive)
}
fn init_validity(&mut self) {
self.validity = Some(MutableBitmap::from_trusted_len_iter(
std::iter::repeat(true)
.take(self.len() - 1)
.chain(std::iter::once(false)),
))
}
/// Converts itself into an [`Array`].
pub fn into_arc(self) -> Arc<dyn Array> {
let a: BinaryArray<O> = self.into();
Arc::new(a)
}
/// Shrinks the capacity of the [`MutableBinaryArray`] to fit its current length.
pub fn shrink_to_fit(&mut self) {
self.values.shrink_to_fit();
self.offsets.shrink_to_fit();
if let Some(validity) = &mut self.validity {
validity.shrink_to_fit()
}
}
}
impl<O: Offset> MutableArray for MutableBinaryArray<O> {
fn len(&self) -> usize {
self.offsets.len() - 1
}
fn validity(&self) -> Option<&MutableBitmap> {
self.validity.as_ref()
}
fn as_box(&mut self) -> Box<dyn Array> {
Box::new(BinaryArray::from_data(
self.data_type.clone(),
std::mem::take(&mut self.offsets).into(),
std::mem::take(&mut self.values).into(),
std::mem::take(&mut self.validity).map(|x| x.into()),
))
}
fn as_arc(&mut self) -> Arc<dyn Array> {
Arc::new(BinaryArray::from_data(
self.data_type.clone(),
std::mem::take(&mut self.offsets).into(),
std::mem::take(&mut self.values).into(),
std::mem::take(&mut self.validity).map(|x| x.into()),
))
}
fn data_type(&self) -> &DataType {
&self.data_type
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
#[inline]
fn push_null(&mut self) {
self.push::<&[u8]>(None)
}
fn shrink_to_fit(&mut self) {
self.shrink_to_fit()
}
}
impl<O: Offset, P: AsRef<[u8]>> FromIterator<Option<P>> for MutableBinaryArray<O> {
fn from_iter<I: IntoIterator<Item = Option<P>>>(iter: I) -> Self {
Self::try_from_iter(iter).unwrap()
}
}
impl<O: Offset> MutableBinaryArray<O> {
/// Creates a [`MutableBinaryArray`] from an iterator of trusted length.
/// # Safety
/// The iterator must be [`TrustedLen`](https://doc.rust-lang.org/std/iter/trait.TrustedLen.html).
/// I.e. that `size_hint().1` correctly reports its length.
#[inline]
pub unsafe fn from_trusted_len_iter_unchecked<I, P>(iterator: I) -> Self
where
P: AsRef<[u8]>,
I: Iterator<Item = Option<P>>,
{
let (validity, offsets, values) = trusted_len_unzip(iterator);
Self::from_data(Self::default_data_type(), offsets, values, validity)
}
/// Creates a [`MutableBinaryArray`] from an iterator of trusted length.
#[inline]
pub fn from_trusted_len_iter<I, P>(iterator: I) -> Self
where
P: AsRef<[u8]>,
I: TrustedLen<Item = Option<P>>,
{
// soundness: I is `TrustedLen`
unsafe { Self::from_trusted_len_iter_unchecked(iterator) }
}
/// Creates a new [`BinaryArray`] from a [`TrustedLen`] of `&[u8]`.
#[inline]
pub fn from_trusted_len_values_iter<T: AsRef<[u8]>, I: TrustedLen<Item = T>>(
iterator: I,
) -> Self {
// soundness: I is `TrustedLen`
let (offsets, values) = unsafe { trusted_len_values_iter(iterator) };
Self::from_data(Self::default_data_type(), offsets, values, None)
}
/// Creates a [`MutableBinaryArray`] from an falible iterator of trusted length.
/// # Safety
/// The iterator must be [`TrustedLen`](https://doc.rust-lang.org/std/iter/trait.TrustedLen.html).
/// I.e. that `size_hint().1` correctly reports its length.
#[inline]
pub unsafe fn try_from_trusted_len_iter_unchecked<E, I, P>(
iterator: I,
) -> std::result::Result<Self, E>
where
P: AsRef<[u8]>,
I: IntoIterator<Item = std::result::Result<Option<P>, E>>,
{
let iterator = iterator.into_iter();
// soundness: assumed trusted len
let (validity, offsets, values) = try_trusted_len_unzip(iterator)?;
Ok(Self::from_data(
Self::default_data_type(),
offsets,
values,
validity,
))
}
/// Creates a [`MutableBinaryArray`] from an falible iterator of trusted length.
#[inline]
pub fn try_from_trusted_len_iter<E, I, P>(iterator: I) -> std::result::Result<Self, E>
where
P: AsRef<[u8]>,
I: TrustedLen<Item = std::result::Result<Option<P>, E>>,
{
// soundness: I: TrustedLen
unsafe { Self::try_from_trusted_len_iter_unchecked(iterator) }
}
/// Extends the [`MutableBinaryArray`] from an iterator of trusted length.
/// This differs from `extend_trusted_len` which accepts iterator of optional values.
#[inline]
pub fn extend_trusted_len_values<I, P>(&mut self, iterator: I)
where
P: AsRef<[u8]>,
I: TrustedLen<Item = P>,
{
// Safety: The iterator is `TrustedLen`
unsafe { self.extend_trusted_len_values_unchecked(iterator) }
}
/// Extends the [`MutableBinaryArray`] from an `iterator` of values of trusted length.
/// This differs from `extend_trusted_len_unchecked` which accepts iterator of optional
/// values.
/// # Safety
/// The `iterator` must be [`TrustedLen`]
#[inline]
pub unsafe fn extend_trusted_len_values_unchecked<I, P>(&mut self, iterator: I)
where
P: AsRef<[u8]>,
I: Iterator<Item = P>,
{
let (_, upper) = iterator.size_hint();
let additional = upper.expect("extend_trusted_len_values requires an upper limit");
extend_from_trusted_len_values_iter(&mut self.offsets, &mut self.values, iterator);
if let Some(validity) = self.validity.as_mut() {
validity.extend_constant(additional, true);
}
}
/// Extends the [`MutableBinaryArray`] from an iterator of [`TrustedLen`]
#[inline]
pub fn extend_trusted_len<I, P>(&mut self, iterator: I)
where
P: AsRef<[u8]>,
I: TrustedLen<Item = Option<P>>,
{
// Safety: The iterator is `TrustedLen`
unsafe { self.extend_trusted_len_unchecked(iterator) }
}
/// Extends the [`MutableBinaryArray`] from an iterator of [`TrustedLen`]
/// # Safety
/// The `iterator` must be [`TrustedLen`]
#[inline]
pub unsafe fn extend_trusted_len_unchecked<I, P>(&mut self, iterator: I)
where
P: AsRef<[u8]>,
I: Iterator<Item = Option<P>>,
{
if self.validity.is_none() {
let mut validity = MutableBitmap::new();
validity.extend_constant(self.len(), true);
self.validity = Some(validity);
}
extend_from_trusted_len_iter(
&mut self.offsets,
&mut self.values,
&mut self.validity.as_mut().unwrap(),
iterator,
);
if self.validity.as_mut().unwrap().null_count() == 0 {
self.validity = None;
}
}
/// Creates a new [`MutableBinaryArray`] from a [`Iterator`] of `&[u8]`.
pub fn from_iter_values<T: AsRef<[u8]>, I: Iterator<Item = T>>(iterator: I) -> Self {
let (offsets, values) = values_iter(iterator);
Self::from_data(Self::default_data_type(), offsets, values, None)
}
}
impl<O: Offset, T: AsRef<[u8]>> Extend<Option<T>> for MutableBinaryArray<O> {
fn extend<I: IntoIterator<Item = Option<T>>>(&mut self, iter: I) {
self.try_extend(iter).unwrap();
}
}
impl<O: Offset, T: AsRef<[u8]>> TryExtend<Option<T>> for MutableBinaryArray<O> {
fn try_extend<I: IntoIterator<Item = Option<T>>>(&mut self, iter: I) -> Result<()> {
let mut iter = iter.into_iter();
self.reserve(iter.size_hint().0);
iter.try_for_each(|x| self.try_push(x))
}
}
impl<O: Offset, T: AsRef<[u8]>> TryPush<Option<T>> for MutableBinaryArray<O> {
fn try_push(&mut self, value: Option<T>) -> Result<()> {
match value {
Some(value) => {
let bytes = value.as_ref();
let size = O::from_usize(self.values.len() + bytes.len())
.ok_or(ArrowError::KeyOverflowError)?;
self.values.extend_from_slice(bytes);
self.offsets.push(size);
match &mut self.validity {
Some(validity) => validity.push(true),
None => {}
}
}
None => {
self.offsets.push(self.last_offset());
match &mut self.validity {
Some(validity) => validity.push(false),
None => self.init_validity(),
}
}
}
Ok(())
}
}
/// Creates [`MutableBitmap`] and two [`MutableBuffer`]s from an iterator of `Option`.
/// The first buffer corresponds to a offset buffer, the second one
/// corresponds to a values buffer.
/// # Safety
/// The caller must ensure that `iterator` is `TrustedLen`.
#[inline]
unsafe fn trusted_len_unzip<O, I, P>(
iterator: I,
) -> (Option<MutableBitmap>, MutableBuffer<O>, MutableBuffer<u8>)
where
O: Offset,
P: AsRef<[u8]>,
I: Iterator<Item = Option<P>>,
{
let (_, upper) = iterator.size_hint();
let len = upper.expect("trusted_len_unzip requires an upper limit");
let mut offsets = MutableBuffer::<O>::with_capacity(len + 1);
let mut values = MutableBuffer::<u8>::new();
let mut validity = MutableBitmap::new();
offsets.push_unchecked(O::default());
extend_from_trusted_len_iter(&mut offsets, &mut values, &mut validity, iterator);
let validity = if validity.null_count() > 0 {
Some(validity)
} else {
None
};
(validity, offsets, values)
}
/// # Safety
/// The caller must ensure that `iterator` is `TrustedLen`.
#[inline]
#[allow(clippy::type_complexity)]
pub(crate) unsafe fn try_trusted_len_unzip<E, I, P, O>(
iterator: I,
) -> std::result::Result<(Option<MutableBitmap>, MutableBuffer<O>, MutableBuffer<u8>), E>
where
O: Offset,
P: AsRef<[u8]>,
I: Iterator<Item = std::result::Result<Option<P>, E>>,
{
let (_, upper) = iterator.size_hint();
let len = upper.expect("trusted_len_unzip requires an upper limit");
let mut null = MutableBitmap::with_capacity(len);
let mut offsets = MutableBuffer::<O>::with_capacity(len + 1);
let mut values = MutableBuffer::<u8>::new();
let mut length = O::default();
let mut dst = offsets.as_mut_ptr();
std::ptr::write(dst, length);
dst = dst.add(1);
for item in iterator {
if let Some(item) = item? {
null.push(true);
let s = item.as_ref();
length += O::from_usize(s.len()).unwrap();
values.extend_from_slice(s);
} else {
null.push(false);
};
std::ptr::write(dst, length);
dst = dst.add(1);
}
assert_eq!(
dst.offset_from(offsets.as_ptr()) as usize,
len + 1,
"Trusted iterator length was not accurately reported"
);
offsets.set_len(len + 1);
Ok((null.into(), offsets, values))
}
/// Creates two [`Buffer`]s from an iterator of `&[u8]`.
/// The first buffer corresponds to a offset buffer, the second to a values buffer.
/// # Safety
/// The caller must ensure that `iterator` is [`TrustedLen`].
#[inline]
pub(crate) unsafe fn trusted_len_values_iter<O, I, P>(
iterator: I,
) -> (MutableBuffer<O>, MutableBuffer<u8>)
where
O: Offset,
P: AsRef<[u8]>,
I: Iterator<Item = P>,
{
let (_, upper) = iterator.size_hint();
let len = upper.expect("trusted_len_unzip requires an upper limit");
let mut offsets = MutableBuffer::<O>::with_capacity(len + 1);
let mut values = MutableBuffer::<u8>::new();
offsets.push_unchecked(O::default());
extend_from_trusted_len_values_iter(&mut offsets, &mut values, iterator);
(offsets, values)
}
// Populates `offsets` and `values` [`MutableBuffer`]s with information extracted
// from the incoming `iterator`.
// # Safety
// The caller must ensure the `iterator` is [`TrustedLen`]
#[inline]
unsafe fn extend_from_trusted_len_values_iter<I, P, O>(
offsets: &mut MutableBuffer<O>,
values: &mut MutableBuffer<u8>,
iterator: I,
) where
O: Offset,
P: AsRef<[u8]>,
I: Iterator<Item = P>,
{
let (_, upper) = iterator.size_hint();
let additional = upper.expect("extend_from_trusted_len_values_iter requires an upper limit");
offsets.reserve(additional);
// Read in the last offset, will be used to increment and store
// new values later on
let mut length = *offsets.last().unwrap();
// Get a mutable pointer to the `offsets`, and move the pointer
// to the position, where a new value will be written
let mut dst = offsets.as_mut_ptr();
dst = dst.add(offsets.len());
for item in iterator {
let s = item.as_ref();
// Calculate the new offset value
length += O::from_usize(s.len()).unwrap();
// Push new entries for both `values` and `offsets` buffer
values.extend_from_slice(s);
std::ptr::write(dst, length);
// Move to the next position in offset buffer
dst = dst.add(1);
}
debug_assert_eq!(
dst.offset_from(offsets.as_ptr()) as usize,
offsets.len() + additional,
"TrustedLen iterator's length was not accurately reported"
);
// We make sure to set the new length for the `offsets` buffer
offsets.set_len(offsets.len() + additional);
}
// Populates `offsets`, `values`, and `validity` [`MutableBuffer`]s with
// information extracted from the incoming `iterator`.
//
// # Safety
// The caller must ensure that `iterator` is [`TrustedLen`]
#[inline]
unsafe fn extend_from_trusted_len_iter<O, I, P>(
offsets: &mut MutableBuffer<O>,
values: &mut MutableBuffer<u8>,
validity: &mut MutableBitmap,
iterator: I,
) where
O: Offset,
P: AsRef<[u8]>,
I: Iterator<Item = Option<P>>,
{
let (_, upper) = iterator.size_hint();
let additional = upper.expect("extend_from_trusted_len_iter requires an upper limit");
offsets.reserve(additional);
validity.reserve(additional);
// Read in the last offset, will be used to increment and store
// new values later on
let mut length = *offsets.last().unwrap();
// Get a mutable pointer to the `offsets`, and move the pointer
// to the position, where a new value will be written
let mut dst = offsets.as_mut_ptr();
dst = dst.add(offsets.len());
for item in iterator {
if let Some(item) = item {
let bytes = item.as_ref();
// Calculate new offset value
length += O::from_usize(bytes.len()).unwrap();
// Push new values for `values` and `validity` buffer
values.extend_from_slice(bytes);
validity.push_unchecked(true);
} else {
// If `None`, update only `validity`
validity.push_unchecked(false);
}
// Push new offset or old offset depending on the `item`
std::ptr::write(dst, length);
// Move to the next position in offset buffer
dst = dst.add(1);
}
debug_assert_eq!(
dst.offset_from(offsets.as_ptr()) as usize,
offsets.len() + additional,
"TrustedLen iterator's length was not accurately reported"
);
// We make sure to set the new length for the `offsets` buffer
offsets.set_len(offsets.len() + additional);
}
/// Creates two [`MutableBuffer`]s from an iterator of `&[u8]`.
/// The first buffer corresponds to a offset buffer, the second to a values buffer.
#[inline]
fn values_iter<O, I, P>(iterator: I) -> (MutableBuffer<O>, MutableBuffer<u8>)
where
O: Offset,
P: AsRef<[u8]>,
I: Iterator<Item = P>,
{
let (lower, _) = iterator.size_hint();
let mut offsets = MutableBuffer::<O>::with_capacity(lower + 1);
let mut values = MutableBuffer::<u8>::new();
let mut length = O::default();
offsets.push(length);
for item in iterator {
let s = item.as_ref();
length += O::from_usize(s.len()).unwrap();
values.extend_from_slice(s);
offsets.push(length)
}
(offsets, values)
} |
/// Reserves `additional` slots.
pub fn reserve(&mut self, additional: usize) {
self.offsets.reserve(additional); |
notification_test.go | // Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved.
// See License for license information.
package mscalendar
import (
"context"
"github.com/stretchr/testify/require"
"testing"
"github.com/golang/mock/gomock"
"golang.org/x/oauth2"
"github.com/mattermost/mattermost-plugin-mscalendar/server/config"
"github.com/mattermost/mattermost-plugin-mscalendar/server/mscalendar/mock_plugin_api"
"github.com/mattermost/mattermost-plugin-mscalendar/server/remote"
"github.com/mattermost/mattermost-plugin-mscalendar/server/remote/mock_remote"
"github.com/mattermost/mattermost-plugin-mscalendar/server/store"
"github.com/mattermost/mattermost-plugin-mscalendar/server/store/mock_store"
"github.com/mattermost/mattermost-plugin-mscalendar/server/utils/bot"
"github.com/mattermost/mattermost-plugin-mscalendar/server/utils/bot/mock_bot"
)
func newTestNotificationProcessor(env Env) NotificationProcessor {
processor := ¬ificationProcessor{
Env: env,
}
return processor
}
func newTestEvent(locationDisplayName string) *remote.Event {
return &remote.Event{
ID: "remote_event_id",
Organizer: &remote.Attendee{
EmailAddress: &remote.EmailAddress{
Address: "event_organizer_email",
Name: "event_organizer_name",
},
},
Location: &remote.Location{
DisplayName: locationDisplayName,
},
ResponseStatus: &remote.EventResponseStatus{
Response: "event_response",
},
Weblink: "event_weblink",
Subject: "event_subject",
BodyPreview: "event_body_preview",
ResponseRequested: true,
}
}
func newTestSubscription() *store.Subscription {
return &store.Subscription{
PluginVersion: "x.x.x",
Remote: &remote.Subscription{
ID: "remote_subscription_id",
ClientState: "stored_client_state",
},
MattermostCreatorID: "creator_mm_id",
}
}
func newTestUser() *store.User {
return &store.User{
Settings: store.Settings{
EventSubscriptionID: "remote_subscription_id",
},
Remote: &remote.User{},
OAuth2Token: &oauth2.Token{
AccessToken: "creator_oauth_token",
},
MattermostUserID: "creator_mm_id",
}
}
func newTestNotification(clientState string, recommendRenew bool) *remote.Notification {
n := &remote.Notification{
SubscriptionID: "remote_subscription_id",
IsBare: true,
SubscriptionCreator: &remote.User{},
Event: newTestEvent("event_location_display_name"),
Subscription: &remote.Subscription{},
ClientState: clientState,
RecommendRenew: recommendRenew,
}
return n
}
func | (t *testing.T) {
tcs := []struct {
name string
expectedError string
notification *remote.Notification
priorEvent *remote.Event
}{
{
name: "incoming ClientState matches stored ClientState",
expectedError: "",
notification: newTestNotification("stored_client_state", false),
priorEvent: nil,
}, {
name: "incoming ClientState doesn't match stored ClientState",
expectedError: "Unauthorized webhook",
notification: newTestNotification("wrong_client_state", false),
priorEvent: nil,
}, {
name: "prior event exists",
expectedError: "",
notification: newTestNotification("stored_client_state", false),
priorEvent: newTestEvent("prior_event_location_display_name"),
}, {
name: "sub renewal recommended",
expectedError: "",
notification: newTestNotification("stored_client_state", true),
priorEvent: nil,
},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockStore := mock_store.NewMockStore(ctrl)
mockPoster := mock_bot.NewMockPoster(ctrl)
mockRemote := mock_remote.NewMockRemote(ctrl)
mockPluginAPI := mock_plugin_api.NewMockPluginAPI(ctrl)
mockClient := mock_remote.NewMockClient(ctrl)
conf := &config.Config{BotUserID: "bot_mm_id", PluginVersion: "x.x.x"}
env := Env{
Config: conf,
Dependencies: &Dependencies{
Store: mockStore,
Logger: &bot.NilLogger{},
Poster: mockPoster,
Remote: mockRemote,
PluginAPI: mockPluginAPI,
},
}
subscription := newTestSubscription()
user := newTestUser()
mockStore.EXPECT().LoadSubscription("remote_subscription_id").Return(subscription, nil).Times(1)
mockStore.EXPECT().LoadUser("creator_mm_id").Return(user, nil).Times(1)
if tc.notification.ClientState == subscription.Remote.ClientState {
mockRemote.EXPECT().MakeClient(context.Background(), &oauth2.Token{
AccessToken: "creator_oauth_token",
}).Return(mockClient).Times(1)
if tc.notification.RecommendRenew {
mockClient.EXPECT().RenewSubscription("remote_subscription_id").Return(&remote.Subscription{}, nil).Times(1)
mockStore.EXPECT().StoreUserSubscription(user, &store.Subscription{
Remote: &remote.Subscription{},
MattermostCreatorID: "creator_mm_id",
PluginVersion: "x.x.x",
}).Return(nil).Times(1)
}
mockClient.EXPECT().GetNotificationData(tc.notification).Return(tc.notification, nil).Times(1)
if tc.priorEvent != nil {
mockStore.EXPECT().LoadUserEvent("creator_mm_id", "remote_event_id").Return(&store.Event{
Remote: tc.priorEvent,
}, nil).Times(1)
} else {
mockStore.EXPECT().LoadUserEvent("creator_mm_id", "remote_event_id").Return(nil, store.ErrNotFound).Times(1)
}
mockPoster.EXPECT().DMWithAttachments("creator_mm_id", gomock.Any()).Return(nil).Times(1)
mockStore.EXPECT().StoreUserEvent("creator_mm_id", gomock.Any()).Return(nil).Times(1)
}
p := newTestNotificationProcessor(env)
processor := p.(*notificationProcessor)
err := processor.processNotification(tc.notification)
if tc.expectedError != "" {
require.Equal(t, tc.expectedError, err.Error())
} else {
require.Nil(t, err)
}
})
}
}
| TestProcessNotification |
oauth2_backends.py | import json
from urllib.parse import urlparse, urlunparse
from oauthlib import oauth2
from oauthlib.common import quote, urlencode, urlencoded
from .exceptions import FatalClientError, OAuthToolkitError
from .settings import oauth2_settings
class OAuthLibCore(object):
"""
TODO: add docs
"""
def __init__(self, server=None):
"""
:params server: An instance of oauthlib.oauth2.Server class
"""
self.server = server or oauth2_settings.OAUTH2_SERVER_CLASS(oauth2_settings.OAUTH2_VALIDATOR_CLASS())
def _get_escaped_full_path(self, request):
"""
Django considers "safe" some characters that aren't so for oauthlib.
We have to search for them and properly escape.
"""
parsed = list(urlparse(request.get_full_path()))
unsafe = set(c for c in parsed[4]).difference(urlencoded)
for c in unsafe:
parsed[4] = parsed[4].replace(c, quote(c, safe=b""))
return urlunparse(parsed)
def _get_extra_credentials(self, request):
"""
Produce extra credentials for token response. This dictionary will be
merged with the response.
See also: `oauthlib.oauth2.rfc6749.TokenEndpoint.create_token_response`
:param request: The current django.http.HttpRequest object
:return: dictionary of extra credentials or None (default)
"""
return None
def _extract_params(self, request):
"""
Extract parameters from the Django request object.
Such parameters will then be passed to OAuthLib to build its own
Request object. The body should be encoded using OAuthLib urlencoded.
"""
uri = self._get_escaped_full_path(request)
http_method = request.method
headers = self.extract_headers(request)
body = urlencode(self.extract_body(request))
return uri, http_method, body, headers
def extract_headers(self, request):
"""
Extracts headers from the Django request object
:param request: The current django.http.HttpRequest object
:return: a dictionary with OAuthLib needed headers
"""
headers = request.META.copy()
if "wsgi.input" in headers:
del headers["wsgi.input"]
if "wsgi.errors" in headers:
del headers["wsgi.errors"]
if "HTTP_AUTHORIZATION" in headers:
headers["Authorization"] = headers["HTTP_AUTHORIZATION"]
return headers
def extract_body(self, request):
"""
Extracts the POST body from the Django request object
:param request: The current django.http.HttpRequest object
:return: provided POST parameters
"""
return request.POST.items()
def validate_authorization_request(self, request):
"""
A wrapper method that calls validate_authorization_request on `server_class` instance.
:param request: The current django.http.HttpRequest object
"""
try:
uri, http_method, body, headers = self._extract_params(request)
scopes, credentials = self.server.validate_authorization_request(
uri, http_method=http_method, body=body, headers=headers)
return scopes, credentials
except oauth2.FatalClientError as error:
raise FatalClientError(error=error)
except oauth2.OAuth2Error as error:
raise OAuthToolkitError(error=error)
def create_authorization_response(self, request, scopes, credentials, allow):
"""
A wrapper method that calls create_authorization_response on `server_class`
instance.
:param request: The current django.http.HttpRequest object
:param scopes: A list of provided scopes
:param credentials: Authorization credentials dictionary containing
`client_id`, `state`, `redirect_uri`, `response_type`
:param allow: True if the user authorize the client, otherwise False
"""
try:
if not allow:
raise oauth2.AccessDeniedError(
state=credentials.get("state", None))
# add current user to credentials. this will be used by OAUTH2_VALIDATOR_CLASS
credentials["user"] = request.user
headers, body, status = self.server.create_authorization_response(
uri=credentials["redirect_uri"], scopes=scopes, credentials=credentials)
uri = headers.get("Location", None)
return uri, headers, body, status
except oauth2.FatalClientError as error:
raise FatalClientError(error=error, redirect_uri=credentials["redirect_uri"])
except oauth2.OAuth2Error as error:
raise OAuthToolkitError(error=error, redirect_uri=credentials["redirect_uri"])
def create_token_response(self, request):
"""
A wrapper method that calls create_token_response on `server_class` instance.
:param request: The current django.http.HttpRequest object
"""
uri, http_method, body, headers = self._extract_params(request)
extra_credentials = self._get_extra_credentials(request)
headers, body, status = self.server.create_token_response(uri, http_method, body,
headers, extra_credentials)
uri = headers.get("Location", None)
return uri, headers, body, status
def create_revocation_response(self, request):
"""
A wrapper method that calls create_revocation_response on a
`server_class` instance.
:param request: The current django.http.HttpRequest object | """
uri, http_method, body, headers = self._extract_params(request)
headers, body, status = self.server.create_revocation_response(
uri, http_method, body, headers)
uri = headers.get("Location", None)
return uri, headers, body, status
def verify_request(self, request, scopes):
"""
A wrapper method that calls verify_request on `server_class` instance.
:param request: The current django.http.HttpRequest object
:param scopes: A list of scopes required to verify so that request is verified
"""
uri, http_method, body, headers = self._extract_params(request)
valid, r = self.server.verify_request(uri, http_method, body, headers, scopes=scopes)
return valid, r
class JSONOAuthLibCore(OAuthLibCore):
"""
Extends the default OAuthLibCore to parse correctly application/json requests
"""
def extract_body(self, request):
"""
Extracts the JSON body from the Django request object
:param request: The current django.http.HttpRequest object
:return: provided POST parameters "urlencodable"
"""
try:
body = json.loads(request.body.decode("utf-8")).items()
except AttributeError:
body = ""
except ValueError:
body = ""
return body
def get_oauthlib_core():
"""
Utility function that take a request and returns an instance of
`oauth2_provider.backends.OAuthLibCore`
"""
validator = oauth2_settings.OAUTH2_VALIDATOR_CLASS()
server = oauth2_settings.OAUTH2_SERVER_CLASS(validator)
return oauth2_settings.OAUTH2_BACKEND_CLASS(server) | |
icon.app_code-js.min.js | (window.webpackJsonp=window.webpackJsonp||[]).push([[9],{4054:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.icon=void 0,n(9),n(5),n(6),n(7);var r=function(e){return e&&e.__esModule?e:{default:e}}(n(0));function l(){return(l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function o(e,t){if(null==e)return{};var n,r,l=function(e,t){if(null==e)return{};var n,r,l={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(l[n]=e[n]);return l}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}var a=function(e){var t=e.title,n=o(e,["title"]);return r.default.createElement("svg",l({width:32,height:32,viewBox:"0 0 32 32",xmlns:"http://www.w3.org/2000/svg"},n),r.default.createElement("title",null,t),r.default.createElement("path",{d:"M11.276 29l.594 2H0l7.621-14.29.811 2.73L3.333 29h7.943zM28.92 31l-4.987-16.598A16 16 0 008.688 3l1.8 6H8.4L6 1h2.607a18 18 0 0117.241 12.828L31 31h-2.08z"}),r.default.createElement("path",{className:"euiIcon__fillSecondary",d:"M12.037 14.02L16.492 29h6.827l-2.333-7.849a10 10 0 00-8.949-7.13zM9.35 12h2.05a12 12 0 0111.503 8.581L26 31H15L9.35 12z"}))},i=a;t.icon=i,a.__docgenInfo={description:"",methods:[],displayName:"EuiIconAppCode"}}}]); | //# sourceMappingURL=icon.app_code-js.min.js.map |
|
srv.go | // Copyright 2015 CoreOS, Inc.
//
// 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 client
import (
"fmt"
"net"
"net/url"
)
var (
// indirection for testing
lookupSRV = net.LookupSRV
)
type srvDiscover struct{}
// NewSRVDiscover constructs a new Dicoverer that uses the stdlib to lookup SRV records.
func NewSRVDiscover() Discoverer { | return &srvDiscover{}
}
// Discover looks up the etcd servers for the domain.
func (d *srvDiscover) Discover(domain string) ([]string, error) {
var urls []*url.URL
updateURLs := func(service, scheme string) error {
_, addrs, err := lookupSRV(service, "tcp", domain)
if err != nil {
return err
}
for _, srv := range addrs {
urls = append(urls, &url.URL{
Scheme: scheme,
Host: net.JoinHostPort(srv.Target, fmt.Sprintf("%d", srv.Port)),
})
}
return nil
}
errHTTPS := updateURLs("etcd-server-ssl", "https")
errHTTP := updateURLs("etcd-server", "http")
if errHTTPS != nil && errHTTP != nil {
return nil, fmt.Errorf("dns lookup errors: %s and %s", errHTTPS, errHTTP)
}
endpoints := make([]string, len(urls))
for i := range urls {
endpoints[i] = urls[i].String()
}
return endpoints, nil
} | |
script.js | $(document).ready(function () {
$("section").slideUp(0);
$("table").fadeOut(0);
$("section div").css("margin-top", "-14px");
$("section div h4").click(function () {
if ($(this).next("table").is(":hidden")) {
$(this).next("table").fadeIn("slow");
} else {
$(this).next("table").fadeOut("slow");
}
});
$("#button1").click(function () {
$("section").slideToggle("slow");
$("#button2, #toggle").toggle(0);
});
$("#button2").click(function () {
$("table").slideToggle("slow");
});
$("#scroll").click(function () {
$("html, body").animate({ scrollTop: 0 }, "slow");
});
});
function | () {
new Chart(document.getElementById("firstChart"), {
type: "bar",
data: {
labels: ["OK (71.4%)", "ERROR (28.6%)"],
datasets: [
{
backgroundColor: ["#41b3a3", "#e7717d"],
data: [5, 2],
},
],
},
options: {
legend: {
display: false
},
title: {
display: true,
text: "TEST SCENARIOS"
},
scales: {
yAxes: [
{ ticks: { beginAtZero: true } }
]
},
},
});
new Chart(document.getElementById("secondChart"), {
type: "horizontalBar",
data: {
labels: ["OK (75%)", "ERROR (8.3%)", "WARN (16.7%)"],
datasets: [
{
backgroundColor: ["#41b3a3", "#e7717d", "#fbc02d"],
data: [18, 2, 4],
},
],
},
options: {
legend: {
display: false
},
title: {
display: true,
text: "TEST STEPS"
},
scales: {
xAxes: [
{ ticks: { beginAtZero: true } }
]
},
},
});
} | showCharts |
train_acregnet.py | from data import DataHandler
from models import ACRegNet
import tensorflow as tf
from utils import get_random_batch, read_config_file, create_dir
RUN_IN_GPU = False
def train_acregnet_model(config):
|
if __name__ == "__main__":
config = read_config_file('./config/JSRT/ACRegNet.cfg')
create_dir(config['ckpt_dir'])
train_acregnet_model(config)
| tf.reset_default_graph()
tf_config = tf.ConfigProto()
if RUN_IN_GPU:
tf_config.gpu_options.allow_growth = True
sess = tf.Session(config=tf_config)
train_ims, _ = DataHandler.load_images(config['train_ims_file'])
train_lbs, _ = DataHandler.load_labels(config['train_lbs_file'])
print('Loading training data...done')
acregnet = ACRegNet(sess, config, 'ACRegNet', is_train=True)
print('Building AC-RegNet model...done')
print('Training...')
for i in range(config['iterations']):
batch_ims_x, batch_ims_y, batch_lbs_x, batch_lbs_y = get_random_batch(
train_ims, config['batch_size'], train_lbs)
cur_loss = acregnet.fit(
batch_ims_x, batch_ims_y, batch_lbs_x, batch_lbs_y)
print('Iteration {:>8d}/{}: Loss: {}'.format(
i + 1, config['iterations'], cur_loss))
acregnet.save(config['ckpt_dir'])
print('Saving current AC-RegNet model...done')
print('Training...done')
tf.reset_default_graph()
sess.close() |
proxymanager.py | from utils import*
from random import*
formattedProxies = []
def chooseProxy(tasknum): | a = randint(1, len(proxieslines) - 1)
if len(proxieslines) == 1:
a = 0
proxy = proxieslines[a].rstrip()
try:
proxytest = proxy.split(":")[2]
userpass = True
except IndexError:
userpass = False
if userpass == False:
proxyedit = proxy
if userpass == True:
ip = proxy.split(":")[0]
port = proxy.split(":")[1]
userpassproxy = ip + ':' + port
proxyedit = userpassproxy
proxyuser = proxy.split(":")[2]
proxyuser = proxyuser.rstrip()
proxypass = proxy.split(":")[3]
proxyuser = proxyuser.rstrip()
if userpass == True:
proxies = {'http': 'http://' + proxyuser + ':' + proxypass + '@' + userpassproxy,
'https': 'https://' + proxyuser + ':' + proxypass + '@' + userpassproxy}
if userpass == False:
proxies = {'http': 'http://' + proxy,
'https': 'https://' + proxy}
global formattedProxies
formattedProxies.append(proxies)
return proxies
def importProxies(proxyfile):
p = open('{}.txt'.format(proxyfile))
global proxieslines
proxieslines = p.readlines()
numproxies = len(proxieslines)
global formattedProxies
if numproxies > 0:
formattedProxies = []
for i in range (0,len(proxieslines)):
chooseProxy(i)
if numproxies == 0:
formattedProxies = [None]
# print(formattedProxies[0])
xlpFormat() #IMPORTANT DO NOT REMOVE OR ELSE SCRIPT WILL BREAK.
log('%s proxies loaded' % numproxies)
return formattedProxies | if tasknum + 1 <= len(proxieslines):
proxy = proxieslines[tasknum].rstrip()
if tasknum + 1 > len(proxieslines):
if len(proxieslines) > 1: |
data.go | package clusterinfo
import (
"fmt"
"net"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"github.com/blang/semver"
"github.com/chainhelen/dtnsq/internal/http_api"
"github.com/chainhelen/dtnsq/internal/lg"
"github.com/chainhelen/dtnsq/internal/stringy"
)
type PartialErr interface {
error
Errors() []error
}
type ErrList []error
func (l ErrList) Error() string {
var es []string
for _, e := range l {
es = append(es, e.Error())
}
return strings.Join(es, "\n")
}
func (l ErrList) Errors() []error {
return l
}
type ClusterInfo struct {
log lg.AppLogFunc
client *http_api.Client
}
func New(log lg.AppLogFunc, client *http_api.Client) *ClusterInfo |
func (c *ClusterInfo) logf(f string, args ...interface{}) {
if c.log != nil {
c.log(lg.INFO, f, args...)
}
}
// GetVersion returns a semver.Version object by querying /info
func (c *ClusterInfo) GetVersion(addr string) (semver.Version, error) {
endpoint := fmt.Sprintf("http://%s/info", addr)
var resp struct {
Version string `json:"version"`
}
err := c.client.GETV1(endpoint, &resp)
if err != nil {
return semver.Version{}, err
}
if resp.Version == "" {
resp.Version = "unknown"
}
return semver.Parse(resp.Version)
}
// GetLookupdTopics returns a []string containing a union of all the topics
// from all the given nsqlookupd
func (c *ClusterInfo) GetLookupdTopics(lookupdHTTPAddrs []string) ([]string, error) {
var topics []string
var lock sync.Mutex
var wg sync.WaitGroup
var errs []error
type respType struct {
Topics []string `json:"topics"`
}
for _, addr := range lookupdHTTPAddrs {
wg.Add(1)
go func(addr string) {
defer wg.Done()
endpoint := fmt.Sprintf("http://%s/topics", addr)
c.logf("CI: querying nsqlookupd %s", endpoint)
var resp respType
err := c.client.GETV1(endpoint, &resp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
lock.Lock()
defer lock.Unlock()
topics = append(topics, resp.Topics...)
}(addr)
}
wg.Wait()
if len(errs) == len(lookupdHTTPAddrs) {
return nil, fmt.Errorf("Failed to query any nsqlookupd: %s", ErrList(errs))
}
topics = stringy.Uniq(topics)
sort.Strings(topics)
if len(errs) > 0 {
return topics, ErrList(errs)
}
return topics, nil
}
// GetLookupdTopicChannels returns a []string containing a union of all the channels
// from all the given lookupd for the given topic
func (c *ClusterInfo) GetLookupdTopicChannels(topic string, lookupdHTTPAddrs []string) ([]string, error) {
var channels []string
var lock sync.Mutex
var wg sync.WaitGroup
var errs []error
type respType struct {
Channels []string `json:"channels"`
}
for _, addr := range lookupdHTTPAddrs {
wg.Add(1)
go func(addr string) {
defer wg.Done()
endpoint := fmt.Sprintf("http://%s/channels?topic=%s", addr, url.QueryEscape(topic))
c.logf("CI: querying nsqlookupd %s", endpoint)
var resp respType
err := c.client.GETV1(endpoint, &resp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
lock.Lock()
defer lock.Unlock()
channels = append(channels, resp.Channels...)
}(addr)
}
wg.Wait()
if len(errs) == len(lookupdHTTPAddrs) {
return nil, fmt.Errorf("Failed to query any nsqlookupd: %s", ErrList(errs))
}
channels = stringy.Uniq(channels)
sort.Strings(channels)
if len(errs) > 0 {
return channels, ErrList(errs)
}
return channels, nil
}
// GetLookupdProducers returns Producers of all the nsqd connected to the given lookupds
func (c *ClusterInfo) GetLookupdProducers(lookupdHTTPAddrs []string) (Producers, error) {
var producers []*Producer
var lock sync.Mutex
var wg sync.WaitGroup
var errs []error
producersByAddr := make(map[string]*Producer)
maxVersion, _ := semver.Parse("0.0.0")
type respType struct {
Producers []*Producer `json:"producers"`
}
for _, addr := range lookupdHTTPAddrs {
wg.Add(1)
go func(addr string) {
defer wg.Done()
endpoint := fmt.Sprintf("http://%s/nodes", addr)
c.logf("CI: querying nsqlookupd %s", endpoint)
var resp respType
err := c.client.GETV1(endpoint, &resp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
lock.Lock()
defer lock.Unlock()
for _, producer := range resp.Producers {
key := producer.TCPAddress()
p, ok := producersByAddr[key]
if !ok {
producersByAddr[key] = producer
producers = append(producers, producer)
if maxVersion.LT(producer.VersionObj) {
maxVersion = producer.VersionObj
}
sort.Sort(producer.Topics)
p = producer
}
p.RemoteAddresses = append(p.RemoteAddresses,
fmt.Sprintf("%s/%s", addr, producer.Address()))
}
}(addr)
}
wg.Wait()
if len(errs) == len(lookupdHTTPAddrs) {
return nil, fmt.Errorf("Failed to query any nsqlookupd: %s", ErrList(errs))
}
for _, producer := range producersByAddr {
if producer.VersionObj.LT(maxVersion) {
producer.OutOfDate = true
}
}
sort.Sort(ProducersByHost{producers})
if len(errs) > 0 {
return producers, ErrList(errs)
}
return producers, nil
}
// GetLookupdTopicProducers returns Producers of all the nsqd for a given topic by
// unioning the nodes returned from the given lookupd
func (c *ClusterInfo) GetLookupdTopicProducers(topic string, lookupdHTTPAddrs []string) (Producers, error) {
var producers Producers
var lock sync.Mutex
var wg sync.WaitGroup
var errs []error
type respType struct {
Producers Producers `json:"producers"`
}
for _, addr := range lookupdHTTPAddrs {
wg.Add(1)
go func(addr string) {
defer wg.Done()
endpoint := fmt.Sprintf("http://%s/lookup?topic=%s", addr, url.QueryEscape(topic))
c.logf("CI: querying nsqlookupd %s", endpoint)
var resp respType
err := c.client.GETV1(endpoint, &resp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
lock.Lock()
defer lock.Unlock()
for _, p := range resp.Producers {
for _, pp := range producers {
if p.HTTPAddress() == pp.HTTPAddress() {
goto skip
}
}
producers = append(producers, p)
skip:
}
}(addr)
}
wg.Wait()
if len(errs) == len(lookupdHTTPAddrs) {
return nil, fmt.Errorf("Failed to query any nsqlookupd: %s", ErrList(errs))
}
if len(errs) > 0 {
return producers, ErrList(errs)
}
return producers, nil
}
// GetNSQDTopics returns a []string containing all the topics produced by the given nsqd
func (c *ClusterInfo) GetNSQDTopics(nsqdHTTPAddrs []string) ([]string, error) {
var topics []string
var lock sync.Mutex
var wg sync.WaitGroup
var errs []error
type respType struct {
Topics []struct {
Name string `json:"topic_name"`
} `json:"topics"`
}
for _, addr := range nsqdHTTPAddrs {
wg.Add(1)
go func(addr string) {
defer wg.Done()
endpoint := fmt.Sprintf("http://%s/stats?format=json", addr)
c.logf("CI: querying nsqd %s", endpoint)
var resp respType
err := c.client.GETV1(endpoint, &resp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
lock.Lock()
defer lock.Unlock()
for _, topic := range resp.Topics {
topics = stringy.Add(topics, topic.Name)
}
}(addr)
}
wg.Wait()
if len(errs) == len(nsqdHTTPAddrs) {
return nil, fmt.Errorf("Failed to query any nsqd: %s", ErrList(errs))
}
sort.Strings(topics)
if len(errs) > 0 {
return topics, ErrList(errs)
}
return topics, nil
}
// GetNSQDProducers returns Producers of all the given nsqd
func (c *ClusterInfo) GetNSQDProducers(nsqdHTTPAddrs []string) (Producers, error) {
var producers Producers
var lock sync.Mutex
var wg sync.WaitGroup
var errs []error
type infoRespType struct {
Version string `json:"version"`
BroadcastAddress string `json:"broadcast_address"`
Hostname string `json:"hostname"`
HTTPPort int `json:"http_port"`
TCPPort int `json:"tcp_port"`
}
type statsRespType struct {
Topics []struct {
Name string `json:"topic_name"`
} `json:"topics"`
}
for _, addr := range nsqdHTTPAddrs {
wg.Add(1)
go func(addr string) {
defer wg.Done()
endpoint := fmt.Sprintf("http://%s/info", addr)
c.logf("CI: querying nsqd %s", endpoint)
var infoResp infoRespType
err := c.client.GETV1(endpoint, &infoResp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
endpoint = fmt.Sprintf("http://%s/stats?format=json&include_clients=false", addr)
c.logf("CI: querying nsqd %s", endpoint)
var statsResp statsRespType
err = c.client.GETV1(endpoint, &statsResp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
var producerTopics ProducerTopics
for _, t := range statsResp.Topics {
producerTopics = append(producerTopics, ProducerTopic{Topic: t.Name})
}
version, err := semver.Parse(infoResp.Version)
if err != nil {
version, _ = semver.Parse("0.0.0")
}
lock.Lock()
defer lock.Unlock()
producers = append(producers, &Producer{
Version: infoResp.Version,
VersionObj: version,
BroadcastAddress: infoResp.BroadcastAddress,
Hostname: infoResp.Hostname,
HTTPPort: infoResp.HTTPPort,
TCPPort: infoResp.TCPPort,
Topics: producerTopics,
})
}(addr)
}
wg.Wait()
if len(errs) == len(nsqdHTTPAddrs) {
return nil, fmt.Errorf("Failed to query any nsqd: %s", ErrList(errs))
}
if len(errs) > 0 {
return producers, ErrList(errs)
}
return producers, nil
}
// GetNSQDTopicProducers returns Producers containing the addresses of all the nsqd
// that produce the given topic
func (c *ClusterInfo) GetNSQDTopicProducers(topic string, nsqdHTTPAddrs []string) (Producers, error) {
var producers Producers
var lock sync.Mutex
var wg sync.WaitGroup
var errs []error
type infoRespType struct {
Version string `json:"version"`
BroadcastAddress string `json:"broadcast_address"`
Hostname string `json:"hostname"`
HTTPPort int `json:"http_port"`
TCPPort int `json:"tcp_port"`
}
type statsRespType struct {
Topics []struct {
Name string `json:"topic_name"`
} `json:"topics"`
}
for _, addr := range nsqdHTTPAddrs {
wg.Add(1)
go func(addr string) {
defer wg.Done()
endpoint := fmt.Sprintf("http://%s/stats?format=json&topic=%s&include_clients=false",
addr, url.QueryEscape(topic))
c.logf("CI: querying nsqd %s", endpoint)
var statsResp statsRespType
err := c.client.GETV1(endpoint, &statsResp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
var producerTopics ProducerTopics
for _, t := range statsResp.Topics {
producerTopics = append(producerTopics, ProducerTopic{Topic: t.Name})
}
for _, t := range statsResp.Topics {
if t.Name == topic {
endpoint := fmt.Sprintf("http://%s/info", addr)
c.logf("CI: querying nsqd %s", endpoint)
var infoResp infoRespType
err := c.client.GETV1(endpoint, &infoResp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
version, err := semver.Parse(infoResp.Version)
if err != nil {
version, _ = semver.Parse("0.0.0")
}
// if BroadcastAddress/HTTPPort are missing, use the values from `addr` for
// backwards compatibility
if infoResp.BroadcastAddress == "" {
var p string
infoResp.BroadcastAddress, p, _ = net.SplitHostPort(addr)
infoResp.HTTPPort, _ = strconv.Atoi(p)
}
if infoResp.Hostname == "" {
infoResp.Hostname, _, _ = net.SplitHostPort(addr)
}
lock.Lock()
producers = append(producers, &Producer{
Version: infoResp.Version,
VersionObj: version,
BroadcastAddress: infoResp.BroadcastAddress,
Hostname: infoResp.Hostname,
HTTPPort: infoResp.HTTPPort,
TCPPort: infoResp.TCPPort,
Topics: producerTopics,
})
lock.Unlock()
return
}
}
}(addr)
}
wg.Wait()
if len(errs) == len(nsqdHTTPAddrs) {
return nil, fmt.Errorf("Failed to query any nsqd: %s", ErrList(errs))
}
if len(errs) > 0 {
return producers, ErrList(errs)
}
return producers, nil
}
// GetNSQDStats returns aggregate topic and channel stats from the given Producers
//
// if selectedChannel is empty, this will return stats for topic/channel
// if selectedTopic is empty, this will return stats for *all* topic/channels
// if includeClients is false, this will *not* return client stats for channels
// and the ChannelStats dict will be keyed by topic + ':' + channel
func (c *ClusterInfo) GetNSQDStats(producers Producers,
selectedTopic string, selectedChannel string,
includeClients bool) ([]*TopicStats, map[string]*ChannelStats, error) {
var lock sync.Mutex
var wg sync.WaitGroup
var topicStatsList TopicStatsList
var errs []error
channelStatsMap := make(map[string]*ChannelStats)
type respType struct {
Topics []*TopicStats `json:"topics"`
}
for _, p := range producers {
wg.Add(1)
go func(p *Producer) {
defer wg.Done()
addr := p.HTTPAddress()
endpoint := fmt.Sprintf("http://%s/stats?format=json", addr)
if selectedTopic != "" {
endpoint += "&topic=" + url.QueryEscape(selectedTopic)
if selectedChannel != "" {
endpoint += "&channel=" + url.QueryEscape(selectedChannel)
}
}
if !includeClients {
endpoint += "&include_clients=false"
}
c.logf("CI: querying nsqd %s", endpoint)
var resp respType
err := c.client.GETV1(endpoint, &resp)
if err != nil {
lock.Lock()
errs = append(errs, err)
lock.Unlock()
return
}
lock.Lock()
defer lock.Unlock()
for _, topic := range resp.Topics {
topic.Node = addr
topic.Hostname = p.Hostname
topic.MemoryDepth = topic.Depth - topic.BackendDepth
if selectedTopic != "" && topic.TopicName != selectedTopic {
continue
}
topicStatsList = append(topicStatsList, topic)
for _, channel := range topic.Channels {
channel.Node = addr
channel.Hostname = p.Hostname
channel.TopicName = topic.TopicName
channel.MemoryDepth = channel.Depth - channel.BackendDepth
key := channel.ChannelName
if selectedTopic == "" {
key = fmt.Sprintf("%s:%s", topic.TopicName, channel.ChannelName)
}
channelStats, ok := channelStatsMap[key]
if !ok {
channelStats = &ChannelStats{
Node: addr,
TopicName: topic.TopicName,
ChannelName: channel.ChannelName,
}
channelStatsMap[key] = channelStats
}
for _, c := range channel.Clients {
c.Node = addr
}
channelStats.Add(channel)
}
}
}(p)
}
wg.Wait()
if len(errs) == len(producers) {
return nil, nil, fmt.Errorf("Failed to query any nsqd: %s", ErrList(errs))
}
sort.Sort(TopicStatsByHost{topicStatsList})
if len(errs) > 0 {
return topicStatsList, channelStatsMap, ErrList(errs)
}
return topicStatsList, channelStatsMap, nil
}
// TombstoneNodeForTopic tombstones the given node for the given topic on all the given nsqlookupd
// and deletes the topic from the node
func (c *ClusterInfo) TombstoneNodeForTopic(topic string, node string, lookupdHTTPAddrs []string) error {
var errs []error
// tombstone the topic on all the lookupds
qs := fmt.Sprintf("topic=%s&node=%s", url.QueryEscape(topic), url.QueryEscape(node))
err := c.nsqlookupdPOST(lookupdHTTPAddrs, "topic/tombstone", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
producers, err := c.GetNSQDProducers([]string{node})
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
// delete the topic on the producer
qs = fmt.Sprintf("topic=%s", url.QueryEscape(topic))
err = c.producersPOST(producers, "topic/delete", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
if len(errs) > 0 {
return ErrList(errs)
}
return nil
}
func (c *ClusterInfo) CreateTopicChannel(topicName string, channelName string, lookupdHTTPAddrs []string) error {
var errs []error
// create the topic on all the nsqlookupd
qs := fmt.Sprintf("topic=%s", url.QueryEscape(topicName))
err := c.nsqlookupdPOST(lookupdHTTPAddrs, "topic/create", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
if len(channelName) > 0 {
qs := fmt.Sprintf("topic=%s&channel=%s", url.QueryEscape(topicName), url.QueryEscape(channelName))
// create the channel on all the nsqlookupd
err := c.nsqlookupdPOST(lookupdHTTPAddrs, "channel/create", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
// create the channel on all the nsqd that produce the topic
producers, err := c.GetLookupdTopicProducers(topicName, lookupdHTTPAddrs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
err = c.producersPOST(producers, "channel/create", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
}
if len(errs) > 0 {
return ErrList(errs)
}
return nil
}
func (c *ClusterInfo) DeleteTopic(topicName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) error {
var errs []error
// for topic removal, you need to get all the producers _first_
producers, err := c.GetTopicProducers(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
qs := fmt.Sprintf("topic=%s", url.QueryEscape(topicName))
// remove the topic from all the nsqlookupd
err = c.nsqlookupdPOST(lookupdHTTPAddrs, "topic/delete", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
// remove the topic from all the nsqd that produce this topic
err = c.producersPOST(producers, "topic/delete", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
if len(errs) > 0 {
return ErrList(errs)
}
return nil
}
func (c *ClusterInfo) DeleteChannel(topicName string, channelName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) error {
var errs []error
producers, err := c.GetTopicProducers(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
qs := fmt.Sprintf("topic=%s&channel=%s", url.QueryEscape(topicName), url.QueryEscape(channelName))
// remove the channel from all the nsqlookupd
err = c.nsqlookupdPOST(lookupdHTTPAddrs, "channel/delete", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
// remove the channel from all the nsqd that produce this topic
err = c.producersPOST(producers, "channel/delete", qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
if len(errs) > 0 {
return ErrList(errs)
}
return nil
}
func (c *ClusterInfo) PauseTopic(topicName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) error {
qs := fmt.Sprintf("topic=%s", url.QueryEscape(topicName))
return c.actionHelper(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs, "topic/pause", qs)
}
func (c *ClusterInfo) UnPauseTopic(topicName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) error {
qs := fmt.Sprintf("topic=%s", url.QueryEscape(topicName))
return c.actionHelper(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs, "topic/unpause", qs)
}
func (c *ClusterInfo) PauseChannel(topicName string, channelName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) error {
qs := fmt.Sprintf("topic=%s&channel=%s", url.QueryEscape(topicName), url.QueryEscape(channelName))
return c.actionHelper(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs, "channel/pause", qs)
}
func (c *ClusterInfo) UnPauseChannel(topicName string, channelName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) error {
qs := fmt.Sprintf("topic=%s&channel=%s", url.QueryEscape(topicName), url.QueryEscape(channelName))
return c.actionHelper(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs, "channel/unpause", qs)
}
func (c *ClusterInfo) EmptyTopic(topicName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) error {
qs := fmt.Sprintf("topic=%s", url.QueryEscape(topicName))
return c.actionHelper(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs, "topic/empty", qs)
}
func (c *ClusterInfo) EmptyChannel(topicName string, channelName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) error {
qs := fmt.Sprintf("topic=%s&channel=%s", url.QueryEscape(topicName), url.QueryEscape(channelName))
return c.actionHelper(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs, "channel/empty", qs)
}
func (c *ClusterInfo) actionHelper(topicName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string, uri string, qs string) error {
var errs []error
producers, err := c.GetTopicProducers(topicName, lookupdHTTPAddrs, nsqdHTTPAddrs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
err = c.producersPOST(producers, uri, qs)
if err != nil {
pe, ok := err.(PartialErr)
if !ok {
return err
}
errs = append(errs, pe.Errors()...)
}
if len(errs) > 0 {
return ErrList(errs)
}
return nil
}
func (c *ClusterInfo) GetProducers(lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) (Producers, error) {
if len(lookupdHTTPAddrs) != 0 {
return c.GetLookupdProducers(lookupdHTTPAddrs)
}
return c.GetNSQDProducers(nsqdHTTPAddrs)
}
func (c *ClusterInfo) GetTopicProducers(topicName string, lookupdHTTPAddrs []string, nsqdHTTPAddrs []string) (Producers, error) {
if len(lookupdHTTPAddrs) != 0 {
return c.GetLookupdTopicProducers(topicName, lookupdHTTPAddrs)
}
return c.GetNSQDTopicProducers(topicName, nsqdHTTPAddrs)
}
func (c *ClusterInfo) nsqlookupdPOST(addrs []string, uri string, qs string) error {
var errs []error
for _, addr := range addrs {
endpoint := fmt.Sprintf("http://%s/%s?%s", addr, uri, qs)
c.logf("CI: querying nsqlookupd %s", endpoint)
err := c.client.POSTV1(endpoint)
if err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return ErrList(errs)
}
return nil
}
func (c *ClusterInfo) producersPOST(pl Producers, uri string, qs string) error {
var errs []error
for _, p := range pl {
endpoint := fmt.Sprintf("http://%s/%s?%s", p.HTTPAddress(), uri, qs)
c.logf("CI: querying nsqd %s", endpoint)
err := c.client.POSTV1(endpoint)
if err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return ErrList(errs)
}
return nil
}
| {
return &ClusterInfo{
log: log,
client: client,
}
} |
error.rs | use thiserror::Error;
#[derive(Error, Debug)]
pub(crate) enum | {
#[error("Io error; {0}")]
IoError(#[from] std::io::Error),
#[error("Fmt error; {0}")]
FmtError(#[from] std::fmt::Error),
#[error("Config error: {0}")]
ConfigError(#[from] config::ConfigError),
#[error("Serde yaml error; {0}")]
SerdeYAMLError(#[from] serde_yaml::Error),
#[error("ParseInt error: {0}")]
ParseIntError(#[from] std::num::ParseIntError),
#[error("Xcb error; {0}")]
XcbError(#[from] xcb::Error<xcb::ffi::xcb_generic_error_t>),
#[error("No screen found")]
NoScreenFound,
#[error("Invalid position specified")]
InvalidPosition,
#[error("Unknown key")]
UnknownKey,
#[error("Configuration not provided, run with --help")]
NoConfig,
}
| Error |
module.rs | use error::Error;
use translate_sections;
use wasmparser::{ModuleReader, SectionCode};
/// Translate from a slice of bytes holding a wasm module.
pub fn translate(data: &[u8]) -> Result<(), Error> {
let mut reader = ModuleReader::new(data)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
let mut section = reader.read()?;
if let SectionCode::Type = section.code {
let types = section.get_type_section_reader()?;
translate_sections::type_(types)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Import = section.code {
let imports = section.get_import_section_reader()?;
translate_sections::import(imports)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Function = section.code {
let functions = section.get_function_section_reader()?;
translate_sections::function(functions)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Table = section.code {
let tables = section.get_table_section_reader()?;
translate_sections::table(tables)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Memory = section.code {
let memories = section.get_memory_section_reader()?;
translate_sections::memory(memories)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Global = section.code {
let globals = section.get_global_section_reader()?;
translate_sections::global(globals)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Export = section.code {
let exports = section.get_export_section_reader()?;
translate_sections::export(exports)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Start = section.code |
if let SectionCode::Element = section.code {
let elements = section.get_element_section_reader()?;
translate_sections::element(elements)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Code = section.code {
let code = section.get_code_section_reader()?;
translate_sections::code(code)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
}
if let SectionCode::Data = section.code {
let data = section.get_data_section_reader()?;
translate_sections::data(data)?;
}
Ok(())
}
| {
let start = section.get_start_section_content()?;
translate_sections::start(start)?;
reader.skip_custom_sections()?;
if reader.eof() {
return Ok(());
}
section = reader.read()?;
} |
upsert.d.ts | /**
* @module Upsert
*/
import * as dgraph from 'dgraph-js';
import { Txn } from 'dgraph-js';
export declare type uid = string;
export interface INodeFoundFunction {
existingUid: string | null;
newNodeFn?: (node: any) => object;
}
export interface IUpsertFnReturnValues {
dgraphQuery: string;
nodeFoundFn: (queryResult: dgraph.Response) => INodeFoundFunction;
}
/**
* #### Return a dgraph query and a node found function
*
* The basicEqualityUpsertFn below will find any nodes that has skill and level predicates.
* ```ts
* const updateJunior = {
* skill: 'Javascript',
* level: 10, | * y: 'y',
* z: 'y'
* };
*
* // So if you already had a node in the db that looks like:
* const existingNode = {
* skill: 'Javascript',
* level: 10,
* x: 'foo',
* y: 'foo',
* z: 'foo'
* };
*
* /// x, y and z would be updated from 'foo' to 'y'
* const updates = [updateJunior];
* const upsertFn = basicEqualityUpsertFn(['skill', 'level']);
*
* // takes a upsertFn as well as an array or single object returns a uid or an array of uids
* await xUpsertCommitTxn(upsertFn, updates, dgraphClient);
* ```
*
* If no node matched both skill 'Javascript' and level '10' a new node would be created
*/
export declare function xUpsertCommitTxn(upsertFn: (input?: any) => IUpsertFnReturnValues, data: object[], dgraphClient: dgraph.DgraphClient, _dgraph?: any): Promise<uid[]>;
export declare function xUpsertCommitTxn(upsertFn: (input?: any) => IUpsertFnReturnValues, data: object, dgraphClient: dgraph.DgraphClient, _dgraph?: any): Promise<uid>;
/** * @ignore */
export declare function xUpsertObject(upsertFn: (input?: any) => IUpsertFnReturnValues, node: object, transaction: Txn): Promise<uid | null>; | * x: 'y', |
tipset.rs | // Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use super::*;
use chain::ChainStore;
use fil_types::verifier::FullVerifier;
use num_bigint::ToBigInt;
use state_manager::StateManager;
use std::sync::Arc;
mod block_messages_json {
use super::*;
use serde::de;
#[derive(Deserialize)]
pub struct BlockMessageJson {
#[serde(with = "address::json")]
pub miner_addr: Address,
pub win_count: i64,
#[serde(with = "base64_bytes::vec")]
pub messages: Vec<Vec<u8>>,
}
pub fn | <'de, D>(deserializer: D) -> Result<Vec<BlockMessages>, D::Error>
where
D: Deserializer<'de>,
{
let bm: Vec<BlockMessageJson> = Deserialize::deserialize(deserializer)?;
Ok(bm
.into_iter()
.map(|m| {
let mut secpk_messages = Vec::new();
let mut bls_messages = Vec::new();
for message in &m.messages {
let msg_decoded =
UnsignedMessage::unmarshal_cbor(&message).map_err(de::Error::custom)?;
match msg_decoded.from().protocol() {
Protocol::Secp256k1 => secpk_messages.push(to_chain_msg(msg_decoded)),
Protocol::BLS => bls_messages.push(to_chain_msg(msg_decoded)),
_ => {
// matching go runner to force failure (bad address)
secpk_messages.push(to_chain_msg(msg_decoded.clone()));
bls_messages.push(to_chain_msg(msg_decoded));
}
}
}
bls_messages.append(&mut secpk_messages);
Ok(BlockMessages {
miner: m.miner_addr,
win_count: m.win_count,
messages: bls_messages,
})
})
.collect::<Result<Vec<BlockMessages>, _>>()?)
}
}
#[derive(Debug, Deserialize)]
pub struct TipsetVector {
pub epoch_offset: ChainEpoch,
pub basefee: f64,
#[serde(with = "block_messages_json")]
pub blocks: Vec<BlockMessages>,
}
pub struct ExecuteTipsetResult {
pub receipts_root: Cid,
pub post_state_root: Cid,
pub _applied_messages: Vec<ChainMessage>,
pub applied_results: Vec<ApplyRet>,
}
pub fn execute_tipset(
bs: Arc<db::MemoryDB>,
pre_root: &Cid,
parent_epoch: ChainEpoch,
tipset: &TipsetVector,
exec_epoch: ChainEpoch,
) -> Result<ExecuteTipsetResult, Box<dyn StdError>> {
let sm = StateManager::new(Arc::new(ChainStore::new(bs)));
let mut _applied_messages = Vec::new();
let mut applied_results = Vec::new();
let (post_state_root, receipts_root) = sm.apply_blocks::<_, FullVerifier, _>(
parent_epoch,
pre_root,
&tipset.blocks,
exec_epoch,
&TestRand,
tipset.basefee.to_bigint().unwrap_or_default(),
Some(|_: &Cid, msg: &ChainMessage, ret: &ApplyRet| {
_applied_messages.push(msg.clone());
applied_results.push(ret.clone());
Ok(())
}),
)?;
Ok(ExecuteTipsetResult {
receipts_root,
post_state_root,
_applied_messages,
applied_results,
})
}
| deserialize |
inputs.ts | import { Comparable, Serializable } from "../interfaces";
import {
ApplicationCommandOption,
ApplicationCommandOptionChoice,
ApplicationCommandOptionType,
ApplicationCommandOptionWithChoice,
} from "../definitions";
import { SlashChoiceList } from "./choices";
type InputChoiceValue = ApplicationCommandOptionChoice["value"];
type InputArgs = {
type: ApplicationCommandOptionType;
name: string;
description: string;
required?: boolean;
choices?: SlashChoiceList<InputChoiceValue>;
options?: ApplicationCommandOption[];
};
export function isChoiceType(
input: ApplicationCommandOption
): input is ApplicationCommandOptionWithChoice {
switch (input.type) {
case ApplicationCommandOptionType.STRING:
case ApplicationCommandOptionType.INTEGER:
case ApplicationCommandOptionType.NUMBER:
return true;
default:
return false;
}
}
export class Input
implements Serializable, Comparable<ApplicationCommandOption>
{
public readonly type;
public readonly name;
public readonly description;
public readonly required;
public readonly options;
public readonly choices;
constructor({
type,
name,
description,
choices,
options,
required = false,
}: InputArgs) {
this.type = type;
this.name = name;
this.description = description;
this.required = required;
this.choices = choices;
this.options = options;
}
serialize(): ApplicationCommandOption {
const payload: ApplicationCommandOption = {
type: this.type,
name: this.name,
description: this.description,
required: this.required,
};
if (isChoiceType(payload)) {
if (this.choices != null) {
payload.choices = this.choices.serialize();
}
}
// TODO: Handle Options (do we want to?)
return payload;
}
equals(schema: ApplicationCommandOption): boolean {
if (
this.type !== schema.type ||
this.name !== schema.name ||
this.description !== schema.description ||
this.required !== (schema.required ?? false)
) {
return false;
}
if (isChoiceType(schema)) {
if (
(this.choices?._choices?.size ?? 0) !== (schema.choices?.length ?? 0)
) {
return false;
}
const choiceMap = new Map();
for (const commandOption of this.choices?._choices?.values() ?? []) {
choiceMap.set(commandOption.name, commandOption.value);
}
const choiceEquality =
schema.choices?.every((choice) => {
if (!choiceMap.has(choice.name)) {
return false;
}
return choiceMap.get(choice.name) === choice.value;
}) ?? true;
if (!choiceEquality) {
return false;
}
}
// TODO: Nothing uses options yet, but eventually verify they're correct somehow
// if ((this.options?.length ?? 0) !== (schema.options?.length ?? 0)) {
// return false;
// }
return true;
}
}
interface StringInputArgs extends Omit<InputArgs, "type" | "options"> {
choices?: SlashChoiceList<string>;
}
export class StringInput extends Input {
constructor(args: StringInputArgs) {
super({ type: ApplicationCommandOptionType.STRING, ...args });
}
}
interface IntegerInputArgs extends Omit<InputArgs, "type" | "options"> {
choices?: SlashChoiceList<number>;
}
export class IntegerInput extends Input {
constructor(args: IntegerInputArgs) {
super({ type: ApplicationCommandOptionType.INTEGER, ...args });
}
}
export class BooleanInput extends Input { | super({ type: ApplicationCommandOptionType.BOOLEAN, ...args });
}
}
export class UserInput extends Input {
constructor(args: Omit<InputArgs, "type" | "choices" | "options">) {
super({ type: ApplicationCommandOptionType.USER, ...args });
}
}
export class ChannelInput extends Input {
constructor(args: Omit<InputArgs, "type" | "choices" | "options">) {
super({ type: ApplicationCommandOptionType.CHANNEL, ...args });
}
}
export class RoleInput extends Input {
constructor(args: Omit<InputArgs, "type" | "choices" | "options">) {
super({ type: ApplicationCommandOptionType.ROLE, ...args });
}
}
export class MentionableInput extends Input {
constructor(args: Omit<InputArgs, "type" | "choices" | "options">) {
super({ type: ApplicationCommandOptionType.MENTIONABLE, ...args });
}
} | constructor(args: Omit<InputArgs, "type" | "choices" | "options">) { |
brute.go | package cidranger
import (
"net"
rnet "github.com/libp2p/go-cidranger/net"
)
// bruteRanger is a brute force implementation of Ranger. Insertion and | // boosted many ways, e.g. changing usage of net.IPNet.Contains() to using masked
// bits equality checking, but the main purpose of this implementation is for
// testing because the correctness of this implementation can be easily guaranteed,
// and used as the ground truth when running a wider range of 'random' tests on
// other more sophisticated implementations.
type bruteRanger struct {
ipV4Entries map[string]RangerEntry
ipV6Entries map[string]RangerEntry
}
// newBruteRanger returns a new Ranger.
func newBruteRanger() Ranger {
return &bruteRanger{
ipV4Entries: make(map[string]RangerEntry),
ipV6Entries: make(map[string]RangerEntry),
}
}
// Insert inserts a RangerEntry into ranger.
func (b *bruteRanger) Insert(entry RangerEntry) error {
network := entry.Network()
key := network.String()
if _, found := b.ipV4Entries[key]; !found {
entries, err := b.getEntriesByVersion(entry.Network().IP)
if err != nil {
return err
}
entries[key] = entry
}
return nil
}
// Remove removes a RangerEntry identified by given network from ranger.
func (b *bruteRanger) Remove(network net.IPNet) (RangerEntry, error) {
networks, err := b.getEntriesByVersion(network.IP)
if err != nil {
return nil, err
}
key := network.String()
if networkToDelete, found := networks[key]; found {
delete(networks, key)
return networkToDelete, nil
}
return nil, nil
}
// Contains returns bool indicating whether given ip is contained by any
// network in ranger.
func (b *bruteRanger) Contains(ip net.IP) (bool, error) {
entries, err := b.getEntriesByVersion(ip)
if err != nil {
return false, err
}
for _, entry := range entries {
network := entry.Network()
if network.Contains(ip) {
return true, nil
}
}
return false, nil
}
// ContainingNetworks returns all RangerEntry(s) that given ip contained in.
func (b *bruteRanger) ContainingNetworks(ip net.IP) ([]RangerEntry, error) {
entries, err := b.getEntriesByVersion(ip)
if err != nil {
return nil, err
}
results := []RangerEntry{}
for _, entry := range entries {
network := entry.Network()
if network.Contains(ip) {
results = append(results, entry)
}
}
return results, nil
}
// CoveredNetworks returns the list of RangerEntry(s) the given ipnet
// covers. That is, the networks that are completely subsumed by the
// specified network.
func (b *bruteRanger) CoveredNetworks(network net.IPNet) ([]RangerEntry, error) {
entries, err := b.getEntriesByVersion(network.IP)
if err != nil {
return nil, err
}
var results []RangerEntry
testNetwork := rnet.NewNetwork(network)
for _, entry := range entries {
entryNetwork := rnet.NewNetwork(entry.Network())
if testNetwork.Covers(entryNetwork) {
results = append(results, entry)
}
}
return results, nil
}
// Len returns number of networks in ranger.
func (b *bruteRanger) Len() int {
return len(b.ipV4Entries) + len(b.ipV6Entries)
}
func (b *bruteRanger) getEntriesByVersion(ip net.IP) (map[string]RangerEntry, error) {
if ip.To4() != nil {
return b.ipV4Entries, nil
}
if ip.To16() != nil {
return b.ipV6Entries, nil
}
return nil, ErrInvalidNetworkInput
} | // deletion of networks is performed on an internal storage in the form of
// map[string]net.IPNet (constant time operations). However, inclusion tests are
// always performed linearly at no guaranteed traversal order of recorded networks,
// so one can assume a worst case performance of O(N). The performance can be |
utils.rs | extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate serde_json;
extern crate tokio_core;
extern crate toml;
use std::io::{self, Read};
use std::fs::File;
use std::error::Error;
use std::time::Duration;
use self::futures::{Future, Stream};
use self::futures::future::Either;
use self::hyper::Client;
use self::hyper_tls::HttpsConnector;
use self::tokio_core::reactor::{Core, Timeout};
use self::serde_json::Value as Json;
use self::toml::Value as Toml;
use crypto::{aes, blockmodes, buffer, symmetriccipher};
use crypto::buffer::{ReadBuffer, WriteBuffer};
pub fn request_json(url: &str, timeout: Option<u64>) -> Result<Json, Box<Error>> {
println!("Request: {}", url);
let mut core = Core::new()?;
let handle = core.handle();
let timeout = Timeout::new(Duration::from_secs(timeout.unwrap_or(60u64)), &handle)?;
let client = Client::configure()
.connector(HttpsConnector::new(4, &handle)?)
.build(&handle);
let get = client.get(url.parse()?).and_then(|res| {
println!("Response: {}", res.status());
res.body().concat2().and_then(move |body| {
serde_json::from_slice(&body).map_err(|_| {
hyper::Error::Io(io::Error::new(
io::ErrorKind::InvalidData,
"Error converting to json",
))
})
})
});
let work = get.select2(timeout)
.map_err(|res| match res {
Either::A((get_error, _timeout)) => get_error,
Either::B((timeout_error, _get)) => From::from(timeout_error),
})
.and_then(|res| match res {
Either::A((got, _timeout)) => Ok(got),
Either::B((_timeout_error, _get)) => Err(hyper::Error::Io(io::Error::new(
io::ErrorKind::TimedOut,
"Client timed out while connecting",
))),
});
core.run(work).map_err(From::from)
}
#[allow(dead_code)]
pub fn toml2json(toml: Toml) -> Json {
match toml {
Toml::String(s) => Json::String(s),
Toml::Integer(i) => Json::Number(i.into()),
Toml::Float(f) => {
let n = serde_json::Number::from_f64(f).expect("Float infinite and nan not allowed");
Json::Number(n)
}
Toml::Boolean(b) => Json::Bool(b),
Toml::Array(arr) => Json::Array(arr.into_iter().map(toml2json).collect()),
Toml::Table(table) => {
Json::Object(table.into_iter().map(|(k, v)| (k, toml2json(v))).collect())
}
Toml::Datetime(dt) => Json::String(dt.to_string()),
}
}
#[allow(dead_code)]
pub fn json_from_tomlfile(filename: &str) -> Json {
let mut input = String::new();
File::open(filename)
.and_then(|mut file| {
file.read_to_string(&mut input)
.expect("Error reading file content");
Ok(())
})
.expect(&format!("Error opening {}", filename));
input
.parse()
.map(toml2json)
.expect("Error converting toml to json")
}
pub fn | (str: &str) -> String {
rfc3986_encode(str, false)
}
pub fn rfc3986_encode(str: &str, full_url: bool) -> String {
str.as_bytes().iter().fold(String::new(), |mut out, &b| {
match b as char {
// unreserved:
'A' ... 'Z'
| 'a' ... 'z'
| '0' ... '9'
| '-' | '.' | '_' | '~' => out.push(b as char),
// gen-delims:
':' | '/' | '?' | '#' | '[' | ']' | '@' |
// sub-delims:
'!' | '$' | '&' | '"' | '(' | ')' | '*' |
'+' | ',' | ';' | '='
if full_url => out.push(b as char),
ch => out.push_str(&format!("%{:02X}", ch as u8)),
};
out
})
}
pub fn encrypt(data: &[u8], key: &[u8]) -> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> {
let mut encryptor: Box<symmetriccipher::Encryptor> = aes::cbc_encryptor(
aes::KeySize::KeySize256,
key,
&[0; 16],
blockmodes::PkcsPadding,
);
let mut final_result = Vec::<u8>::new();
let mut buffer = [0; 4096];
let mut read_buffer = buffer::RefReadBuffer::new(data);
let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = try!(encryptor.encrypt(&mut read_buffer, &mut write_buffer, true));
final_result.extend(write_buffer.take_read_buffer().take_remaining());
match result {
buffer::BufferResult::BufferUnderflow => break,
buffer::BufferResult::BufferOverflow => {}
}
}
Ok(final_result)
}
pub fn decrypt(
encrypted_data: &[u8],
key: &[u8],
) -> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> {
let mut decryptor: Box<symmetriccipher::Decryptor> = aes::cbc_decryptor(
aes::KeySize::KeySize256,
key,
&[0; 16],
blockmodes::PkcsPadding,
);
let mut final_result = Vec::<u8>::new();
let mut buffer = [0; 4096];
let mut read_buffer = buffer::RefReadBuffer::new(encrypted_data);
let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = try!(decryptor.decrypt(&mut read_buffer, &mut write_buffer, true));
final_result.extend(write_buffer.take_read_buffer().take_remaining());
match result {
buffer::BufferResult::BufferUnderflow => break,
buffer::BufferResult::BufferOverflow => {}
}
}
Ok(final_result)
}
| query_quote |
storage.go | //
// (C) Copyright 2019-2022 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package main
import (
"context"
"strings"
"github.com/pkg/errors"
"github.com/daos-stack/daos/src/control/cmd/dmg/pretty"
"github.com/daos-stack/daos/src/control/common"
"github.com/daos-stack/daos/src/control/lib/control"
)
// storageCmd is the struct representing the top-level storage subcommand.
type storageCmd struct {
Scan storageScanCmd `command:"scan" description:"Scan SCM and NVMe storage attached to remote servers."`
Format storageFormatCmd `command:"format" description:"Format SCM and NVMe storage attached to remote servers."`
Query storageQueryCmd `command:"query" description:"Query storage commands, including raw NVMe SSD device health stats and internal blobstore health info."`
NvmeRebind nvmeRebindCmd `command:"nvme-rebind" description:"Detach NVMe SSD from kernel driver and rebind to userspace driver for use with DAOS."`
NvmeAddDevice nvmeAddDeviceCmd `command:"nvme-add-device" description:"Add a hot-inserted NVMe SSD to a specific engine configuration to enable the new device to be used."`
Set setFaultyCmd `command:"set" description:"Manually set the device state."`
Replace storageReplaceCmd `command:"replace" description:"Replace a storage device that has been hot-removed with a new device."`
Identify storageIdentifyCmd `command:"identify" description:"Blink the status LED on a given VMD device for visual SSD identification."`
}
// storageScanCmd is the struct representing the scan storage subcommand.
type storageScanCmd struct {
baseCmd
ctlInvokerCmd
hostListCmd
jsonOutputCmd
Verbose bool `short:"v" long:"verbose" description:"List SCM & NVMe device details"`
NvmeHealth bool `short:"n" long:"nvme-health" description:"Display NVMe device health statistics"`
NvmeMeta bool `short:"m" long:"nvme-meta" description:"Display server meta data held on NVMe storage"`
}
// Execute is run when storageScanCmd activates.
//
// Runs NVMe and SCM storage scan on all connected servers.
func (cmd *storageScanCmd) Execute(_ []string) error {
if cmd.NvmeHealth && cmd.NvmeMeta {
return errors.New("cannot use --nvme-health and --nvme-meta together")
}
if cmd.Verbose && (cmd.NvmeHealth || cmd.NvmeMeta) {
return errors.New("cannot use --verbose with --nvme-health or --nvme-meta")
}
req := &control.StorageScanReq{
NvmeHealth: cmd.NvmeHealth,
NvmeMeta: cmd.NvmeMeta,
// don't strip nvme details if verbose or health or meta set
NvmeBasic: !(cmd.Verbose || cmd.NvmeHealth || cmd.NvmeMeta),
}
req.SetHostList(cmd.hostlist)
cmd.Debugf("storage scan request: %+v", req)
resp, err := control.StorageScan(context.Background(), cmd.ctlInvoker, req)
if err != nil {
return err
}
cmd.Debugf("storage scan response: %+v", resp.HostStorage)
if cmd.jsonOutputEnabled() {
return cmd.outputJSON(resp, resp.Errors())
}
var outErr strings.Builder
if err := pretty.PrintResponseErrors(resp, &outErr); err != nil {
return err
}
if outErr.Len() > 0 {
cmd.Error(outErr.String())
}
var out strings.Builder
switch {
case cmd.NvmeHealth:
if err := pretty.PrintNvmeHealthMap(resp.HostStorage, &out); err != nil {
return err
}
case cmd.NvmeMeta:
if err := pretty.PrintNvmeMetaMap(resp.HostStorage, &out); err != nil {
return err
}
default:
verbose := pretty.PrintWithVerboseOutput(cmd.Verbose)
if err := pretty.PrintHostStorageMap(resp.HostStorage, &out, verbose); err != nil {
return err
}
}
cmd.Info(out.String())
return resp.Errors()
}
// storageFormatCmd is the struct representing the format storage subcommand.
type storageFormatCmd struct {
baseCmd
ctlInvokerCmd
hostListCmd
jsonOutputCmd
Verbose bool `short:"v" long:"verbose" description:"Show results of each SCM & NVMe device format operation"`
Force bool `long:"force" description:"Force storage format on a host, stopping any running engines (CAUTION: destructive operation)"`
}
// Execute is run when storageFormatCmd activates.
//
// Run NVMe and SCM storage format on all connected servers.
func (cmd *storageFormatCmd) Execute(args []string) (err error) {
ctx := context.Background()
req := &control.StorageFormatReq{Reformat: cmd.Force}
req.SetHostList(cmd.hostlist)
resp, err := control.StorageFormat(ctx, cmd.ctlInvoker, req)
if err != nil {
return err
}
if cmd.jsonOutputEnabled() {
return cmd.outputJSON(resp, resp.Errors())
}
return cmd.printFormatResp(resp)
}
func (cmd *storageFormatCmd) printFormatResp(resp *control.StorageFormatResp) error {
var outErr strings.Builder
if err := pretty.PrintResponseErrors(resp, &outErr); err != nil {
return err
}
if outErr.Len() > 0 {
cmd.Error(outErr.String())
}
var out strings.Builder
verbose := pretty.PrintWithVerboseOutput(cmd.Verbose)
if err := pretty.PrintStorageFormatMap(resp.HostStorage, &out, verbose); err != nil {
return err
}
cmd.Info(out.String())
return resp.Errors()
}
// nvmeRebindCmd is the struct representing the nvme-rebind storage subcommand.
type nvmeRebindCmd struct {
baseCmd
ctlInvokerCmd
hostListCmd
jsonOutputCmd
PCIAddr string `short:"a" long:"pci-address" required:"1" description:"NVMe SSD PCI address to rebind."`
}
// Execute is run when nvmeRebindCmd activates.
//
// Rebind NVMe SSD from kernel driver and bind to user-space driver on single server.
func (cmd *nvmeRebindCmd) Execute(args []string) error {
ctx := context.Background()
if len(cmd.hostlist) != 1 {
return errors.New("command expects a single host in hostlist")
}
req := &control.NvmeRebindReq{PCIAddr: cmd.PCIAddr}
req.SetHostList(cmd.hostlist)
resp, err := control.StorageNvmeRebind(ctx, cmd.ctlInvoker, req)
if err != nil {
return err
}
if cmd.jsonOutputEnabled() {
return cmd.outputJSON(resp, resp.Errors())
}
var outErr strings.Builder
if err := pretty.PrintResponseErrors(resp, &outErr); err != nil {
return err
}
if outErr.Len() > 0 {
cmd.Error(outErr.String())
} else {
cmd.Info("Command completed successfully")
}
return resp.Errors()
}
// nvmeAddDeviceCmd is the struct representing the nvme-add-device storage subcommand.
//
// StorageTierIndex is by default set -1 to signal the server to add the device to the first
// configured bdev tier.
type nvmeAddDeviceCmd struct {
baseCmd
ctlInvokerCmd
hostListCmd
jsonOutputCmd
PCIAddr string `short:"a" long:"pci-address" required:"1" description:"NVMe SSD PCI address to add."`
EngineIndex uint32 `short:"e" long:"engine-index" required:"1" description:"Index of DAOS engine to add NVMe device to."`
StorageTierIndex int32 `short:"t" long:"tier-index" default:"-1" description:"Index of storage tier on DAOS engine to add NVMe device to."`
}
// Execute is run when nvmeAddDeviceCmd activates.
//
// Add recently inserted NVMe SSD to a running engine by updating relevant NVMe config file.
func (cmd *nvmeAddDeviceCmd) Execute(args []string) error { |
if len(cmd.hostlist) != 1 {
return errors.New("command expects a single host in hostlist")
}
req := &control.NvmeAddDeviceReq{
PCIAddr: cmd.PCIAddr,
EngineIndex: cmd.EngineIndex,
StorageTierIndex: cmd.StorageTierIndex,
}
req.SetHostList(cmd.hostlist)
cmd.Debugf("nvme add device req: %+v", req)
resp, err := control.StorageNvmeAddDevice(ctx, cmd.ctlInvoker, req)
if err != nil {
return err
}
if cmd.jsonOutputEnabled() {
return cmd.outputJSON(resp, resp.Errors())
}
var outErr strings.Builder
if err := pretty.PrintResponseErrors(resp, &outErr); err != nil {
return err
}
if outErr.Len() > 0 {
cmd.Error(outErr.String())
} else {
cmd.Info("Command completed successfully")
}
return resp.Errors()
}
// setFaultyCmd is the struct representing the set storage subcommand
type setFaultyCmd struct {
NVMe nvmeSetFaultyCmd `command:"nvme-faulty" description:"Manually set the device state of an NVMe SSD to FAULTY."`
}
// nvmeSetFaultyCmd is the struct representing the set-faulty storage subcommand
type nvmeSetFaultyCmd struct {
smdQueryCmd
UUID string `short:"u" long:"uuid" description:"Device UUID to set" required:"1"`
Force bool `short:"f" long:"force" description:"Do not require confirmation"`
}
// Execute is run when nvmeSetFaultyCmd activates
// Set the SMD device state of the given device to "FAULTY"
func (cmd *nvmeSetFaultyCmd) Execute(_ []string) error {
cmd.Info("WARNING: This command will permanently mark the device as unusable!")
if !cmd.Force {
if cmd.jsonOutputEnabled() {
return errors.New("Cannot use --json without --force")
}
if !common.GetConsent(cmd.Logger) {
return errors.New("consent not given")
}
}
req := &control.SmdQueryReq{
UUID: cmd.UUID,
SetFaulty: true,
}
return cmd.makeRequest(context.Background(), req)
}
// storageReplaceCmd is the struct representing the replace storage subcommand
type storageReplaceCmd struct {
NVMe nvmeReplaceCmd `command:"nvme" description:"Replace an evicted/FAULTY NVMe SSD with another device."`
}
// nvmeReplaceCmd is the struct representing the replace nvme storage subcommand
type nvmeReplaceCmd struct {
smdQueryCmd
OldDevUUID string `long:"old-uuid" description:"Device UUID of hot-removed SSD" required:"1"`
NewDevUUID string `long:"new-uuid" description:"Device UUID of new device" required:"1"`
NoReint bool `long:"no-reint" description:"Bypass reintegration of device and just bring back online."`
}
// Execute is run when storageReplaceCmd activates
// Replace a hot-removed device with a newly plugged device, or reuse a FAULTY device
func (cmd *nvmeReplaceCmd) Execute(_ []string) error {
if cmd.OldDevUUID == cmd.NewDevUUID {
cmd.Info("WARNING: Attempting to reuse a previously set FAULTY device!")
}
// TODO: Implement no-reint flag option
if cmd.NoReint {
cmd.Info("NoReint is not currently implemented")
}
req := &control.SmdQueryReq{
UUID: cmd.OldDevUUID,
ReplaceUUID: cmd.NewDevUUID,
NoReint: cmd.NoReint,
}
return cmd.makeRequest(context.Background(), req)
}
// storageIdentifyCmd is the struct representing the identify storage subcommand.
type storageIdentifyCmd struct {
VMD vmdIdentifyCmd `command:"vmd" description:"Quickly blink the status LED on a VMD NVMe SSD for device identification. Duration of LED event can be configured by setting the VMD_LED_PERIOD environment variable, otherwise default is 60 seconds."`
}
// vmdIdentifyCmd is the struct representing the identify vmd storage subcommand.
type vmdIdentifyCmd struct {
smdQueryCmd
UUID string `long:"uuid" description:"Device UUID of the VMD device to identify" required:"1"`
}
// Execute is run when vmdIdentifyCmd activates.
//
// Runs SPDK VMD API commands to set the LED state on the VMD to "IDENTIFY"
func (cmd *vmdIdentifyCmd) Execute(_ []string) error {
req := &control.SmdQueryReq{
UUID: cmd.UUID,
Identify: true,
}
return cmd.makeRequest(context.Background(), req)
} | ctx := context.Background() |
sql_provider.go | package storage
import (
"database/sql"
"encoding/base64"
"fmt"
"time"
"github.com/authelia/authelia/internal/models"
)
// SQLProvider is a storage provider persisting data in a SQL database.
type SQLProvider struct {
db *sql.DB
sqlCreateUserPreferencesTable string
sqlCreateIdentityVerificationTokensTable string
sqlCreateTOTPSecretsTable string
sqlCreateU2FDeviceHandlesTable string
sqlCreateAuthenticationLogsTable string
sqlCreateAuthenticationLogsUserTimeIndex string
sqlGetPreferencesByUsername string
sqlUpsertSecondFactorPreference string
sqlTestIdentityVerificationTokenExistence string
sqlInsertIdentityVerificationToken string
sqlDeleteIdentityVerificationToken string
sqlGetTOTPSecretByUsername string
sqlUpsertTOTPSecret string
sqlDeleteTOTPSecret string
sqlGetU2FDeviceHandleByUsername string
sqlUpsertU2FDeviceHandle string
sqlInsertAuthenticationLog string
sqlGetLatestAuthenticationLogs string
}
func (p *SQLProvider) initialize(db *sql.DB) error {
p.db = db
_, err := db.Exec(p.sqlCreateUserPreferencesTable)
if err != nil {
return fmt.Errorf("Unable to create table %s: %v", preferencesTableName, err)
}
_, err = db.Exec(p.sqlCreateIdentityVerificationTokensTable)
if err != nil {
return fmt.Errorf("Unable to create table %s: %v", identityVerificationTokensTableName, err)
}
_, err = db.Exec(p.sqlCreateTOTPSecretsTable)
if err != nil {
return fmt.Errorf("Unable to create table %s: %v", totpSecretsTableName, err)
}
// keyHandle and publicKey are stored in base64 format
_, err = db.Exec(p.sqlCreateU2FDeviceHandlesTable)
if err != nil {
return fmt.Errorf("Unable to create table %s: %v", u2fDeviceHandlesTableName, err)
}
_, err = db.Exec(p.sqlCreateAuthenticationLogsTable)
if err != nil {
return fmt.Errorf("Unable to create table %s: %v", authenticationLogsTableName, err)
}
// Create an index on (username, time) because this couple is highly used by the regulation module
// to check whether a user is banned.
if p.sqlCreateAuthenticationLogsUserTimeIndex != "" {
_, err = db.Exec(p.sqlCreateAuthenticationLogsUserTimeIndex)
if err != nil {
return fmt.Errorf("Unable to create table %s: %v", authenticationLogsTableName, err)
}
}
return nil
}
// LoadPreferred2FAMethod load the preferred method for 2FA from sqlite db.
func (p *SQLProvider) LoadPreferred2FAMethod(username string) (string, error) {
var method string
rows, err := p.db.Query(p.sqlGetPreferencesByUsername, username)
if err != nil {
return "", err
}
defer rows.Close()
if !rows.Next() {
return "", nil
}
err = rows.Scan(&method)
return method, err
}
// SavePreferred2FAMethod save the preferred method for 2FA in sqlite db.
func (p *SQLProvider) SavePreferred2FAMethod(username string, method string) error {
_, err := p.db.Exec(p.sqlUpsertSecondFactorPreference, username, method)
return err
}
// FindIdentityVerificationToken look for an identity verification token in DB.
func (p *SQLProvider) FindIdentityVerificationToken(token string) (bool, error) {
var found bool
err := p.db.QueryRow(p.sqlTestIdentityVerificationTokenExistence, token).Scan(&found)
if err != nil {
return false, err
}
return found, nil
}
// SaveIdentityVerificationToken save an identity verification token in DB.
func (p *SQLProvider) SaveIdentityVerificationToken(token string) error {
_, err := p.db.Exec(p.sqlInsertIdentityVerificationToken, token)
return err
}
// RemoveIdentityVerificationToken remove an identity verification token from the DB.
func (p *SQLProvider) RemoveIdentityVerificationToken(token string) error {
_, err := p.db.Exec(p.sqlDeleteIdentityVerificationToken, token)
return err
}
// SaveTOTPSecret save a TOTP secret of a given user.
func (p *SQLProvider) SaveTOTPSecret(username string, secret string) error {
_, err := p.db.Exec(p.sqlUpsertTOTPSecret, username, secret)
return err
}
// LoadTOTPSecret load a TOTP secret given a username.
func (p *SQLProvider) LoadTOTPSecret(username string) (string, error) {
var secret string
if err := p.db.QueryRow(p.sqlGetTOTPSecretByUsername, username).Scan(&secret); err != nil {
if err == sql.ErrNoRows {
return "", ErrNoTOTPSecret
}
return "", err
}
return secret, nil
}
// DeleteTOTPSecret delete a TOTP secret given a username.
func (p *SQLProvider) DeleteTOTPSecret(username string) error {
_, err := p.db.Exec(p.sqlDeleteTOTPSecret, username)
return err
}
// SaveU2FDeviceHandle save a registered U2F device registration blob.
func (p *SQLProvider) SaveU2FDeviceHandle(username string, keyHandle []byte, publicKey []byte) error {
_, err := p.db.Exec(p.sqlUpsertU2FDeviceHandle,
username,
base64.StdEncoding.EncodeToString(keyHandle),
base64.StdEncoding.EncodeToString(publicKey))
return err
}
// LoadU2FDeviceHandle load a U2F device registration blob for a given username.
func (p *SQLProvider) LoadU2FDeviceHandle(username string) ([]byte, []byte, error) {
var keyHandleBase64, publicKeyBase64 string
if err := p.db.QueryRow(p.sqlGetU2FDeviceHandleByUsername, username).Scan(&keyHandleBase64, &publicKeyBase64); err != nil {
if err == sql.ErrNoRows {
return nil, nil, ErrNoU2FDeviceHandle
}
return nil, nil, err
}
keyHandle, err := base64.StdEncoding.DecodeString(keyHandleBase64)
if err != nil |
publicKey, err := base64.StdEncoding.DecodeString(publicKeyBase64)
if err != nil {
return nil, nil, err
}
return keyHandle, publicKey, nil
}
// AppendAuthenticationLog append a mark to the authentication log.
func (p *SQLProvider) AppendAuthenticationLog(attempt models.AuthenticationAttempt) error {
_, err := p.db.Exec(p.sqlInsertAuthenticationLog, attempt.Username, attempt.Successful, attempt.Time.Unix())
return err
}
// LoadLatestAuthenticationLogs retrieve the latest marks from the authentication log.
func (p *SQLProvider) LoadLatestAuthenticationLogs(username string, fromDate time.Time) ([]models.AuthenticationAttempt, error) {
var t int64
rows, err := p.db.Query(p.sqlGetLatestAuthenticationLogs, fromDate.Unix(), username)
if err != nil {
return nil, err
}
attempts := make([]models.AuthenticationAttempt, 0, 10)
for rows.Next() {
attempt := models.AuthenticationAttempt{
Username: username,
}
err = rows.Scan(&attempt.Successful, &t)
attempt.Time = time.Unix(t, 0)
if err != nil {
return nil, err
}
attempts = append(attempts, attempt)
}
return attempts, nil
}
| {
return nil, nil, err
} |
split_demo.rs | // Copyright 2019 The Druid 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.
//! This example demonstrates the `Split` widget
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::piet::Color;
use druid::widget::{Align, Container, Label, Padding, Split};
use druid::{AppLauncher, LocalizedString, Widget, WindowDesc};
fn build_app() -> impl Widget<u32> {
let fixed_cols = Padding::new(
10.0,
Container::new( | Align::centered(Label::new("Right Split")),
)
.split_point(0.5),
)
.border(Color::WHITE, 1.0),
);
let fixed_rows = Padding::new(
10.0,
Container::new(
Split::rows(
Align::centered(Label::new("Top Split")),
Align::centered(Label::new("Bottom Split")),
)
.split_point(0.4)
.bar_size(3.0),
)
.border(Color::WHITE, 1.0),
);
let draggable_cols = Padding::new(
10.0,
Container::new(
Split::columns(
Align::centered(Label::new("Split A")),
Align::centered(Label::new("Split B")),
)
.split_point(0.5)
.draggable(true)
.solid_bar(true)
.min_size(60.0, 60.0),
)
.border(Color::WHITE, 1.0),
);
Padding::new(
10.0,
Container::new(
Split::rows(
Split::rows(fixed_cols, fixed_rows)
.split_point(0.33)
.bar_size(3.0)
.min_bar_area(3.0)
.draggable(true),
draggable_cols,
)
.split_point(0.75)
.bar_size(5.0)
.min_bar_area(11.0)
.draggable(true),
)
.border(Color::WHITE, 1.0),
)
}
pub fn main() {
let window = WindowDesc::new(build_app())
.title(LocalizedString::new("split-demo-window-title").with_placeholder("Split Demo"));
AppLauncher::new()
.with_window(window)
.log_to_console()
.launch(0u32)
.expect("launch failed");
} | Split::columns(
Align::centered(Label::new("Left Split")), |
decode.go | /*
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 candiedyaml
import (
"bytes"
"errors"
"fmt"
"io"
"reflect"
"runtime"
"strconv"
"strings"
)
type Unmarshaler interface {
UnmarshalYAML(tag string, value interface{}) error
}
// A Number represents a JSON number literal.
type Number string
// String returns the literal text of the number.
func (n Number) String() string { return string(n) }
// Float64 returns the number as a float64.
func (n Number) Float64() (float64, error) {
return strconv.ParseFloat(string(n), 64)
}
// Int64 returns the number as an int64.
func (n Number) Int64() (int64, error) {
return strconv.ParseInt(string(n), 10, 64)
}
type Decoder struct {
parser yaml_parser_t
event yaml_event_t
replay_events []yaml_event_t
useNumber bool
mapType reflect.Type
// `strictMode` determines how the decoder should act when a field is encountered
// which cannot be mapped to a field on the struct being decode into.
// When `strictMode` is true, then the decoder errors when such a field is encountered.
// When false, the decoder ignores the field.
strictMode bool
anchors map[string][]yaml_event_t
tracking_anchors [][]yaml_event_t
}
type ParserError struct {
ErrorType YAML_error_type_t
Context string
ContextMark YAML_mark_t
Problem string
ProblemMark YAML_mark_t
}
func (e *ParserError) Error() string {
return fmt.Sprintf("yaml: [%s] %s at line %d, column %d", e.Context, e.Problem, e.ProblemMark.line+1, e.ProblemMark.column+1)
}
type UnexpectedEventError struct {
Value string
EventType yaml_event_type_t
At YAML_mark_t
}
func (e *UnexpectedEventError) Error() string {
return fmt.Sprintf("yaml: Unexpect event [%d]: '%s' at line %d, column %d", e.EventType, e.Value, e.At.line+1, e.At.column+1)
}
func recovery(err *error) {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
var tmpError error
switch r := r.(type) {
case error:
tmpError = r
case string:
tmpError = errors.New(r)
default:
tmpError = errors.New("Unknown panic: " + reflect.ValueOf(r).String())
}
*err = tmpError
}
}
func Unmarshal(data []byte, v interface{}) error |
func NewDecoder(r io.Reader) *Decoder {
d := &Decoder{
anchors: make(map[string][]yaml_event_t),
tracking_anchors: make([][]yaml_event_t, 0),
}
yaml_parser_initialize(&d.parser)
yaml_parser_set_input_reader(&d.parser, r)
return d
}
func (d *Decoder) Decode(v interface{}) (err error) {
defer recovery(&err)
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return fmt.Errorf("Expected a pointer or nil but was a %s at %s", rv.String(), d.event.start_mark)
}
if d.event.event_type == yaml_NO_EVENT {
d.nextEvent()
if d.event.event_type != yaml_STREAM_START_EVENT {
return errors.New("Invalid stream")
}
d.nextEvent()
}
d.document(rv)
return nil
}
func (d *Decoder) UseNumber() { d.useNumber = true }
// StrictMode is used to set the strict mode flag on the decoder.
// When the strict mode is set to true, the decoder should
// error when an unexpected field is encountered.
func (d *Decoder) StrictMode(strict bool) {
d.strictMode = strict
}
func (d *Decoder) error(err error) {
panic(err)
}
func (d *Decoder) nextEvent() {
if d.event.event_type == yaml_STREAM_END_EVENT {
d.error(errors.New("The stream is closed"))
}
if d.replay_events != nil {
d.event = d.replay_events[0]
if len(d.replay_events) == 1 {
d.replay_events = nil
} else {
d.replay_events = d.replay_events[1:]
}
} else {
if !yaml_parser_parse(&d.parser, &d.event) {
yaml_event_delete(&d.event)
d.error(&ParserError{
ErrorType: d.parser.error,
Context: d.parser.context,
ContextMark: d.parser.context_mark,
Problem: d.parser.problem,
ProblemMark: d.parser.problem_mark,
})
}
}
last := len(d.tracking_anchors)
// skip aliases when tracking an anchor
if last > 0 && d.event.event_type != yaml_ALIAS_EVENT {
d.tracking_anchors[last-1] = append(d.tracking_anchors[last-1], d.event)
}
}
func (d *Decoder) document(rv reflect.Value) {
if d.event.event_type != yaml_DOCUMENT_START_EVENT {
d.error(fmt.Errorf("Expected document start at %s", d.event.start_mark))
}
d.nextEvent()
d.parse(rv)
if d.event.event_type != yaml_DOCUMENT_END_EVENT {
d.error(fmt.Errorf("Expected document end at %s", d.event.start_mark))
}
d.nextEvent()
}
func (d *Decoder) parse(rv reflect.Value) {
if !rv.IsValid() {
// skip ahead since we cannot store
d.valueInterface()
return
}
anchor := string(d.event.anchor)
switch d.event.event_type {
case yaml_SEQUENCE_START_EVENT:
d.begin_anchor(anchor)
d.sequence(rv)
d.end_anchor(anchor)
case yaml_MAPPING_START_EVENT:
d.begin_anchor(anchor)
d.mapping(rv)
d.end_anchor(anchor)
case yaml_SCALAR_EVENT:
d.begin_anchor(anchor)
d.scalar(rv)
d.end_anchor(anchor)
case yaml_ALIAS_EVENT:
d.alias(rv)
case yaml_DOCUMENT_END_EVENT:
default:
d.error(&UnexpectedEventError{
Value: string(d.event.value),
EventType: d.event.event_type,
At: d.event.start_mark,
})
}
}
func (d *Decoder) begin_anchor(anchor string) {
if anchor != "" {
events := []yaml_event_t{d.event}
d.tracking_anchors = append(d.tracking_anchors, events)
}
}
func (d *Decoder) end_anchor(anchor string) {
if anchor != "" {
events := d.tracking_anchors[len(d.tracking_anchors)-1]
d.tracking_anchors = d.tracking_anchors[0 : len(d.tracking_anchors)-1]
// remove the anchor, replaying events shouldn't have anchors
events[0].anchor = nil
// we went one too many, remove the extra event
events = events[:len(events)-1]
// if nested, append to all the other anchors
for i, e := range d.tracking_anchors {
d.tracking_anchors[i] = append(e, events...)
}
d.anchors[anchor] = events
}
}
func (d *Decoder) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, reflect.Value) {
// If v is a named type and is addressable,
// start with its address, so that if the type has pointer methods,
// we find them.
if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
v = v.Addr()
}
for {
// Load value from interface, but only if the result will be
// usefully addressable.
if v.Kind() == reflect.Interface && !v.IsNil() {
e := v.Elem()
if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
v = e
continue
}
}
if v.Kind() != reflect.Ptr {
break
}
if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() {
break
}
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
if v.Type().NumMethod() > 0 {
if u, ok := v.Interface().(Unmarshaler); ok {
var temp interface{}
return u, reflect.ValueOf(&temp)
}
}
v = v.Elem()
}
return nil, v
}
func (d *Decoder) sequence(v reflect.Value) {
if d.event.event_type != yaml_SEQUENCE_START_EVENT {
d.error(fmt.Errorf("Expected sequence start at %s", d.event.start_mark))
}
u, pv := d.indirect(v, false)
if u != nil {
defer func() {
if err := u.UnmarshalYAML(yaml_SEQ_TAG, pv.Interface()); err != nil {
d.error(err)
}
}()
_, pv = d.indirect(pv, false)
}
v = pv
// Check type of target.
switch v.Kind() {
case reflect.Interface:
if v.NumMethod() == 0 {
// Decoding into nil interface? Switch to non-reflect code.
v.Set(reflect.ValueOf(d.sequenceInterface()))
return
}
// Otherwise it's invalid.
fallthrough
default:
d.error(fmt.Errorf("Expected an array, slice or interface{} but was a %s at %s", v, d.event.start_mark))
case reflect.Array:
case reflect.Slice:
break
}
d.nextEvent()
i := 0
done:
for {
switch d.event.event_type {
case yaml_SEQUENCE_END_EVENT, yaml_DOCUMENT_END_EVENT:
break done
}
// Get element of array, growing if necessary.
if v.Kind() == reflect.Slice {
// Grow slice if necessary
if i >= v.Cap() {
newcap := v.Cap() + v.Cap()/2
if newcap < 4 {
newcap = 4
}
newv := reflect.MakeSlice(v.Type(), v.Len(), newcap)
reflect.Copy(newv, v)
v.Set(newv)
}
if i >= v.Len() {
v.SetLen(i + 1)
}
}
if i < v.Len() {
// Decode into element.
d.parse(v.Index(i))
} else {
// Ran out of fixed array: skip.
d.parse(reflect.Value{})
}
i++
}
if i < v.Len() {
if v.Kind() == reflect.Array {
// Array. Zero the rest.
z := reflect.Zero(v.Type().Elem())
for ; i < v.Len(); i++ {
v.Index(i).Set(z)
}
} else {
v.SetLen(i)
}
}
if i == 0 && v.Kind() == reflect.Slice {
v.Set(reflect.MakeSlice(v.Type(), 0, 0))
}
if d.event.event_type != yaml_DOCUMENT_END_EVENT {
d.nextEvent()
}
}
func (d *Decoder) mapping(v reflect.Value) {
u, pv := d.indirect(v, false)
if u != nil {
defer func() {
if err := u.UnmarshalYAML(yaml_MAP_TAG, pv.Interface()); err != nil {
d.error(err)
}
}()
_, pv = d.indirect(pv, false)
}
v = pv
// Decoding into nil interface? Switch to non-reflect code.
if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
if d.mapType != nil {
subv := reflect.New(d.mapType).Elem()
d.mappingSlice(subv)
v.Set(subv)
} else {
v.Set(reflect.ValueOf(d.mappingInterface()))
}
return
}
// Check type of target: struct or map[X]Y
switch v.Kind() {
case reflect.Struct:
d.mappingStruct(v)
return
case reflect.Slice:
oldMapType := d.mapType
d.mapType = v.Type()
d.mappingSlice(v)
d.mapType = oldMapType
return
case reflect.Map:
default:
d.error(fmt.Errorf("Expected a struct or map but was a %s at %s ", v, d.event.start_mark))
}
mapt := v.Type()
if v.IsNil() {
v.Set(reflect.MakeMap(mapt))
}
d.nextEvent()
keyt := mapt.Key()
mapElemt := mapt.Elem()
var mapElem reflect.Value
done:
for {
switch d.event.event_type {
case yaml_MAPPING_END_EVENT:
break done
case yaml_DOCUMENT_END_EVENT:
return
}
key := reflect.New(keyt)
d.parse(key.Elem())
if !mapElem.IsValid() {
mapElem = reflect.New(mapElemt).Elem()
} else {
mapElem.Set(reflect.Zero(mapElemt))
}
d.parse(mapElem)
v.SetMapIndex(key.Elem(), mapElem)
}
d.nextEvent()
}
func (d *Decoder) mappingSlice(v reflect.Value) {
structt := v.Type().Elem()
fields := cachedTypeFields(structt)
var nameField *field
var valueField *field
for _, f := range fields {
switch f.name {
case "Key":
tempf := f
nameField = &tempf
case "Value":
tempf := f
valueField = &tempf
}
}
// in this instance, we require that a struct
// with names Key and Value
if nameField == nil || valueField == nil {
d.error(fmt.Errorf("Expected a slice of a struct with fields called 'Key' and 'Value' ", v, d.event.start_mark))
}
d.nextEvent()
i := 0
done:
for {
switch d.event.event_type {
case yaml_MAPPING_END_EVENT:
break done
case yaml_DOCUMENT_END_EVENT:
return
}
// Grow slice if necessary
if i >= v.Cap() {
newcap := v.Cap() + v.Cap()/2
if newcap < 4 {
newcap = 4
}
newv := reflect.MakeSlice(v.Type(), v.Len(), newcap)
reflect.Copy(newv, v)
v.Set(newv)
}
if i >= v.Len() {
v.SetLen(i + 1)
}
subv := reflect.New(structt).Elem()
d.parse(subv.FieldByName(nameField.name))
d.parse(subv.FieldByName(valueField.name))
v.Index(i).Set(subv)
i++
}
v.SetLen(i)
if i == 0 && v.Kind() == reflect.Slice {
v.Set(reflect.MakeSlice(v.Type(), 0, 0))
}
d.nextEvent()
}
func (d *Decoder) mappingStruct(v reflect.Value) {
structt := v.Type()
fields := cachedTypeFields(structt)
d.nextEvent()
done:
for {
switch d.event.event_type {
case yaml_MAPPING_END_EVENT:
break done
case yaml_DOCUMENT_END_EVENT:
return
}
key := ""
d.parse(reflect.ValueOf(&key))
// Figure out field corresponding to key.
var subv reflect.Value
var f *field
for i := range fields {
ff := &fields[i]
if ff.name == key {
f = ff
break
}
if f == nil && strings.EqualFold(ff.name, key) {
f = ff
}
}
if f != nil {
subv = v
for _, i := range f.index {
if subv.Kind() == reflect.Ptr {
if subv.IsNil() {
subv.Set(reflect.New(subv.Type().Elem()))
}
subv = subv.Elem()
}
subv = subv.Field(i)
}
} else if d.strictMode {
d.error(fmt.Errorf("unable to map key %q to a struct field at %v", key, d.event.start_mark))
}
d.parse(subv)
}
d.nextEvent()
}
func (d *Decoder) scalar(v reflect.Value) {
val := string(d.event.value)
wantptr := null_values[val]
u, pv := d.indirect(v, wantptr)
var tag string
if u != nil {
defer func() {
if err := u.UnmarshalYAML(tag, pv.Interface()); err != nil {
d.error(err)
}
}()
_, pv = d.indirect(pv, wantptr)
}
v = pv
var err error
tag, err = resolve(d.event, v, d.useNumber)
if err != nil {
d.error(err)
}
d.nextEvent()
}
func (d *Decoder) alias(rv reflect.Value) {
val, ok := d.anchors[string(d.event.anchor)]
if !ok {
d.error(fmt.Errorf("missing anchor: '%s' at %s", d.event.anchor, d.event.start_mark))
}
d.replay_events = val
d.nextEvent()
d.parse(rv)
}
func (d *Decoder) valueInterface() interface{} {
var v interface{}
anchor := string(d.event.anchor)
switch d.event.event_type {
case yaml_SEQUENCE_START_EVENT:
d.begin_anchor(anchor)
v = d.sequenceInterface()
case yaml_MAPPING_START_EVENT:
d.begin_anchor(anchor)
if d.mapType != nil {
subv := reflect.New(d.mapType).Elem()
d.mappingSlice(subv)
v = subv.Interface()
} else {
v = d.mappingInterface()
}
case yaml_SCALAR_EVENT:
d.begin_anchor(anchor)
v = d.scalarInterface()
case yaml_ALIAS_EVENT:
rv := reflect.ValueOf(&v)
d.alias(rv)
return v
case yaml_DOCUMENT_END_EVENT:
d.error(&UnexpectedEventError{
Value: string(d.event.value),
EventType: d.event.event_type,
At: d.event.start_mark,
})
}
d.end_anchor(anchor)
return v
}
func (d *Decoder) scalarInterface() interface{} {
_, v := resolveInterface(d.event, d.useNumber)
d.nextEvent()
return v
}
// sequenceInterface is like sequence but returns []interface{}.
func (d *Decoder) sequenceInterface() []interface{} {
var v = make([]interface{}, 0)
d.nextEvent()
done:
for {
switch d.event.event_type {
case yaml_SEQUENCE_END_EVENT, yaml_DOCUMENT_END_EVENT:
break done
}
v = append(v, d.valueInterface())
}
if d.event.event_type != yaml_DOCUMENT_END_EVENT {
d.nextEvent()
}
return v
}
// mappingInterface is like mapping but returns map[interface{}]interface{}.
func (d *Decoder) mappingInterface() map[interface{}]interface{} {
m := make(map[interface{}]interface{})
d.nextEvent()
done:
for {
switch d.event.event_type {
case yaml_MAPPING_END_EVENT, yaml_DOCUMENT_END_EVENT:
break done
}
key := d.valueInterface()
// Read value.
m[key] = d.valueInterface()
}
if d.event.event_type != yaml_DOCUMENT_END_EVENT {
d.nextEvent()
}
return m
}
| {
d := NewDecoder(bytes.NewBuffer(data))
return d.Decode(v)
} |
usuarios.component_20200420193538.ts | import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-usuarios',
templateUrl: './usuarios.component.html',
styleUrls: ['./usuarios.component.scss']
})
export class UsuariosComponent implements OnInit {
constructor() { }
ngOnInit() {
} |
} |
|
bitcoin_ro_RO.ts | <TS language="ro_RO" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Click-dreapta pentru a edita adresa sau eticheta</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Creează o adresă nouă</translation>
</message>
<message>
<source>&New</source>
<translation>&Nou</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copiază adresa selectată în clipboard</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Copiază</translation>
</message>
<message>
<source>C&lose</source>
<translation>Închide</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Şterge adresa selectată din listă</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>Introduceţi adresa sau eticheta pentru căutare</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exportă datele din tab-ul curent într-un fişier</translation>
</message>
<message>
<source>&Export</source>
<translation>&Exportă</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Şterge</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Alege $adresa unde să trimiteţi monede</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Alege adresa la care sa primesti monedele cu</translation>
</message>
<message>
<source>C&hoose</source>
<translation>A&lege</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Adresa de trimitere</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Adresa de primire</translation>
</message>
<message>
<source>These are your Tooncoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Acestea sunt adresele tale Tooncoin pentru efectuarea platilor. Intotdeauna verifica atent suma de plata si adresa beneficiarului inainte de a trimite monede.</translation>
</message>
<message>
<source>These are your Tooncoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Acestea sunt adresele tale Tooncoin pentru receptionarea platilor. Este recomandat sa folosesti mereu o adresa noua pentru primirea platilor.</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Copiază Adresa</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Copiaza si eticheteaza</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Editare</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Exportă listă de adrese</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Fisier cu separator virgulă (*.csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Export nereusit</translation>
</message>
<message>
<source>There was an error trying to save the address list to %1. Please try again.</source>
<translation>A apărut o eroare la salvarea listei de adrese la %1. Vă rugăm să încercaţi din nou.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<source>Address</source>
<translation>Adresă</translation>
</message>
<message>
<source>(no label)</source>
<translation>(fără etichetă)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Dialogul pentru fraza de acces</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Introduceţi fraza de acces</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Frază de acces nouă</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Repetaţi noua frază de acces</translation>
</message>
<message>
<source>Show password</source>
<translation>Arata parola</translation>
</message>
<message>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Introduceţi noua parolă a portofelului electronic.<br/>Vă rugăm să folosiţi o parolă de<b>minimum 10 caractere aleatoare</b>, sau <b>minimum 8 cuvinte</b>.</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Criptare portofel</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Această acţiune necesită introducerea parolei de acces pentru deblocarea portofelului.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Deblocare portofel</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Această acţiune necesită introducerea parolei de acces pentru decriptarea portofelului.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Decriptare portofel</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Schimbă parola</translation>
</message>
<message>
<source>Enter the old passphrase and new passphrase to the wallet.</source>
<translation>Introduceţi vechea şi noua parolă pentru portofel.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Confirmaţi criptarea portofelului</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation>Atenţie: Dacă va criptati portofelul si ulterior pierdeti parola, <b>VEŢI PIERDE TOTI LITECOINII</b>!</translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Sigur doriţi să criptaţi portofelul dvs.?</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Portofel criptat</translation>
</message>
<message>
<source>%1 will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your tooncoins from being stolen by malware infecting your computer.</source>
<translation>%1 se va închide acum pentru a termina procesul de criptare. Ţineţi minte că criptarea portofelului nu vă poate proteja în totalitate de furtul monedelor de către programe malware care vă infectează calculatorul.</translation>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT: Orice copie de siguranţă făcută anterior portofelului dumneavoastră ar trebui înlocuită cu cea generată cel mai recent, fişier criptat al portofelului. Pentru siguranţă, copiile de siguranţă vechi ale portofelului ne-criptat vor deveni inutile imediat ce veţi începe folosirea noului fişier criptat al portofelului.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Criptarea portofelului a eşuat.</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Criptarea portofelului nu a reuşit din cauza unei erori interne. Portofelul dvs. nu a fost criptat.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Parolele furnizate nu se potrivesc.</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Deblocarea portofelului a esuat.</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Parola introdusă pentru decriptarea portofelului a fost incorectă.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Decriptarea portofelului a esuat.</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Parola portofelului a fost schimbata.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>Atenţie! Caps Lock este pornit!</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
<message>
<source>IP/Netmask</source>
<translation>IP/Netmask</translation>
</message>
<message>
<source>Banned Until</source>
<translation>Banat până la</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Semnează &mesaj...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Se sincronizează cu reţeaua...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Imagine de ansamblu</translation>
</message>
<message>
<source>Node</source>
<translation>Nod</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Arată o stare generală de ansamblu a portofelului</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Tranzacţii</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Răsfoire istoric tranzacţii</translation>
</message>
<message>
<source>E&xit</source>
<translation>Ieşire</translation>
</message>
<message>
<source>Quit application</source>
<translation>Închide aplicaţia</translation>
</message>
<message>
<source>&About %1</source>
<translation>&Despre %1</translation>
</message>
<message>
<source>Show information about %1</source>
<translation>Arată informaţii despre %1</translation>
</message>
<message>
<source>About &Qt</source>
<translation>Despre &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Arată informaţii despre Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Opţiuni...</translation>
</message>
<message>
<source>Modify configuration options for %1</source>
<translation>Modifică opţiunile de configurare pentru %1</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>Cript&ează portofelul...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>Face o copie de siguranţă a portofelului...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>S&chimbă parola...</translation>
</message>
<message>
<source>&Sending addresses...</source>
<translation>Adrese de trimitere...</translation>
</message>
<message>
<source>&Receiving addresses...</source>
<translation>Adrese de p&rimire...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Deschide &URI...</translation>
</message>
<message>
<source>Wallet:</source>
<translation>Portofel:</translation>
</message>
<message>
<source>default wallet</source>
<translation>portofel implicit</translation>
</message>
<message>
<source>Click to disable network activity.</source>
<translation>Click pentru a opri activitatea retelei.</translation>
</message>
<message>
<source>Network activity disabled.</source>
<translation>Activitatea retelei a fost oprita.</translation>
</message>
<message>
<source>Click to enable network activity again.</source>
<translation>Click pentu a porni activitatea retelei.</translation>
</message>
<message>
<source>Syncing Headers (%1%)...</source>
<translation>Se sincronizeaza Header-ele (%1%)...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Se reindexează blocurile pe disc...</translation>
</message>
<message>
<source>Proxy is <b>enabled</b>: %1</source>
<translation>Proxy este<b>activat</b>:%1</translation>
</message>
<message>
<source>Send coins to a Tooncoin address</source>
<translation>Trimite monede către o adresă Tooncoin</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Creează o copie de rezervă a portofelului într-o locaţie diferită</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Schimbă fraza de acces folosită pentru criptarea portofelului</translation>
</message>
<message>
<source>&Debug window</source>
<translation>Fereastra de &depanare</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Deschide consola de depanare şi diagnosticare</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Verifică mesaj...</translation>
</message>
<message>
<source>Tooncoin</source>
<translation>Tooncoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Portofel</translation>
</message>
<message>
<source>&Send</source>
<translation>Trimite</translation>
</message>
<message>
<source>&Receive</source>
<translation>P&rimeşte</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>Arată/Ascunde</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Arată sau ascunde fereastra principală</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Criptează cheile private ale portofelului dvs.</translation>
</message>
<message>
<source>Sign messages with your Tooncoin addresses to prove you own them</source>
<translation>Semnaţi mesaje cu adresa dvs. Tooncoin pentru a dovedi că vă aparţin</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Tooncoin addresses</source>
<translation>Verificaţi mesaje pentru a vă asigura că au fost semnate cu adresa Tooncoin specificată</translation>
</message>
<message>
<source>&File</source>
<translation>&Fişier</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Setări</translation>
</message>
<message>
<source>&Help</source>
<translation>A&jutor</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Bara de unelte</translation>
</message>
<message>
<source>Request payments (generates QR codes and tooncoin: URIs)</source>
<translation>Cereţi plăţi (generează coduri QR şi tooncoin-uri: URls)</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>Arată lista de adrese trimise şi etichetele folosite.</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>Arată lista de adrese pentru primire şi etichetele</translation>
</message>
<message>
<source>Open a tooncoin: URI or payment request</source>
<translation>Deschidere tooncoin: o adresa URI sau o cerere de plată</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>Opţiuni linie de &comandă</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Tooncoin network</source>
<translation><numerusform>%n conexiune activă către reţeaua Tooncoin</numerusform><numerusform>%n conexiuni active către reţeaua Tooncoin</numerusform><numerusform>%n de conexiuni active către reţeaua Tooncoin</numerusform></translation>
</message>
<message>
<source>Indexing blocks on disk...</source>
<translation>Se indexează blocurile pe disc...</translation>
</message>
<message>
<source>Processing blocks on disk...</source>
<translation>Se proceseaza blocurile pe disc...</translation>
</message>
<message numerus="yes">
<source>Processed %n block(s) of transaction history.</source>
<translation><numerusform>S-a procesat %n bloc din istoricul tranzacţiilor.</numerusform><numerusform>S-au procesat %n blocuri din istoricul tranzacţiilor.</numerusform><numerusform>S-au procesat %n de blocuri din istoricul tranzacţiilor.</numerusform></translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 în urmă</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Ultimul bloc recepţionat a fost generat acum %1.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Tranzacţiile după aceasta nu vor fi vizibile încă.</translation>
</message>
<message>
<source>Error</source>
<translation>Eroare</translation>
</message>
<message>
<source>Warning</source>
<translation>Avertisment</translation>
</message>
<message>
<source>Information</source>
<translation>Informaţie</translation>
</message>
<message>
<source>Up to date</source>
<translation>Actualizat</translation>
</message>
<message>
<source>Show the %1 help message to get a list with possible Tooncoin command-line options</source>
<translation>Arată mesajul de ajutor %1 pentru a obţine o listă cu opţiunile posibile de linii de comandă Tooncoin</translation>
</message>
<message>
<source>%1 client</source>
<translation>Client %1</translation>
</message>
<message>
<source>Connecting to peers...</source>
<translation>Se conecteaza cu alte noduri...</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Se actualizează...</translation>
</message>
<message>
<source>Date: %1
</source>
<translation>Data: %1
</translation>
</message>
<message>
<source>Amount: %1
</source>
<translation>Sumă: %1
</translation>
</message>
<message>
<source>Wallet: %1
</source>
<translation>Portofel: %1
</translation>
</message>
<message>
<source>Type: %1
</source>
<translation>Tip: %1
</translation>
</message>
<message>
<source>Label: %1
</source>
<translation>Etichetă: %1
</translation>
</message>
<message>
<source>Address: %1
</source>
<translation>Adresă: %1
</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Tranzacţie expediată</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Tranzacţie recepţionată</translation>
</message>
<message>
<source>HD key generation is <b>enabled</b></source>
<translation>Generarea de chei HD este <b>activata</b></translation>
</message>
<message>
<source>HD key generation is <b>disabled</b></source>
<translation>Generarea de chei HD este <b>dezactivata</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Portofelul este <b>criptat</b> iar în momentul de faţă este <b>deblocat</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Portofelul este <b>criptat</b> iar în momentul de faţă este <b>blocat</b></translation>
</message>
<message>
<source>A fatal error occurred. Tooncoin can no longer continue safely and will quit.</source>
<translation>A survenit o eroare fatală. Tooncoin nu mai poate continua în siguranţă şi se va opri.</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Coin Selection</source>
<translation>Selectarea monedei</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Cantitate:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Octeţi:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Sumă:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Taxă:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Praf:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>După taxă:</translation>
</message>
<message>
<source>Change:</source>
<translation>Schimb:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>(de)selectare tot</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Mod arbore</translation>
</message>
<message>
<source>List mode</source>
<translation>Mod listă</translation>
</message>
<message>
<source>Amount</source>
<translation>Sumă</translation>
</message>
<message>
<source>Received with label</source>
<translation>Primite cu eticheta</translation>
</message>
<message>
<source>Received with address</source>
<translation>Primite cu adresa</translation>
</message>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Confirmări</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Confirmat</translation>
</message>
<message>
<source>Copy address</source>
<translation>Copiază adresa</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copiază eticheta</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copiază suma</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Copiază ID tranzacţie</translation>
</message>
<message>
<source>Lock unspent</source>
<translation>Blocare necheltuiţi</translation>
</message>
<message>
<source>Unlock unspent</source>
<translation>Deblocare necheltuiţi</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Copiază cantitea</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Copiază taxa</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Copiază după taxă</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Copiază octeţi</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Copiază praf</translation>
</message>
<message>
<source>Copy change</source>
<translation>Copiază rest</translation>
</message>
<message>
<source>yes</source>
<translation>da</translation>
</message>
<message>
<source>no</source>
<translation>nu</translation>
</message>
<message>
<source>This label turns red if any recipient receives an amount smaller than the current dust threshold.</source>
<translation>Această etichetă devine roşie, dacă orice beneficiar primeşte o sumă mai mică decât pragul curent pentru praf.</translation>
</message>
<message>
<source>Can vary +/- %1 satoshi(s) per input.</source>
<translation>Poate varia +/- %1 satoshi pentru fiecare intrare.</translation>
</message>
<message>
<source>(no label)</source> | <translation>restul de la %1 (%2)</translation>
</message>
<message>
<source>(change)</source>
<translation>(rest)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Editează adresa</translation>
</message>
<message>
<source>&Label</source>
<translation>&Etichetă</translation>
</message>
<message>
<source>The label associated with this address list entry</source>
<translation>Eticheta asociată cu această intrare din listă.</translation>
</message>
<message>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation>Adresa asociată cu această adresă din listă. Aceasta poate fi modificată doar pentru adresele de trimitere.</translation>
</message>
<message>
<source>&Address</source>
<translation>&Adresă</translation>
</message>
<message>
<source>New sending address</source>
<translation>Noua adresă de trimitere</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Editează adresa de primire</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Editează adresa de trimitere</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Tooncoin address.</source>
<translation>Adresa introdusă "%1" nu este o adresă Tooncoin validă.</translation>
</message>
<message>
<source>Address "%1" already exists as a receiving address with label "%2" and so cannot be added as a sending address.</source>
<translation>Adresa "%1" exista deja ca si adresa de primire cu eticheta "%2" si deci nu poate fi folosita ca si adresa de trimitere.</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book with label "%2".</source>
<translation>Adresa introdusa "%1" este deja in lista de adrese cu eticheta "%2"</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Portofelul nu a putut fi deblocat.</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Generarea noii chei nu a reuşit.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Va fi creat un nou dosar de date.</translation>
</message>
<message>
<source>name</source>
<translation>nume</translation>
</message>
<message>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>Dosarul deja există. Adaugă %1 dacă intenţionaţi să creaţi un nou dosar aici.</translation>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation>Calea deja există şi nu este un dosar.</translation>
</message>
<message>
<source>Cannot create data directory here.</source>
<translation>Nu se poate crea un dosar de date aici.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>versiunea</translation>
</message>
<message>
<source>(%1-bit)</source>
<translation>(%1-bit)</translation>
</message>
<message>
<source>About %1</source>
<translation>Despre %1</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Opţiuni linie de comandă</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Bun venit</translation>
</message>
<message>
<source>Welcome to %1.</source>
<translation>Bun venit la %1!</translation>
</message>
<message>
<source>As this is the first time the program is launched, you can choose where %1 will store its data.</source>
<translation>Deoarece este prima lansare a programului poți alege unde %1 va stoca datele sale.</translation>
</message>
<message>
<source>When you click OK, %1 will begin to download and process the full %4 block chain (%2GB) starting with the earliest transactions in %3 when %4 initially launched.</source>
<translation>Cand apasati OK, %1 va incepe descarcarea si procesarea intregului %4 blockchain (%2GB) incepand cu cele mai vechi tranzactii din %3 de la lansarea initiala a %4.</translation>
</message>
<message>
<source>This initial synchronisation is very demanding, and may expose hardware problems with your computer that had previously gone unnoticed. Each time you run %1, it will continue downloading where it left off.</source>
<translation>Sincronizarea initiala necesita foarte multe resurse, si poate releva probleme de hardware ale computerului care anterior au trecut neobservate. De fiecare data cand rulati %1, descarcarea va continua de unde a fost intrerupta.</translation>
</message>
<message>
<source>If you have chosen to limit block chain storage (pruning), the historical data must still be downloaded and processed, but will be deleted afterward to keep your disk usage low.</source>
<translation>Daca ati ales o limita pentru capacitatea de stocare a blockchainului (pruning), datele mai vechi tot trebuie sa fie descarcate si procesate, insa vor fi sterse ulterior pentru a reduce utilizarea harddiskului.</translation>
</message>
<message>
<source>Use the default data directory</source>
<translation>Foloseşte dosarul de date implicit</translation>
</message>
<message>
<source>Use a custom data directory:</source>
<translation>Foloseşte un dosar de date personalizat:</translation>
</message>
<message>
<source>Tooncoin</source>
<translation>Tooncoin</translation>
</message>
<message>
<source>At least %1 GB of data will be stored in this directory, and it will grow over time.</source>
<translation>Cel putin %1GB de date vor fi stocate in acest director, si aceasta valoare va creste in timp.</translation>
</message>
<message>
<source>Approximately %1 GB of data will be stored in this directory.</source>
<translation>Aproximativ %1 GB de date vor fi stocate in acest director.</translation>
</message>
<message>
<source>%1 will download and store a copy of the Tooncoin block chain.</source>
<translation>%1 va descarca si stoca o copie a blockchainului Tooncoin</translation>
</message>
<message>
<source>The wallet will also be stored in this directory.</source>
<translation>Portofelul va fi de asemeni stocat in acest director.</translation>
</message>
<message>
<source>Error: Specified data directory "%1" cannot be created.</source>
<translation>Eroare: Directorul datelor specificate "%1" nu poate fi creat.</translation>
</message>
<message>
<source>Error</source>
<translation>Eroare</translation>
</message>
<message numerus="yes">
<source>%n GB of free space available</source>
<translation><numerusform>%n GB de spaţiu liber disponibil</numerusform><numerusform>%n GB de spaţiu liber disponibil</numerusform><numerusform>%n GB de spaţiu liber disponibil</numerusform></translation>
</message>
<message numerus="yes">
<source>(of %n GB needed)</source>
<translation><numerusform>(din %n GB necesar)</numerusform><numerusform>(din %n GB necesari)</numerusform><numerusform>(din %n GB necesari)</numerusform></translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
<message>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<source>Recent transactions may not yet be visible, and therefore your wallet's balance might be incorrect. This information will be correct once your wallet has finished synchronizing with the tooncoin network, as detailed below.</source>
<translation>Tranzactiile recente pot sa nu fie inca vizibile, de aceea balanta portofelului poate fi incorecta. Aceasta informatie va fi corecta de indata ce portofelul va fi complet sincronizat cu reteaua Tooncoin, asa cum este detaliat mai jos.</translation>
</message>
<message>
<source>Attempting to spend tooncoins that are affected by not-yet-displayed transactions will not be accepted by the network.</source>
<translation>Incercarea de a cheltui tooncoini care sunt afectati de tranzactii ce inca nu sunt afisate nu va fi acceptata de retea.</translation>
</message>
<message>
<source>Number of blocks left</source>
<translation>Numarul de blocuri ramase</translation>
</message>
<message>
<source>Unknown...</source>
<translation>Necunoscut...</translation>
</message>
<message>
<source>Last block time</source>
<translation>Data ultimului bloc</translation>
</message>
<message>
<source>Progress</source>
<translation>Progres</translation>
</message>
<message>
<source>Progress increase per hour</source>
<translation>Cresterea progresului per ora</translation>
</message>
<message>
<source>calculating...</source>
<translation>calculeaza...</translation>
</message>
<message>
<source>Estimated time left until synced</source>
<translation>Timp estimat pana la sincronizare</translation>
</message>
<message>
<source>Hide</source>
<translation>Ascunde</translation>
</message>
<message>
<source>Unknown. Syncing Headers (%1)...</source>
<translation>Necunoscut. Se sincronizeaza headerele (%1)...</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation>Deschide URI</translation>
</message>
<message>
<source>Open payment request from URI or file</source>
<translation>Deschideţi cerere de plată prin intermediul adresei URI sau a fişierului</translation>
</message>
<message>
<source>URI:</source>
<translation>URI:</translation>
</message>
<message>
<source>Select payment request file</source>
<translation>Selectaţi fişierul cerere de plată</translation>
</message>
<message>
<source>Select payment request file to open</source>
<translation>Selectati care fisier de cerere de plata va fi deschis</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Opţiuni</translation>
</message>
<message>
<source>&Main</source>
<translation>Principal</translation>
</message>
<message>
<source>Automatically start %1 after logging in to the system.</source>
<translation>Porneşte automat %1 după logarea in sistem.</translation>
</message>
<message>
<source>&Start %1 on system login</source>
<translation>&Porneste %1 la logarea in sistem.</translation>
</message>
<message>
<source>Size of &database cache</source>
<translation>Mărimea bazei de &date cache</translation>
</message>
<message>
<source>MB</source>
<translation>MB</translation>
</message>
<message>
<source>Number of script &verification threads</source>
<translation>Numărul de thread-uri de &verificare</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>Adresa IP a serverului proxy (de exemplu: IPv4: 127.0.0.1 / IPv6: ::1)</translation>
</message>
<message>
<source>Shows if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source>
<translation>Arata daca proxy-ul SOCKS5 furnizat implicit este folosit pentru a gasi parteneri via acest tip de retea.</translation>
</message>
<message>
<source>Use separate SOCKS&5 proxy to reach peers via Tor hidden services:</source>
<translation>Foloseste un proxy SOCKS&5 separat pentru a gasi parteneri via servicii TOR ascunse</translation>
</message>
<message>
<source>Hide the icon from the system tray.</source>
<translation>Ascunde icon-ul din system tray.</translation>
</message>
<message>
<source>&Hide tray icon</source>
<translation>&Ascunde icon-ul din system tray.</translation>
</message>
<message>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source>
<translation>Minimizează fereastra în locul părăsirii programului în momentul închiderii ferestrei. Cînd acestă opţiune e activă, aplicaţia se va opri doar în momentul selectării comenzii 'Închide aplicaţia' din menu.</translation>
</message>
<message>
<source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source>
<translation>URL-uri terţe părţi (de exemplu, un explorator de bloc), care apar în tab-ul tranzacţiilor ca elemente de meniu contextual. %s în URL este înlocuit cu hash de tranzacţie. URL-urile multiple sînt separate prin bară verticală |.</translation>
</message>
<message>
<source>Active command-line options that override above options:</source>
<translation>Opţiuni linie de comandă active care oprimă opţiunile de mai sus:</translation>
</message>
<message>
<source>Open the %1 configuration file from the working directory.</source>
<translation>Deschide fisierul de configurare %1 din directorul curent.</translation>
</message>
<message>
<source>Open Configuration File</source>
<translation>Deschide fisierul de configurare.</translation>
</message>
<message>
<source>Reset all client options to default.</source>
<translation>Resetează toate setările clientului la valorile implicite.</translation>
</message>
<message>
<source>&Reset Options</source>
<translation>&Resetează opţiunile</translation>
</message>
<message>
<source>&Network</source>
<translation>Reţea</translation>
</message>
<message>
<source>(0 = auto, <0 = leave that many cores free)</source>
<translation>(0 = automat, <0 = lasă atîtea nuclee libere)</translation>
</message>
<message>
<source>W&allet</source>
<translation>Portofel</translation>
</message>
<message>
<source>Expert</source>
<translation>Expert</translation>
</message>
<message>
<source>Enable coin &control features</source>
<translation>Activare caracteristici de control ale monedei</translation>
</message>
<message>
<source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source>
<translation>Dacă dezactivaţi cheltuirea restului neconfirmat, restul dintr-o tranzacţie nu poate fi folosit pînă cînd tranzacţia are cel puţin o confirmare. Aceasta afectează de asemenea calcularea soldului.</translation>
</message>
<message>
<source>&Spend unconfirmed change</source>
<translation>Cheltuire rest neconfirmat</translation>
</message>
<message>
<source>Automatically open the Tooncoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Deschide automat în router portul aferent clientului Tooncoin. Funcţionează doar dacă routerul duportă UPnP şi e activat.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>Mapare port folosind &UPnP</translation>
</message>
<message>
<source>Accept connections from outside.</source>
<translation>Acceptă conexiuni din exterior</translation>
</message>
<message>
<source>Allow incomin&g connections</source>
<translation>Permite conexiuni de intrar&e</translation>
</message>
<message>
<source>Connect to the Tooncoin network through a SOCKS5 proxy.</source>
<translation>Conectare la reţeaua Tooncoin printr-un proxy SOCKS.</translation>
</message>
<message>
<source>&Connect through SOCKS5 proxy (default proxy):</source>
<translation>&Conectare printr-un proxy SOCKS (implicit proxy):</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Portul proxy (de exemplu: 9050)</translation>
</message>
<message>
<source>Used for reaching peers via:</source>
<translation>Folosit pentru a gasi parteneri via:</translation>
</message>
<message>
<source>IPv4</source>
<translation>IPv4</translation>
</message>
<message>
<source>IPv6</source>
<translation>IPv6</translation>
</message>
<message>
<source>Tor</source>
<translation>Tor</translation>
</message>
<message>
<source>Connect to the Tooncoin network through a separate SOCKS5 proxy for Tor hidden services.</source>
<translation>Conectare la reteaua Tooncoin printr-un proxy SOCKS5 separat pentru serviciile TOR ascunse.</translation>
</message>
<message>
<source>&Window</source>
<translation>&Fereastră</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Arată doar un icon în tray la ascunderea ferestrei</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizare în tray în loc de taskbar</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>M&inimizare fereastră în locul închiderii programului</translation>
</message>
<message>
<source>&Display</source>
<translation>&Afişare</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>&Limbă interfaţă utilizator</translation>
</message>
<message>
<source>The user interface language can be set here. This setting will take effect after restarting %1.</source>
<translation>Limba interfeţei utilizatorului poate fi setată aici. Această setare va avea efect după repornirea %1.</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>&Unitatea de măsură pentru afişarea sumelor:</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Alegeţi subdiviziunea folosită la afişarea interfeţei şi la trimiterea de tooncoin.</translation>
</message>
<message>
<source>Whether to show coin control features or not.</source>
<translation>Arată controlul caracteristicilor monedei sau nu.</translation>
</message>
<message>
<source>&Third party transaction URLs</source>
<translation>URL-uri tranzacţii &terţe părţi</translation>
</message>
<message>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<source>&Cancel</source>
<translation>Renunţă</translation>
</message>
<message>
<source>default</source>
<translation>iniţial</translation>
</message>
<message>
<source>none</source>
<translation>nimic</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Confirmă resetarea opţiunilor</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>Este necesară repornirea clientului pentru a activa schimbările.</translation>
</message>
<message>
<source>Client will be shut down. Do you want to proceed?</source>
<translation>Clientul va fi închis. Doriţi să continuaţi?</translation>
</message>
<message>
<source>Configuration options</source>
<translation>Optiuni de configurare</translation>
</message>
<message>
<source>The configuration file is used to specify advanced user options which override GUI settings. Additionally, any command-line options will override this configuration file.</source>
<translation>Fisierul de configurare e folosit pentru a specifica optiuni utilizator avansate care modifica setarile din GUI. In plus orice optiune din linia de comanda va modifica acest fisier de configurare. </translation>
</message>
<message>
<source>Error</source>
<translation>Eroare</translation>
</message>
<message>
<source>The configuration file could not be opened.</source>
<translation>Fisierul de configurare nu a putut fi deschis.</translation>
</message>
<message>
<source>This change would require a client restart.</source>
<translation>Această schimbare necesită o repornire a clientului.</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>Adresa tooncoin pe care aţi specificat-o nu este validă.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Tooncoin network after a connection is established, but this process has not completed yet.</source>
<translation>Informaţiile afişate pot fi neactualizate. Portofelul dvs. se sincronizează automat cu reţeaua Tooncoin după ce o conexiune este stabilită, dar acest proces nu a fost finalizat încă.</translation>
</message>
<message>
<source>Watch-only:</source>
<translation>Doar-supraveghere:</translation>
</message>
<message>
<source>Available:</source>
<translation>Disponibil:</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>Balanţa dvs. curentă de cheltuieli</translation>
</message>
<message>
<source>Pending:</source>
<translation>În aşteptare:</translation>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>Totalul tranzacţiilor care nu sunt confirmate încă şi care nu sunt încă adunate la balanţa de cheltuieli</translation>
</message>
<message>
<source>Immature:</source>
<translation>Nematurizat:</translation>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation>Balanţa minata ce nu s-a maturizat încă</translation>
</message>
<message>
<source>Balances</source>
<translation>Balanţă</translation>
</message>
<message>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>Balanţa totală curentă</translation>
</message>
<message>
<source>Your current balance in watch-only addresses</source>
<translation>Soldul dvs. curent în adresele doar-supraveghere</translation>
</message>
<message>
<source>Spendable:</source>
<translation>Cheltuibil:</translation>
</message>
<message>
<source>Recent transactions</source>
<translation>Tranzacţii recente</translation>
</message>
<message>
<source>Unconfirmed transactions to watch-only addresses</source>
<translation>Tranzacţii neconfirmate la adresele doar-supraveghere</translation>
</message>
<message>
<source>Mined balance in watch-only addresses that has not yet matured</source>
<translation>Balanţă minată în adresele doar-supraveghere care nu s-a maturizat încă</translation>
</message>
<message>
<source>Current total balance in watch-only addresses</source>
<translation>Soldul dvs. total în adresele doar-supraveghere</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<source>Payment request error</source>
<translation>Eroare la cererea de plată</translation>
</message>
<message>
<source>Cannot start tooncoin: click-to-pay handler</source>
<translation>Tooncoin nu poate porni: click-to-pay handler</translation>
</message>
<message>
<source>URI handling</source>
<translation>Gestionare URI</translation>
</message>
<message>
<source>Payment request fetch URL is invalid: %1</source>
<translation>URL-ul cererii de plată preluat nu este valid: %1</translation>
</message>
<message>
<source>Invalid payment address %1</source>
<translation>Adresă pentru plată invalidă %1</translation>
</message>
<message>
<source>URI cannot be parsed! This can be caused by an invalid Tooncoin address or malformed URI parameters.</source>
<translation>URI nu poate fi analizat! Acest lucru poate fi cauzat de o adresă Tooncoin invalidă sau parametri URI deformaţi.</translation>
</message>
<message>
<source>Payment request file handling</source>
<translation>Manipulare fişier cerere de plată</translation>
</message>
<message>
<source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source>
<translation>Fişierul cerere de plată nu poate fi citit! Cauza poate fi un fişier cerere de plată nevalid.</translation>
</message>
<message>
<source>Payment request rejected</source>
<translation>Cerere de plată refuzată</translation>
</message>
<message>
<source>Payment request network doesn't match client network.</source>
<translation>Cererea de plată din reţea nu se potriveşte cu clientul din reţea</translation>
</message>
<message>
<source>Payment request expired.</source>
<translation>Cerere de plată expirata</translation>
</message>
<message>
<source>Payment request is not initialized.</source>
<translation>Cererea de plată nu este iniţializată.</translation>
</message>
<message>
<source>Unverified payment requests to custom payment scripts are unsupported.</source>
<translation>Cererile nesecurizate către scripturi personalizate de plăți nu sunt suportate</translation>
</message>
<message>
<source>Invalid payment request.</source>
<translation>Cerere de plată invalidă.</translation>
</message>
<message>
<source>Requested payment amount of %1 is too small (considered dust).</source>
<translation>Suma cerută de plată de %1 este prea mică (considerată praf).</translation>
</message>
<message>
<source>Refund from %1</source>
<translation>Rambursare de la %1</translation>
</message>
<message>
<source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source>
<translation>Cererea de plată %1 este prea mare (%2 octeţi, permis %3 octeţi).</translation>
</message>
<message>
<source>Error communicating with %1: %2</source>
<translation>Eroare la comunicarea cu %1: %2</translation>
</message>
<message>
<source>Payment request cannot be parsed!</source>
<translation>Cererea de plată nu poate fi analizată!</translation>
</message>
<message>
<source>Bad response from server %1</source>
<translation>Răspuns greşit de la server %1</translation>
</message>
<message>
<source>Network request error</source>
<translation>Eroare în cererea de reţea</translation>
</message>
<message>
<source>Payment acknowledged</source>
<translation>Plată acceptată</translation>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>User Agent</source>
<translation>Agent utilizator</translation>
</message>
<message>
<source>Node/Service</source>
<translation>Nod/Serviciu</translation>
</message>
<message>
<source>NodeId</source>
<translation>NodeID</translation>
</message>
<message>
<source>Ping</source>
<translation>Ping</translation>
</message>
<message>
<source>Sent</source>
<translation>Expediat</translation>
</message>
<message>
<source>Received</source>
<translation>Recepţionat</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Cantitate</translation>
</message>
<message>
<source>Enter a Tooncoin address (e.g. %1)</source>
<translation>Introduceţi o adresă Tooncoin (de exemplu %1)</translation>
</message>
<message>
<source>%1 d</source>
<translation>%1 z</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 h</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 m</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 s</translation>
</message>
<message>
<source>None</source>
<translation>Niciuna</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>%1 ms</source>
<translation>%1 ms</translation>
</message>
<message numerus="yes">
<source>%n second(s)</source>
<translation><numerusform>%n secunda</numerusform><numerusform>%n secunde</numerusform><numerusform>%n secunde</numerusform></translation>
</message>
<message numerus="yes">
<source>%n minute(s)</source>
<translation><numerusform>%n minut</numerusform><numerusform>%n minute</numerusform><numerusform>%n minute</numerusform></translation>
</message>
<message numerus="yes">
<source>%n hour(s)</source>
<translation><numerusform>%n ora</numerusform><numerusform>%n ore</numerusform><numerusform>%n ore</numerusform></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation><numerusform>%n zi</numerusform><numerusform>%n zile</numerusform><numerusform>%n zile</numerusform></translation>
</message>
<message numerus="yes">
<source>%n week(s)</source>
<translation><numerusform>%n saptamana</numerusform><numerusform>%n saptamani</numerusform><numerusform>%n saptamani</numerusform></translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 şi %2</translation>
</message>
<message numerus="yes">
<source>%n year(s)</source>
<translation><numerusform>%n an</numerusform><numerusform>%n ani</numerusform><numerusform>%n ani</numerusform></translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<source>%1 didn't yet exit safely...</source>
<translation>%1 nu a fost inchis in siguranta...</translation>
</message>
<message>
<source>unknown</source>
<translation>necunoscut</translation>
</message>
</context>
<context>
<name>QObject::QObject</name>
<message>
<source>Error: Specified data directory "%1" does not exist.</source>
<translation>Eroare: Directorul de date specificat "%1" nu există.</translation>
</message>
<message>
<source>Error: %1</source>
<translation>Eroare: %1</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>&Save Image...</source>
<translation>&Salvează Imaginea...</translation>
</message>
<message>
<source>&Copy Image</source>
<translation>&Copiaza Imaginea</translation>
</message>
<message>
<source>Save QR Code</source>
<translation>Salvează codul QR</translation>
</message>
<message>
<source>PNG Image (*.png)</source>
<translation>Imagine de tip PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>Nespecificat</translation>
</message>
<message>
<source>Client version</source>
<translation>Versiune client</translation>
</message>
<message>
<source>&Information</source>
<translation>&Informaţii</translation>
</message>
<message>
<source>Debug window</source>
<translation>Fereastra de depanare</translation>
</message>
<message>
<source>General</source>
<translation>General</translation>
</message>
<message>
<source>Using BerkeleyDB version</source>
<translation>Foloseşte BerkeleyDB versiunea</translation>
</message>
<message>
<source>Datadir</source>
<translation>Dirdate</translation>
</message>
<message>
<source>Startup time</source>
<translation>Ora de pornire</translation>
</message>
<message>
<source>Network</source>
<translation>Reţea</translation>
</message>
<message>
<source>Name</source>
<translation>Nume</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Numărul de conexiuni</translation>
</message>
<message>
<source>Block chain</source>
<translation>Lanţ de blocuri</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Numărul curent de blocuri</translation>
</message>
<message>
<source>Memory Pool</source>
<translation>Pool Memorie</translation>
</message>
<message>
<source>Current number of transactions</source>
<translation>Numărul curent de tranzacţii</translation>
</message>
<message>
<source>Memory usage</source>
<translation>Memorie folosită</translation>
</message>
<message>
<source>&Reset</source>
<translation>&Resetare</translation>
</message>
<message>
<source>Received</source>
<translation>Recepţionat</translation>
</message>
<message>
<source>Sent</source>
<translation>Expediat</translation>
</message>
<message>
<source>&Peers</source>
<translation>&Parteneri</translation>
</message>
<message>
<source>Banned peers</source>
<translation>Terti banati</translation>
</message>
<message>
<source>Select a peer to view detailed information.</source>
<translation>Selectaţi un partener pentru a vedea informaţiile detaliate.</translation>
</message>
<message>
<source>Whitelisted</source>
<translation>Whitelisted</translation>
</message>
<message>
<source>Direction</source>
<translation>Direcţie</translation>
</message>
<message>
<source>Version</source>
<translation>Versiune</translation>
</message>
<message>
<source>Starting Block</source>
<translation>Bloc de început</translation>
</message>
<message>
<source>Synced Headers</source>
<translation>Headere Sincronizate</translation>
</message>
<message>
<source>Synced Blocks</source>
<translation>Blocuri Sincronizate</translation>
</message>
<message>
<source>User Agent</source>
<translation>Agent utilizator</translation>
</message>
<message>
<source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Deschide fişierul jurnal depanare %1 din directorul curent. Aceasta poate dura cateva secunde pentru fişierele mai mari.</translation>
</message>
<message>
<source>Decrease font size</source>
<translation>Micsoreaza fontul</translation>
</message>
<message>
<source>Increase font size</source>
<translation>Mareste fontul</translation>
</message>
<message>
<source>Services</source>
<translation>Servicii</translation>
</message>
<message>
<source>Ban Score</source>
<translation>Scor Ban</translation>
</message>
<message>
<source>Connection Time</source>
<translation>Timp conexiune</translation>
</message>
<message>
<source>Last Send</source>
<translation>Ultima trimitere</translation>
</message>
<message>
<source>Last Receive</source>
<translation>Ultima primire</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Timp ping</translation>
</message>
<message>
<source>The duration of a currently outstanding ping.</source>
<translation>Durata ping-ului intarziat.</translation>
</message>
<message>
<source>Ping Wait</source>
<translation>Asteptare ping</translation>
</message>
<message>
<source>Min Ping</source>
<translation>Min Ping</translation>
</message>
<message>
<source>Time Offset</source>
<translation>Diferenta timp</translation>
</message>
<message>
<source>Last block time</source>
<translation>Data ultimului bloc</translation>
</message>
<message>
<source>&Open</source>
<translation>&Deschide</translation>
</message>
<message>
<source>&Console</source>
<translation>&Consolă</translation>
</message>
<message>
<source>&Network Traffic</source>
<translation>Trafic reţea</translation>
</message>
<message>
<source>Totals</source>
<translation>Totaluri</translation>
</message>
<message>
<source>In:</source>
<translation>Intrare:</translation>
</message>
<message>
<source>Out:</source>
<translation>Ieşire:</translation>
</message>
<message>
<source>Debug log file</source>
<translation>Fişier jurnal depanare</translation>
</message>
<message>
<source>Clear console</source>
<translation>Curăţă consola</translation>
</message>
<message>
<source>1 &hour</source>
<translation>1 &oră</translation>
</message>
<message>
<source>1 &day</source>
<translation>1 &zi</translation>
</message>
<message>
<source>1 &week</source>
<translation>1 &săptămână</translation>
</message>
<message>
<source>1 &year</source>
<translation>1 &an</translation>
</message>
<message>
<source>&Disconnect</source>
<translation>&Deconectare</translation>
</message>
<message>
<source>Ban for</source>
<translation>Interzicere pentru</translation>
</message>
<message>
<source>&Unban</source>
<translation>&Unban</translation>
</message>
<message>
<source>default wallet</source>
<translation>portofel implicit</translation>
</message>
<message>
<source>Welcome to the %1 RPC console.</source>
<translation>Bun venit la consola %1 RPC.</translation>
</message>
<message>
<source>Use up and down arrows to navigate history, and %1 to clear screen.</source>
<translation>Folosiţi săgetile sus şi jos pentru a naviga în istoric şi %1 pentru a curăţa ecranul.</translation>
</message>
<message>
<source>Type %1 for an overview of available commands.</source>
<translation>Tastati %1 pentru o recapitulare a comenzilor disponibile.</translation>
</message>
<message>
<source>For more information on using this console type %1.</source>
<translation>Pentru mai multe informatii despre folosirea acestei console tastati %1.</translation>
</message>
<message>
<source>WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.</source>
<translation>ATENTIONARE: Sunt excroci care instruiesc userii sa introduca aici comenzi, pentru a le fura continutul portofelelor. Nu folositi aceasta consolă fara a intelege pe deplin ramificatiile unei comenzi.</translation>
</message>
<message>
<source>Network activity disabled</source>
<translation>Activitatea retelei a fost oprita.</translation>
</message>
<message>
<source>(node id: %1)</source>
<translation>(node id: %1)</translation>
</message>
<message>
<source>via %1</source>
<translation>via %1</translation>
</message>
<message>
<source>never</source>
<translation>niciodată</translation>
</message>
<message>
<source>Inbound</source>
<translation>Intrare</translation>
</message>
<message>
<source>Outbound</source>
<translation>Ieşire</translation>
</message>
<message>
<source>Yes</source>
<translation>Da</translation>
</message>
<message>
<source>No</source>
<translation>Nu</translation>
</message>
<message>
<source>Unknown</source>
<translation>Necunoscut</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>Sum&a:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Etichetă:</translation>
</message>
<message>
<source>&Message:</source>
<translation>&Mesaj:</translation>
</message>
<message>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Tooncoin network.</source>
<translation>Un mesaj opţional de ataşat la cererea de plată, care va fi afişat cînd cererea este deschisă. Notă: Acest mesaj nu va fi trimis cu plata către reţeaua Tooncoin.</translation>
</message>
<message>
<source>An optional label to associate with the new receiving address.</source>
<translation>O etichetă opţională de asociat cu adresa de primire.</translation>
</message>
<message>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation>Foloseşte acest formular pentru a solicita plăţi. Toate cîmpurile sînt <b>opţionale</b>.</translation>
</message>
<message>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation>O sumă opţională de cerut. Lăsaţi gol sau zero pentru a nu cere o sumă anume.</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Curăţă toate cîmpurile formularului.</translation>
</message>
<message>
<source>Clear</source>
<translation>Curăţă</translation>
</message>
<message>
<source>Native segwit addresses (aka Bech32 or BIP-173) reduce your transaction fees later on and offer better protection against typos, but old wallets don't support them. When unchecked, an address compatible with older wallets will be created instead.</source>
<translation>Adresele native segwit (aka Bech32 sau BIP-173) vor reduce mai tarziu comisioanele de tranzactionare si vor oferi o mai buna protectie impotriva introducerii gresite, dar portofelele vechi nu sunt compatibile. Daca optiunea nu e bifata, se va crea o adresa compatibila cu portofelele vechi.</translation>
</message>
<message>
<source>Generate native segwit (Bech32) address</source>
<translation>Genereaza adresa nativa segwit (Bech32)</translation>
</message>
<message>
<source>Requested payments history</source>
<translation>Istoricul plăţilor cerute</translation>
</message>
<message>
<source>&Request payment</source>
<translation>&Cerere plată</translation>
</message>
<message>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation>Arată cererea selectată (acelaşi lucru ca şi dublu-clic pe o înregistrare)</translation>
</message>
<message>
<source>Show</source>
<translation>Arată</translation>
</message>
<message>
<source>Remove the selected entries from the list</source>
<translation>Înlătură intrările selectate din listă</translation>
</message>
<message>
<source>Remove</source>
<translation>Înlătură</translation>
</message>
<message>
<source>Copy URI</source>
<translation>Copiază URl</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copiază eticheta</translation>
</message>
<message>
<source>Copy message</source>
<translation>Copiază mesajul</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copiază suma</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>Cod QR</translation>
</message>
<message>
<source>Copy &URI</source>
<translation>Copiază &URl</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>Copiază &adresa</translation>
</message>
<message>
<source>&Save Image...</source>
<translation>&Salvează imaginea...</translation>
</message>
<message>
<source>Request payment to %1</source>
<translation>Cere plata pentru %1</translation>
</message>
<message>
<source>Payment information</source>
<translation>Informaţiile plată</translation>
</message>
<message>
<source>URI</source>
<translation>URI</translation>
</message>
<message>
<source>Address</source>
<translation>Adresă</translation>
</message>
<message>
<source>Amount</source>
<translation>Cantitate</translation>
</message>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<source>Message</source>
<translation>Mesaj</translation>
</message>
<message>
<source>Wallet</source>
<translation>Portofel</translation>
</message>
<message>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI rezultat este prea lung, încearcă să reduci textul pentru etichetă / mesaj.</translation>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation>Eroare la codarea URl-ului în cod QR.</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<source>Message</source>
<translation>Mesaj</translation>
</message>
<message>
<source>(no label)</source>
<translation>(fără etichetă)</translation>
</message>
<message>
<source>(no message)</source>
<translation>(nici un mesaj)</translation>
</message>
<message>
<source>(no amount requested)</source>
<translation>(nici o sumă solicitată)</translation>
</message>
<message>
<source>Requested</source>
<translation>Ceruta</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Trimite monede</translation>
</message>
<message>
<source>Coin Control Features</source>
<translation>Caracteristici de control ale monedei</translation>
</message>
<message>
<source>Inputs...</source>
<translation>Intrări...</translation>
</message>
<message>
<source>automatically selected</source>
<translation>selecţie automată</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Fonduri insuficiente!</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Cantitate:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Octeţi:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Sumă:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Comision:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>După taxă:</translation>
</message>
<message>
<source>Change:</source>
<translation>Rest:</translation>
</message>
<message>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation>Dacă este activat, dar adresa de rest este goală sau nevalidă, restul va fi trimis la o adresă nou generată.</translation>
</message>
<message>
<source>Custom change address</source>
<translation>Adresă personalizată de rest</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Taxă tranzacţie:</translation>
</message>
<message>
<source>Choose...</source>
<translation>Alegeţi...</translation>
</message>
<message>
<source>Using the fallbackfee can result in sending a transaction that will take several hours or days (or never) to confirm. Consider choosing your fee manually or wait until you have validated the complete chain.</source>
<translation>Folosirea taxei implicite poate rezulta in trimiterea unei tranzactii care va dura cateva ore sau zile (sau niciodata) pentru a fi confirmata. Luati in considerare sa setati manual taxa sau asteptati pana ati validat complet lantul.</translation>
</message>
<message>
<source>Warning: Fee estimation is currently not possible.</source>
<translation>Avertisment: Estimarea comisionului nu s-a putut efectua.</translation>
</message>
<message>
<source>collapse fee-settings</source>
<translation>inchide setarile de taxare</translation>
</message>
<message>
<source>per kilobyte</source>
<translation>per kilooctet</translation>
</message>
<message>
<source>Hide</source>
<translation>Ascunde</translation>
</message>
<message>
<source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for tooncoin transactions than the network can process.</source>
<translation>Plata unei taxe minime de tranzactie este in regula atata timp cat exista mai mult spatiu in blocuri dacat sunt tranzactii. Insa trebuie sa fiti constienti ca acest lucru poate conduce la tranzactii care nu vor fi niciodata confirmate in cazul in care exista cerere de tranzactii mai mare decat poate procesa reteaua.</translation>
</message>
<message>
<source>(read the tooltip)</source>
<translation>(citeste tooltip)</translation>
</message>
<message>
<source>Recommended:</source>
<translation>Recomandat:</translation>
</message>
<message>
<source>Custom:</source>
<translation>Personalizat:</translation>
</message>
<message>
<source>(Smart fee not initialized yet. This usually takes a few blocks...)</source>
<translation>(Taxa smart nu este inca initializata. Aceasta poate dura cateva blocuri...)</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Trimite simultan către mai mulţi destinatari</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>Adaugă destinata&r</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Şterge toate câmpurile formularului.</translation>
</message>
<message>
<source>Dust:</source>
<translation>Praf:</translation>
</message>
<message>
<source>Confirmation time target:</source>
<translation>Timp confirmare tinta:</translation>
</message>
<message>
<source>Enable Replace-By-Fee</source>
<translation>Autorizeaza Replace-By-Fee</translation>
</message>
<message>
<source>With Replace-By-Fee (BIP-125) you can increase a transaction's fee after it is sent. Without this, a higher fee may be recommended to compensate for increased transaction delay risk.</source>
<translation>Cu Replace-By-Fee (BIP-125) se poate creste taxa unei tranzactii dupa ce a fost trimisa. Fara aceasta optiune, o taxa mai mare e posibil sa fie recomandata pentru a compensa riscul crescut de intarziere a tranzactiei.</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Curăţă to&ate</translation>
</message>
<message>
<source>Balance:</source>
<translation>Balanţă:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Confirmă operaţiunea de trimitere</translation>
</message>
<message>
<source>S&end</source>
<translation>Trimit&e</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Copiază cantitea</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copiază suma</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Copiază taxa</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Copiază după taxă</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Copiază octeţi</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Copiază praf</translation>
</message>
<message>
<source>Copy change</source>
<translation>Copiază rest</translation>
</message>
<message>
<source>%1 (%2 blocks)</source>
<translation>%1(%2 blocuri)</translation>
</message>
<message>
<source>%1 to %2</source>
<translation>%1 la %2</translation>
</message>
<message>
<source>Are you sure you want to send?</source>
<translation>Sigur doriţi să trimiteţi?</translation>
</message>
<message>
<source>or</source>
<translation>sau</translation>
</message>
<message>
<source>You can increase the fee later (signals Replace-By-Fee, BIP-125).</source>
<translation>Puteti creste taxa mai tarziu (semnaleaza Replace-By-Fee, BIP-125).</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Taxă tranzacţie</translation>
</message>
<message>
<source>Not signalling Replace-By-Fee, BIP-125.</source>
<translation>Nu se semnalizeaza Replace-By-Fee, BIP-125</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Confirmă trimiterea monedelor</translation>
</message>
<message>
<source>The recipient address is not valid. Please recheck.</source>
<translation>Adresa destinatarului nu este validă. Rugăm să reverificaţi.</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>Suma de plată trebuie să fie mai mare decît 0.</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>Suma depăşeşte soldul contului.</translation>
</message>
<message>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totalul depăşeşte soldul contului dacă se include şi plata taxei de %1.</translation>
</message>
<message>
<source>Duplicate address found: addresses should only be used once each.</source>
<translation>Adresă duplicat găsită: fiecare adresă ar trebui folosită o singură dată.</translation>
</message>
<message>
<source>Transaction creation failed!</source>
<translation>Creare tranzacţie nereuşită!</translation>
</message>
<message>
<source>The transaction was rejected with the following reason: %1</source>
<translation>Tranzactia a fost refuzata pentru urmatorul motiv: %1</translation>
</message>
<message>
<source>A fee higher than %1 is considered an absurdly high fee.</source>
<translation> O taxă mai mare de %1 este considerată o taxă absurd de mare </translation>
</message>
<message>
<source>Payment request expired.</source>
<translation>Cerere de plată expirata</translation>
</message>
<message>
<source>Pay only the required fee of %1</source>
<translation>Plăteşte doar taxa solicitata de %1</translation>
</message>
<message numerus="yes">
<source>Estimated to begin confirmation within %n block(s).</source>
<translation><numerusform>Se estimeaza inceperea confirmarii in %n bloc.</numerusform><numerusform>Se estimeaza inceperea confirmarii in %n blocuri.</numerusform><numerusform>Se estimeaza inceperea confirmarii in %n blocuri.</numerusform></translation>
</message>
<message>
<source>Warning: Invalid Tooncoin address</source>
<translation>Atenţie: Adresa tooncoin nevalidă!</translation>
</message>
<message>
<source>Warning: Unknown change address</source>
<translation>Atenţie: Adresă de rest necunoscută</translation>
</message>
<message>
<source>Confirm custom change address</source>
<translation>Confirmati adresa personalizata de rest</translation>
</message>
<message>
<source>The address you selected for change is not part of this wallet. Any or all funds in your wallet may be sent to this address. Are you sure?</source>
<translation>Adresa selectata pentru rest nu face parte din acest portofel. Orice suma, sau intreaga suma din portofel poate fi trimisa la aceasta adresa. Sunteti sigur?</translation>
</message>
<message>
<source>(no label)</source>
<translation>(fără etichetă)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Su&mă:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Plăteşte că&tre:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Etichetă:</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Alegeţi adrese folosite anterior</translation>
</message>
<message>
<source>This is a normal payment.</source>
<translation>Aceasta este o tranzacţie normală.</translation>
</message>
<message>
<source>The Tooncoin address to send the payment to</source>
<translation>Adresa tooncoin către care se face plata</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Lipeşte adresa din clipboard</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Remove this entry</source>
<translation>Înlătură această intrare</translation>
</message>
<message>
<source>The fee will be deducted from the amount being sent. The recipient will receive less tooncoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source>
<translation>Taxa va fi scazuta in suma trimisa. Destinatarul va primi mai putini tooncoin decat ati specificat in campul sumei trimise. Daca au fost selectati mai multi destinatari, taxa se va imparti in mod egal.</translation>
</message>
<message>
<source>S&ubtract fee from amount</source>
<translation>S&cade taxa din suma</translation>
</message>
<message>
<source>Use available balance</source>
<translation>Folosește balanța disponibilă</translation>
</message>
<message>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<source>This is an unauthenticated payment request.</source>
<translation>Aceasta este o cerere de plata neautentificata.</translation>
</message>
<message>
<source>This is an authenticated payment request.</source>
<translation>Aceasta este o cerere de plata autentificata.</translation>
</message>
<message>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation>Introduceţi eticheta pentru ca această adresa să fie introdusă în lista de adrese folosite</translation>
</message>
<message>
<source>A message that was attached to the tooncoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Tooncoin network.</source>
<translation>un mesaj a fost ataşat la tooncoin: URI care va fi stocat cu tranzacţia pentru referinţa dvs. Notă: Acest mesaj nu va fi trimis către reţeaua tooncoin.</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Plăteşte către:</translation>
</message>
<message>
<source>Memo:</source>
<translation>Memo:</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>Introduceţi o etichetă pentru această adresă pentru a fi adăugată în lista dvs. de adrese</translation>
</message>
</context>
<context>
<name>SendConfirmationDialog</name>
<message>
<source>Yes</source>
<translation>Da</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>%1 is shutting down...</source>
<translation>%1 se închide</translation>
</message>
<message>
<source>Do not shut down the computer until this window disappears.</source>
<translation>Nu închide calculatorul pînă ce această fereastră nu dispare.</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation>Semnaturi - Semnează/verifică un mesaj</translation>
</message>
<message>
<source>&Sign Message</source>
<translation>&Semnează mesaj</translation>
</message>
<message>
<source>You can sign messages/agreements with your addresses to prove you can receive tooncoins sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Puteţi semna mesaje/contracte cu adresele dvs. pentru a demostra ca puteti primi tooncoini trimisi la ele. Aveţi grijă să nu semnaţi nimic vag sau aleator, deoarece atacurile de tip phishing vă pot păcăli să le transferaţi identitatea. Semnaţi numai declaraţiile detaliate cu care sînteti de acord.</translation>
</message>
<message>
<source>The Tooncoin address to sign the message with</source>
<translation>Adresa cu care semnaţi mesajul</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Alegeţi adrese folosite anterior</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Lipeşte adresa copiată din clipboard</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>Introduceţi mesajul pe care vreţi să-l semnaţi, aici</translation>
</message>
<message>
<source>Signature</source>
<translation>Semnătură</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiază semnatura curentă în clipboard-ul sistemului</translation>
</message>
<message>
<source>Sign the message to prove you own this Tooncoin address</source>
<translation>Semnează mesajul pentru a dovedi ca deţineţi acestă adresă Tooncoin</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Semnează &mesaj</translation>
</message>
<message>
<source>Reset all sign message fields</source>
<translation>Resetează toate cîmpurile mesajelor semnate</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Curăţă to&ate</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>&Verifică mesaj</translation>
</message>
<message>
<source>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source>
<translation>Introduceţi adresa de semnatură, mesajul (asiguraţi-vă că aţi copiat spaţiile, taburile etc. exact) şi semnatura dedesubt pentru a verifica mesajul. Aveţi grijă să nu citiţi mai mult în semnatură decît mesajul în sine, pentru a evita să fiţi păcăliţi de un atac de tip man-in-the-middle. De notat ca aceasta dovedeste doar ca semnatarul primeste odata cu adresa, nu dovedesta insa trimiterea vreunei tranzactii.</translation>
</message>
<message>
<source>The Tooncoin address the message was signed with</source>
<translation>Introduceţi o adresă Tooncoin</translation>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified Tooncoin address</source>
<translation>Verificaţi mesajul pentru a vă asigura că a fost semnat cu adresa Tooncoin specificată</translation>
</message>
<message>
<source>Verify &Message</source>
<translation>Verifică &mesaj</translation>
</message>
<message>
<source>Reset all verify message fields</source>
<translation>Resetează toate cîmpurile mesajelor semnate</translation>
</message>
<message>
<source>Click "Sign Message" to generate signature</source>
<translation>Faceţi clic pe "Semneaza msaj" pentru a genera semnătura</translation>
</message>
<message>
<source>The entered address is invalid.</source>
<translation>Adresa introdusă este invalidă.</translation>
</message>
<message>
<source>Please check the address and try again.</source>
<translation>Vă rugăm verificaţi adresa şi încercaţi din nou.</translation>
</message>
<message>
<source>The entered address does not refer to a key.</source>
<translation>Adresa introdusă nu se referă la o cheie.</translation>
</message>
<message>
<source>Wallet unlock was cancelled.</source>
<translation>Deblocarea portofelului a fost anulata.</translation>
</message>
<message>
<source>Private key for the entered address is not available.</source>
<translation>Cheia privată pentru adresa introdusă nu este disponibila.</translation>
</message>
<message>
<source>Message signing failed.</source>
<translation>Semnarea mesajului nu a reuşit.</translation>
</message>
<message>
<source>Message signed.</source>
<translation>Mesaj semnat.</translation>
</message>
<message>
<source>The signature could not be decoded.</source>
<translation>Semnatura nu a putut fi decodată.</translation>
</message>
<message>
<source>Please check the signature and try again.</source>
<translation>Vă rugăm verificaţi semnătura şi încercaţi din nou.</translation>
</message>
<message>
<source>The signature did not match the message digest.</source>
<translation>Semnatura nu se potriveşte cu mesajul.</translation>
</message>
<message>
<source>Message verification failed.</source>
<translation>Verificarea mesajului nu a reuşit.</translation>
</message>
<message>
<source>Message verified.</source>
<translation>Mesaj verificat. </translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>Deschis pentru inca un bloc</numerusform><numerusform>Deschis pentru inca %n blocuri</numerusform><numerusform>Deschis pentru inca %n blocuri</numerusform></translation>
</message>
<message>
<source>Open until %1</source>
<translation>Deschis pînă la %1</translation>
</message>
<message>
<source>conflicted with a transaction with %1 confirmations</source>
<translation>in conflict cu o tranzactie cu %1 confirmari</translation>
</message>
<message>
<source>0/unconfirmed, %1</source>
<translation>0/neconfirmat, %1</translation>
</message>
<message>
<source>in memory pool</source>
<translation>in memory pool</translation>
</message>
<message>
<source>not in memory pool</source>
<translation>nu e in memory pool</translation>
</message>
<message>
<source>abandoned</source>
<translation>abandonat</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/neconfirmat</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 confirmări</translation>
</message>
<message>
<source>Status</source>
<translation>Stare</translation>
</message>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Source</source>
<translation>Sursa</translation>
</message>
<message>
<source>Generated</source>
<translation>Generat</translation>
</message>
<message>
<source>From</source>
<translation>De la</translation>
</message>
<message>
<source>unknown</source>
<translation>necunoscut</translation>
</message>
<message>
<source>To</source>
<translation>Către</translation>
</message>
<message>
<source>own address</source>
<translation>adresa proprie</translation>
</message>
<message>
<source>watch-only</source>
<translation>doar-supraveghere</translation>
</message>
<message>
<source>label</source>
<translation>etichetă</translation>
</message>
<message>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<source>matures in %n more block(s)</source>
<translation><numerusform>se matureaza intr-un bloc</numerusform><numerusform>se matureaza in %n blocuri</numerusform><numerusform>se matureaza in %n blocuri</numerusform></translation>
</message>
<message>
<source>not accepted</source>
<translation>neacceptat</translation>
</message>
<message>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<source>Total debit</source>
<translation>Total debit</translation>
</message>
<message>
<source>Total credit</source>
<translation>Total credit</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Taxă tranzacţie</translation>
</message>
<message>
<source>Net amount</source>
<translation>Suma netă</translation>
</message>
<message>
<source>Message</source>
<translation>Mesaj</translation>
</message>
<message>
<source>Comment</source>
<translation>Comentariu</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>ID tranzacţie</translation>
</message>
<message>
<source>Transaction total size</source>
<translation>Dimensiune totala tranzacţie</translation>
</message>
<message>
<source>Output index</source>
<translation>Index debit</translation>
</message>
<message>
<source>Merchant</source>
<translation>Comerciant</translation>
</message>
<message>
<source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Monedele generate se pot cheltui doar dupa inca %1 blocuri. După ce a fost generat, s-a propagat în reţea, urmând să fie adăugat in blockchain. Dacă nu poate fi inclus in lanţ, starea sa va deveni "neacceptat" si nu va putea fi folosit la tranzacţii. Acest fenomen se întâmplă atunci cand un alt nod a generat un bloc la o diferenţa de câteva secunde.</translation>
</message>
<message>
<source>Debug information</source>
<translation>Informaţii pentru depanare</translation>
</message>
<message>
<source>Transaction</source>
<translation>Tranzacţie</translation>
</message>
<message>
<source>Inputs</source>
<translation>Intrări</translation>
</message>
<message>
<source>Amount</source>
<translation>Cantitate</translation>
</message>
<message>
<source>true</source>
<translation>adevărat</translation>
</message>
<message>
<source>false</source>
<translation>fals</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Acest panou arată o descriere detaliată a tranzacţiei</translation>
</message>
<message>
<source>Details for %1</source>
<translation>Detalii pentru %1</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Type</source>
<translation>Tip</translation>
</message>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<source>Open until %1</source>
<translation>Deschis pînă la %1</translation>
</message>
<message>
<source>Unconfirmed</source>
<translation>Neconfirmat</translation>
</message>
<message>
<source>Abandoned</source>
<translation>Abandonat</translation>
</message>
<message>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Confirmare (%1 din %2 confirmari recomandate)</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmat (%1 confirmari)</translation>
</message>
<message>
<source>Conflicted</source>
<translation>În conflict</translation>
</message>
<message>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Imatur (%1 confirmari, va fi disponibil după %2)</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>Generat dar neacceptat</translation>
</message>
<message>
<source>Received with</source>
<translation>Recepţionat cu</translation>
</message>
<message>
<source>Received from</source>
<translation>Primit de la</translation>
</message>
<message>
<source>Sent to</source>
<translation>Trimis către</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Plată către dvs.</translation>
</message>
<message>
<source>Mined</source>
<translation>Minat</translation>
</message>
<message>
<source>watch-only</source>
<translation>doar-supraveghere</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(indisponibil)</translation>
</message>
<message>
<source>(no label)</source>
<translation>(fără etichetă)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Starea tranzacţiei. Treceţi cu mouse-ul peste acest cîmp pentru afişarea numărului de confirmari.</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Data şi ora la care a fost recepţionată tranzacţia.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Tipul tranzacţiei.</translation>
</message>
<message>
<source>Whether or not a watch-only address is involved in this transaction.</source>
<translation>Indiferent dacă sau nu o adresa doar-suăpraveghere este implicată în această tranzacţie.</translation>
</message>
<message>
<source>User-defined intent/purpose of the transaction.</source>
<translation>Intentie/scop al tranzactie definit de user.</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>Suma extrasă sau adăugată la sold.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Toate</translation>
</message>
<message>
<source>Today</source>
<translation>Astăzi</translation>
</message>
<message>
<source>This week</source>
<translation>Saptamana aceasta</translation>
</message>
<message>
<source>This month</source>
<translation>Luna aceasta</translation>
</message>
<message>
<source>Last month</source>
<translation>Luna trecuta</translation>
</message>
<message>
<source>This year</source>
<translation>Anul acesta</translation>
</message>
<message>
<source>Range...</source>
<translation>Interval...</translation>
</message>
<message>
<source>Received with</source>
<translation>Recepţionat cu</translation>
</message>
<message>
<source>Sent to</source>
<translation>Trimis către</translation>
</message>
<message>
<source>To yourself</source>
<translation>Către dvs.</translation>
</message>
<message>
<source>Mined</source>
<translation>Minat</translation>
</message>
<message>
<source>Other</source>
<translation>Altele</translation>
</message>
<message>
<source>Enter address, transaction id, or label to search</source>
<translation>Introduceți adresa, ID-ul tranzacției, sau eticheta pentru a căuta</translation>
</message>
<message>
<source>Min amount</source>
<translation>Suma minimă</translation>
</message>
<message>
<source>Abandon transaction</source>
<translation>Abandoneaza tranzacţia</translation>
</message>
<message>
<source>Increase transaction fee</source>
<translation>Cresteti comisionul pentru tranzacţie</translation>
</message>
<message>
<source>Copy address</source>
<translation>Copiază adresa</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copiază eticheta</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copiază suma</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Copiază ID tranzacţie</translation>
</message>
<message>
<source>Copy raw transaction</source>
<translation>Copiază tranzacţia bruta</translation>
</message>
<message>
<source>Copy full transaction details</source>
<translation>Copiaza toate detaliile tranzacţiei</translation>
</message>
<message>
<source>Edit label</source>
<translation>Editează eticheta</translation>
</message>
<message>
<source>Show transaction details</source>
<translation>Arată detaliile tranzacţiei</translation>
</message>
<message>
<source>Export Transaction History</source>
<translation>Export istoric tranzacţii</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Fisier .csv cu separator - virgula</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Confirmat</translation>
</message>
<message>
<source>Watch-only</source>
<translation>Doar-supraveghere</translation>
</message>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Type</source>
<translation>Tip</translation>
</message>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<source>Address</source>
<translation>Adresă</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Exportarea a eșuat</translation>
</message>
<message>
<source>There was an error trying to save the transaction history to %1.</source>
<translation>S-a produs o eroare la salvarea istoricului tranzacţiilor la %1.</translation>
</message>
<message>
<source>Exporting Successful</source>
<translation>Export reuşit</translation>
</message>
<message>
<source>The transaction history was successfully saved to %1.</source>
<translation>Istoricul tranzacţiilor a fost salvat cu succes la %1.</translation>
</message>
<message>
<source>Range:</source>
<translation>Interval:</translation>
</message>
<message>
<source>to</source>
<translation>către</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
<message>
<source>Unit to show amounts in. Click to select another unit.</source>
<translation>Unitatea în care sînt arătate sumele. Faceţi clic pentru a selecta o altă unitate.</translation>
</message>
</context>
<context>
<name>WalletFrame</name>
<message>
<source>No wallet has been loaded.</source>
<translation>Nu a fost încărcat nici un portofel.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Trimite monede</translation>
</message>
<message>
<source>Fee bump error</source>
<translation>Eroare in cresterea taxei</translation>
</message>
<message>
<source>Increasing transaction fee failed</source>
<translation>Cresterea comisionului pentru tranzactie a esuat.</translation>
</message>
<message>
<source>Do you want to increase the fee?</source>
<translation>Doriti sa cresteti taxa de tranzactie?</translation>
</message>
<message>
<source>Current fee:</source>
<translation>Comision curent:</translation>
</message>
<message>
<source>Increase:</source>
<translation>Crestere:</translation>
</message>
<message>
<source>New fee:</source>
<translation>Noul comision:</translation>
</message>
<message>
<source>Confirm fee bump</source>
<translation>Confirma cresterea comisionului</translation>
</message>
<message>
<source>Can't sign transaction.</source>
<translation>Nu s-a reuşit semnarea tranzacţiei</translation>
</message>
<message>
<source>Could not commit transaction</source>
<translation>Tranzactia nu a putut fi consemnata.</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exportă datele din tab-ul curent într-un fişier</translation>
</message>
<message>
<source>Backup Wallet</source>
<translation>Backup portofelul electronic</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>Date portofel (*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>Backup esuat</translation>
</message>
<message>
<source>There was an error trying to save the wallet data to %1.</source>
<translation>S-a produs o eroare la salvarea datelor portofelului la %1.</translation>
</message>
<message>
<source>Backup Successful</source>
<translation>Backup efectuat cu succes</translation>
</message>
<message>
<source>The wallet data was successfully saved to %1.</source>
<translation>Datele portofelului s-au salvat cu succes la %1.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Distributed under the MIT software license, see the accompanying file %s or %s</source>
<translation>Distribuit sub licenţa de programe MIT, vezi fişierul însoţitor %s sau %s</translation>
</message>
<message>
<source>Prune configured below the minimum of %d MiB. Please use a higher number.</source>
<translation>Reductia e configurata sub minimul de %d MiB. Rugam folositi un numar mai mare.</translation>
</message>
<message>
<source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source>
<translation>Reductie: ultima sincronizare merge dincolo de datele reductiei. Trebuie sa faceti -reindex (sa descarcati din nou intregul blockchain in cazul unui nod redus)</translation>
</message>
<message>
<source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source>
<translation>Rescanarile nu sunt posibile in modul redus. Va trebui sa folositi -reindex, ceea ce va descarca din nou intregul blockchain.</translation>
</message>
<message>
<source>Error: A fatal internal error occurred, see debug.log for details</source>
<translation>Eroare: S-a produs o eroare interna fatala, vedeti debug.log pentru detalii</translation>
</message>
<message>
<source>Pruning blockstore...</source>
<translation>Reductie blockstore...</translation>
</message>
<message>
<source>Unable to start HTTP server. See debug log for details.</source>
<translation>Imposibil de pornit serverul HTTP. Pentru detalii vezi logul de depanare.</translation>
</message>
<message>
<source>Tooncoin Core</source>
<translation>Nucleul Tooncoin</translation>
</message>
<message>
<source>The %s developers</source>
<translation>Dezvoltatorii %s</translation>
</message>
<message>
<source>Cannot obtain a lock on data directory %s. %s is probably already running.</source>
<translation>Nu se poate obține o blocare a directorului de date %s. %s probabil rulează deja.</translation>
</message>
<message>
<source>Cannot provide specific connections and have addrman find outgoing connections at the same.</source>
<translation>Nu se pot furniza conexiuni specifice in acelasi timp in care addrman este folosit pentru a gasi conexiuni de iesire.</translation>
</message>
<message>
<source>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Eroare la citirea %s! Toate cheile sînt citite corect, dar datele tranzactiei sau anumite intrări din agenda sînt incorecte sau lipsesc.</translation>
</message>
<message>
<source>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</source>
<translation>Vă rugăm verificaţi dacă data/timpul calculatorului dvs. sînt corecte! Dacă ceasul calcultorului este gresit, %s nu va funcţiona corect.</translation>
</message>
<message>
<source>Please contribute if you find %s useful. Visit %s for further information about the software.</source>
<translation>Va rugam sa contribuiti daca apreciati ca %s va este util. Vizitati %s pentru mai multe informatii despre software.</translation>
</message>
<message>
<source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source>
<translation>Baza de date a blocurilor contine un bloc ce pare a fi din viitor. Acest lucru poate fi cauzat de setarea incorecta a datei si orei in computerul dvs. Reconstruiti baza de date a blocurilor doar daca sunteti sigur ca data si ora calculatorului dvs sunt corecte.</translation>
</message>
<message>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Aceasta este o versiune de test preliminară - vă asumaţi riscul folosind-o - nu folosiţi pentru minerit sau aplicaţiile comercianţilor</translation>
</message>
<message>
<source>This is the transaction fee you may discard if change is smaller than dust at this level</source>
<translation>Aceasta este taxa de tranzactie la care puteti renunta daca restul este mai mic decat praful la acest nivel.</translation>
</message>
<message>
<source>Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.</source>
<translation>Imposibil de refacut blocurile. Va trebui sa reconstruiti baza de date folosind -reindex-chainstate.</translation>
</message>
<message>
<source>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</source>
<translation>Imposibil de a readuce baza de date la statusul pre-fork. Va trebui redescarcat blockchainul.</translation>
</message>
<message>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation>Atenţie: Reţeaua nu pare să fie de acord în totalitate! Aparent nişte mineri au probleme.</translation>
</message>
<message>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Atenţie: Aparent, nu sîntem de acord cu toţi partenerii noştri! Va trebui să faceţi o actualizare, sau alte noduri necesită actualizare.</translation>
</message>
<message>
<source>%d of last 100 blocks have unexpected version</source>
<translation>%d din ultimele 100 blocuri a o versiune neasteptata</translation>
</message>
<message>
<source>%s corrupt, salvage failed</source>
<translation>%s corupt, salvare nereuşită</translation>
</message>
<message>
<source>-maxmempool must be at least %d MB</source>
<translation>-maxmempool trebuie sa fie macar %d MB</translation>
</message>
<message>
<source>Cannot resolve -%s address: '%s'</source>
<translation>Nu se poate rezolva adresa -%s: '%s'</translation>
</message>
<message>
<source>Change index out of range</source>
<translation>Indexul de schimbare este iesit din parametrii</translation>
</message>
<message>
<source>Copyright (C) %i-%i</source>
<translation>Copyright (C) %i-%i</translation>
</message>
<message>
<source>Corrupted block database detected</source>
<translation>Bloc defect din baza de date detectat</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>Doriţi să reconstruiţi baza de date blocuri acum?</translation>
</message>
<message>
<source>Error creating %s: You can't create non-HD wallets with this version.</source>
<translation>Eroare la crearea %s: Nu se pot crea portofele non-HD cu aceasta versiune.</translation>
</message>
<message>
<source>Error initializing block database</source>
<translation>Eroare la iniţializarea bazei de date de blocuri</translation>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation>Eroare la iniţializarea mediului de bază de date a portofelului %s!</translation>
</message>
<message>
<source>Error loading %s</source>
<translation>Eroare la încărcarea %s</translation>
</message>
<message>
<source>Error loading %s: Wallet corrupted</source>
<translation>Eroare la încărcarea %s: Portofel corupt</translation>
</message>
<message>
<source>Error loading %s: Wallet requires newer version of %s</source>
<translation>Eroare la încărcarea %s: Portofelul are nevoie de o versiune %s mai nouă</translation>
</message>
<message>
<source>Error loading block database</source>
<translation>Eroare la încărcarea bazei de date de blocuri</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Eroare la deschiderea bazei de date de blocuri</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Eroare: Spaţiu pe disc redus!</translation>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Nu s-a reuşit ascultarea pe orice port. Folosiţi -listen=0 dacă vreţi asta.</translation>
</message>
<message>
<source>Failed to rescan the wallet during initialization</source>
<translation>Rescanarea portofelului in timpul initializarii a esuat.</translation>
</message>
<message>
<source>Importing...</source>
<translation>Import...</translation>
</message>
<message>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>Incorect sau nici un bloc de geneza găsit. Directorul de retea greşit?</translation>
</message>
<message>
<source>Initialization sanity check failed. %s is shutting down.</source>
<translation>Nu s-a reuşit iniţierea verificării sănătăţii. %s se inchide.</translation>
</message>
<message>
<source>Invalid amount for -%s=<amount>: '%s'</source>
<translation>Sumă nevalidă pentru -%s=<amount>: '%s'</translation>
</message>
<message>
<source>Invalid amount for -discardfee=<amount>: '%s'</source>
<translation>Sumă nevalidă pentru -discardfee=<amount>: '%s'</translation>
</message>
<message>
<source>Invalid amount for -fallbackfee=<amount>: '%s'</source>
<translation>Suma nevalidă pentru -fallbackfee=<amount>: '%s'</translation>
</message>
<message>
<source>Loading P2P addresses...</source>
<translation>Încărcare adrese P2P...</translation>
</message>
<message>
<source>Loading banlist...</source>
<translation>Încărcare banlist...</translation>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation>Nu sînt destule descriptoare disponibile.</translation>
</message>
<message>
<source>Prune cannot be configured with a negative value.</source>
<translation>Reductia nu poate fi configurata cu o valoare negativa.</translation>
</message>
<message>
<source>Prune mode is incompatible with -txindex.</source>
<translation>Modul redus este incompatibil cu -txindex.</translation>
</message>
<message>
<source>Replaying blocks...</source>
<translation>Se reiau blocurile...</translation>
</message>
<message>
<source>Rewinding blocks...</source>
<translation>Se deruleaza blocurile...</translation>
</message>
<message>
<source>The source code is available from %s.</source>
<translation>Codul sursa este disponibil la %s.</translation>
</message>
<message>
<source>Transaction fee and change calculation failed</source>
<translation>Calcului taxei de tranzactie si a restului a esuat.</translation>
</message>
<message>
<source>Unable to bind to %s on this computer. %s is probably already running.</source>
<translation>Nu se poate efectua legatura la %s pe acest computer. %s probabil ruleaza deja.</translation>
</message>
<message>
<source>Unsupported argument -benchmark ignored, use -debug=bench.</source>
<translation>Argumentul nesuportat -benchmark este ignorat, folositi debug=bench.</translation>
</message>
<message>
<source>Unsupported argument -debugnet ignored, use -debug=net.</source>
<translation>Argument nesuportat -debugnet ignorat, folosiţi -debug=net.</translation>
</message>
<message>
<source>Unsupported argument -tor found, use -onion.</source>
<translation>Argument nesuportat -tor găsit, folosiţi -onion.</translation>
</message>
<message>
<source>Unsupported logging category %s=%s.</source>
<translation>Categoria de logging %s=%s nu este suportata.</translation>
</message>
<message>
<source>Upgrading UTXO database</source>
<translation>Actualizarea bazei de date UTXO</translation>
</message>
<message>
<source>User Agent comment (%s) contains unsafe characters.</source>
<translation>Comentariul (%s) al Agentului Utilizator contine caractere nesigure.</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Se verifică blocurile...</translation>
</message>
<message>
<source>Error: Listening for incoming connections failed (listen returned error %s)</source>
<translation>Eroare: Ascultarea conexiunilor de intrare nu a reuşit (ascultarea a reurnat eroarea %s)</translation>
</message>
<message>
<source>Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source>
<translation>Sumă nevalidă pentru -maxtxfee=<amount>: '%s' (trebuie să fie cel puţin taxa minrelay de %s pentru a preveni blocarea tranzactiilor)</translation>
</message>
<message>
<source>The transaction amount is too small to send after the fee has been deducted</source>
<translation>Suma tranzactiei este prea mica pentru a fi trimisa dupa ce se scade taxa.</translation>
</message>
<message>
<source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source>
<translation>Trebuie reconstruita intreaga baza de date folosind -reindex pentru a va intoarce la modul non-redus. Aceasta va determina descarcarea din nou a intregului blockchain</translation>
</message>
<message>
<source>Error loading %s: You can't disable HD on an already existing HD wallet</source>
<translation>Eroare la incarcarea %s: Nu se poate dezactiva HD la un portofel care este deja HD.</translation>
</message>
<message>
<source>Error reading from database, shutting down.</source>
<translation>Eroare la citirea bazei de date. Oprire.</translation>
</message>
<message>
<source>Error upgrading chainstate database</source>
<translation>Eroare la actualizarea bazei de date chainstate</translation>
</message>
<message>
<source>Information</source>
<translation>Informaţie</translation>
</message>
<message>
<source>Invalid -onion address or hostname: '%s'</source>
<translation>Adresa sau hostname -onion invalide: '%s'</translation>
</message>
<message>
<source>Invalid -proxy address or hostname: '%s'</source>
<translation>Adresa sau hostname -proxy invalide: '%s'</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)</source>
<translation>Sumă nevalidă pentru -paytxfee=<suma>: '%s' (trebuie să fie cel puţin %s)</translation>
</message>
<message>
<source>Invalid netmask specified in -whitelist: '%s'</source>
<translation>Mască reţea nevalidă specificată în -whitelist: '%s'</translation>
</message>
<message>
<source>Need to specify a port with -whitebind: '%s'</source>
<translation>Trebuie să specificaţi un port cu -whitebind: '%s'</translation>
</message>
<message>
<source>Reducing -maxconnections from %d to %d, because of system limitations.</source>
<translation>Se micsoreaza -maxconnections de la %d la %d, datorita limitarilor de sistem.</translation>
</message>
<message>
<source>Signing transaction failed</source>
<translation>Nu s-a reuşit semnarea tranzacţiei</translation>
</message>
<message>
<source>Specified -walletdir "%s" does not exist</source>
<translation>Nu exista -walletdir "%s" specificat</translation>
</message>
<message>
<source>Specified -walletdir "%s" is a relative path</source>
<translation>-walletdir "%s" specificat este o cale relativa</translation>
</message>
<message>
<source>The transaction amount is too small to pay the fee</source>
<translation>Suma tranzactiei este prea mica pentru plata taxei</translation>
</message>
<message>
<source>This is experimental software.</source>
<translation>Acesta este un program experimental.</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Suma tranzacţionată este prea mică</translation>
</message>
<message>
<source>Transaction too large for fee policy</source>
<translation>Tranzacţia are suma prea mare pentru a beneficia de gratuitate</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Tranzacţie prea mare</translation>
</message>
<message>
<source>Unable to bind to %s on this computer (bind returned error %s)</source>
<translation>Nu se poate lega la %s pe acest calculator. (Legarea a întors eroarea %s)</translation>
</message>
<message>
<source>Unable to generate initial keys</source>
<translation>Nu s-au putut genera cheile initiale</translation>
</message>
<message>
<source>Verifying wallet(s)...</source>
<translation>Se verifică portofelul(ele)...</translation>
</message>
<message>
<source>Wallet %s resides outside wallet directory %s</source>
<translation>Portofelul %s se află în afara directorului portofelului %s</translation>
</message>
<message>
<source>Warning</source>
<translation>Avertisment</translation>
</message>
<message>
<source>Warning: unknown new rules activated (versionbit %i)</source>
<translation>Atentie: se activeaza reguli noi necunoscute (versionbit %i)</translation>
</message>
<message>
<source>Zapping all transactions from wallet...</source>
<translation>Şterge toate tranzacţiile din portofel...</translation>
</message>
<message>
<source>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</source>
<translation>-maxtxfee este setata foarte sus! Se pot plati taxe de aceasta marime pe o singura tranzactie.</translation>
</message>
<message>
<source>Error loading %s: You can't enable HD on an already existing non-HD wallet</source>
<translation>Eroare la incarcarea %s: Nu se poate activa HD la un portofel care este deja non-HD.</translation>
</message>
<message>
<source>This is the transaction fee you may pay when fee estimates are not available.</source>
<translation>Aceasta este taxa de tranzactie pe care este posibil sa o platiti daca estimarile de taxe nu sunt disponibile.</translation>
</message>
<message>
<source>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</source>
<translation>Acest produs include software dezvoltat de OpenSSL Project pentru a fi folosit in Toolkitul OpenSSL %s, software criptografic scris de Eric Young si software UPnP scris de Thomas Bernard. </translation>
</message>
<message>
<source>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</source>
<translation>Lungimea totala a sirului versiunii retelei (%i) depaseste lungimea maxima (%i). Reduceti numarul sa dimensiunea uacomments. </translation>
</message>
<message>
<source>Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation>S-a gasit un argument -socks nesuportat. Setarea versiunii SOCKS nu mai este posibila, sunt suportate doar proxiurile SOCKS5.</translation>
</message>
<message>
<source>Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.</source>
<translation>Se ignora argumentul nesuportat -whitelistalwaysrelay, folositi -whitelistrelay si/sau -whitelistforcerelay.</translation>
</message>
<message>
<source>Warning: Unknown block versions being mined! It's possible unknown rules are in effect</source>
<translation>Atentie: se mineaza blocuri cu versiune necunoscuta! Este posibil sa fie in vigoare reguli necunoscute.</translation>
</message>
<message>
<source>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Atenţie: fişierul portofelului este corupt, date salvate! Fişierul %s a fost salvat ca %s in %s; dacă balanta sau tranzactiile sunt incorecte ar trebui să restauraţi dintr-o copie de siguranţă.</translation>
</message>
<message>
<source>%s is set very high!</source>
<translation>%s este setata foarte sus!</translation>
</message>
<message>
<source>Error loading wallet %s. Duplicate -wallet filename specified.</source>
<translation>Eroare la incarcarea portofelului %s. Este specificat un fisier -wallet duplicat.</translation>
</message>
<message>
<source>Keypool ran out, please call keypoolrefill first</source>
<translation>Keypool epuizat, folositi intai functia keypoolrefill</translation>
</message>
<message>
<source>Starting network threads...</source>
<translation>Se pornesc threadurile retelei...</translation>
</message>
<message>
<source>The wallet will avoid paying less than the minimum relay fee.</source>
<translation>Portofelul va evita sa plateasca mai putin decat minimul taxei de retransmisie.</translation>
</message>
<message>
<source>This is the minimum transaction fee you pay on every transaction.</source>
<translation>Acesta este minimum de taxa de tranzactie care va fi platit la fiecare tranzactie.</translation>
</message>
<message>
<source>This is the transaction fee you will pay if you send a transaction.</source>
<translation>Aceasta este taxa de tranzactie pe care o platiti cand trimiteti o tranzactie.</translation>
</message>
<message>
<source>Transaction amounts must not be negative</source>
<translation>Sumele tranzactionate nu pot fi negative</translation>
</message>
<message>
<source>Transaction has too long of a mempool chain</source>
<translation>Tranzacţia are o lungime prea mare in lantul mempool</translation>
</message>
<message>
<source>Transaction must have at least one recipient</source>
<translation>Tranzactia trebuie sa aiba cel putin un destinatar</translation>
</message>
<message>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Reţeaua specificată în -onlynet este necunoscută: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Fonduri insuficiente</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Încărcare index bloc...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Încărcare portofel...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>Nu se poate retrograda portofelul</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Rescanare...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Încărcare terminată</translation>
</message>
<message>
<source>Error</source>
<translation>Eroare</translation>
</message>
</context>
</TS> | <translation>(fără etichetă)</translation>
</message>
<message>
<source>change from %1 (%2)</source> |
store.go | package store
import (
"context"
"encoding/json"
"errors"
"os"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/sync/errgroup"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/lotus/api"
bstore "github.com/filecoin-project/lotus/blockstore"
"github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/journal"
"github.com/filecoin-project/lotus/metrics"
"go.opencensus.io/stats"
"go.opencensus.io/trace"
"go.uber.org/multierr"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/pubsub"
lru "github.com/hashicorp/golang-lru"
block "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
dstore "github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/query"
cbor "github.com/ipfs/go-ipld-cbor"
logging "github.com/ipfs/go-log/v2"
"golang.org/x/xerrors"
)
var log = logging.Logger("chainstore")
var (
chainHeadKey = dstore.NewKey("head")
checkpointKey = dstore.NewKey("/chain/checks")
blockValidationCacheKeyPrefix = dstore.NewKey("blockValidation")
)
var DefaultTipSetCacheSize = 8192
var DefaultMsgMetaCacheSize = 2048
var ErrNotifeeDone = errors.New("notifee is done and should be removed")
func init() {
if s := os.Getenv("LOTUS_CHAIN_TIPSET_CACHE"); s != "" {
tscs, err := strconv.Atoi(s)
if err != nil {
log.Errorf("failed to parse 'LOTUS_CHAIN_TIPSET_CACHE' env var: %s", err)
}
DefaultTipSetCacheSize = tscs
}
if s := os.Getenv("LOTUS_CHAIN_MSGMETA_CACHE"); s != "" {
mmcs, err := strconv.Atoi(s)
if err != nil {
log.Errorf("failed to parse 'LOTUS_CHAIN_MSGMETA_CACHE' env var: %s", err)
}
DefaultMsgMetaCacheSize = mmcs
}
}
// ReorgNotifee represents a callback that gets called upon reorgs.
type ReorgNotifee = func(rev, app []*types.TipSet) error
// Journal event types.
const (
evtTypeHeadChange = iota
)
type HeadChangeEvt struct {
From types.TipSetKey
FromHeight abi.ChainEpoch
To types.TipSetKey
ToHeight abi.ChainEpoch
RevertCount int
ApplyCount int
}
type WeightFunc func(ctx context.Context, stateBs bstore.Blockstore, ts *types.TipSet) (types.BigInt, error)
// ChainStore is the main point of access to chain data.
//
// Raw chain data is stored in the Blockstore, with relevant markers (genesis,
// latest head tipset references) being tracked in the Datastore (key-value
// store).
//
// To alleviate disk access, the ChainStore has two ARC caches:
// 1. a tipset cache
// 2. a block => messages references cache.
type ChainStore struct {
chainBlockstore bstore.Blockstore
stateBlockstore bstore.Blockstore
metadataDs dstore.Batching
weight WeightFunc
chainLocalBlockstore bstore.Blockstore
heaviestLk sync.RWMutex
heaviest *types.TipSet
checkpoint *types.TipSet
bestTips *pubsub.PubSub
pubLk sync.Mutex
tstLk sync.Mutex
tipsets map[abi.ChainEpoch][]cid.Cid
cindex *ChainIndex
reorgCh chan<- reorg
reorgNotifeeCh chan ReorgNotifee
mmCache *lru.ARCCache // msg meta cache (mh.Messages -> secp, bls []cid)
tsCache *lru.ARCCache
evtTypes [1]journal.EventType
journal journal.Journal
cancelFn context.CancelFunc
wg sync.WaitGroup
}
func NewChainStore(chainBs bstore.Blockstore, stateBs bstore.Blockstore, ds dstore.Batching, weight WeightFunc, j journal.Journal) *ChainStore {
c, _ := lru.NewARC(DefaultMsgMetaCacheSize)
tsc, _ := lru.NewARC(DefaultTipSetCacheSize)
if j == nil {
j = journal.NilJournal()
}
ctx, cancel := context.WithCancel(context.Background())
// unwraps the fallback store in case one is configured.
// some methods _need_ to operate on a local blockstore only.
localbs, _ := bstore.UnwrapFallbackStore(chainBs)
cs := &ChainStore{
chainBlockstore: chainBs,
stateBlockstore: stateBs,
chainLocalBlockstore: localbs,
weight: weight,
metadataDs: ds,
bestTips: pubsub.New(64),
tipsets: make(map[abi.ChainEpoch][]cid.Cid),
mmCache: c,
tsCache: tsc,
cancelFn: cancel,
journal: j,
}
cs.evtTypes = [1]journal.EventType{
evtTypeHeadChange: j.RegisterEventType("sync", "head_change"),
}
ci := NewChainIndex(cs.LoadTipSet)
cs.cindex = ci
hcnf := func(rev, app []*types.TipSet) error {
cs.pubLk.Lock()
defer cs.pubLk.Unlock()
notif := make([]*api.HeadChange, len(rev)+len(app))
for i, r := range rev {
notif[i] = &api.HeadChange{
Type: HCRevert,
Val: r,
}
}
for i, r := range app {
notif[i+len(rev)] = &api.HeadChange{
Type: HCApply,
Val: r,
}
}
cs.bestTips.Pub(notif, "headchange")
return nil
}
hcmetric := func(rev, app []*types.TipSet) error {
for _, r := range app {
stats.Record(context.Background(), metrics.ChainNodeHeight.M(int64(r.Height())))
}
return nil
}
cs.reorgNotifeeCh = make(chan ReorgNotifee)
cs.reorgCh = cs.reorgWorker(ctx, []ReorgNotifee{hcnf, hcmetric})
return cs
}
func (cs *ChainStore) Close() error {
cs.cancelFn()
cs.wg.Wait()
return nil
}
func (cs *ChainStore) Load(ctx context.Context) error {
if err := cs.loadHead(ctx); err != nil {
return err
}
if err := cs.loadCheckpoint(ctx); err != nil {
return err
}
return nil
}
func (cs *ChainStore) loadHead(ctx context.Context) error {
head, err := cs.metadataDs.Get(ctx, chainHeadKey)
if err == dstore.ErrNotFound {
log.Warn("no previous chain state found")
return nil
}
if err != nil {
return xerrors.Errorf("failed to load chain state from datastore: %w", err)
}
var tscids []cid.Cid
if err := json.Unmarshal(head, &tscids); err != nil {
return xerrors.Errorf("failed to unmarshal stored chain head: %w", err)
}
ts, err := cs.LoadTipSet(ctx, types.NewTipSetKey(tscids...))
if err != nil {
return xerrors.Errorf("loading tipset: %w", err)
}
cs.heaviest = ts
return nil
}
func (cs *ChainStore) loadCheckpoint(ctx context.Context) error {
tskBytes, err := cs.metadataDs.Get(ctx, checkpointKey)
if err == dstore.ErrNotFound {
return nil
}
if err != nil {
return xerrors.Errorf("failed to load checkpoint from datastore: %w", err)
}
var tsk types.TipSetKey
err = json.Unmarshal(tskBytes, &tsk)
if err != nil {
return err
}
ts, err := cs.LoadTipSet(ctx, tsk)
if err != nil {
return xerrors.Errorf("loading tipset: %w", err)
}
cs.checkpoint = ts
return nil
}
func (cs *ChainStore) writeHead(ctx context.Context, ts *types.TipSet) error {
data, err := json.Marshal(ts.Cids())
if err != nil {
return xerrors.Errorf("failed to marshal tipset: %w", err)
}
if err := cs.metadataDs.Put(ctx, chainHeadKey, data); err != nil {
return xerrors.Errorf("failed to write chain head to datastore: %w", err)
}
return nil
}
const (
HCRevert = "revert"
HCApply = "apply"
HCCurrent = "current"
)
func (cs *ChainStore) SubHeadChanges(ctx context.Context) chan []*api.HeadChange {
cs.pubLk.Lock()
subch := cs.bestTips.Sub("headchange")
head := cs.GetHeaviestTipSet()
cs.pubLk.Unlock()
out := make(chan []*api.HeadChange, 16)
out <- []*api.HeadChange{{
Type: HCCurrent,
Val: head,
}}
go func() {
defer func() {
// Tell the caller we're done first, the following may block for a bit.
close(out)
// Unsubscribe.
cs.bestTips.Unsub(subch)
// Drain the channel.
for range subch {
}
}()
for {
select {
case val, ok := <-subch:
if !ok {
// Shutting down.
return
}
select {
case out <- val.([]*api.HeadChange):
default:
log.Errorf("closing head change subscription due to slow reader")
return
}
if len(out) > 5 {
log.Warnf("head change sub is slow, has %d buffered entries", len(out))
}
case <-ctx.Done():
return
}
}
}()
return out
}
func (cs *ChainStore) SubscribeHeadChanges(f ReorgNotifee) {
cs.reorgNotifeeCh <- f
}
func (cs *ChainStore) IsBlockValidated(ctx context.Context, blkid cid.Cid) (bool, error) {
key := blockValidationCacheKeyPrefix.Instance(blkid.String())
return cs.metadataDs.Has(ctx, key)
}
func (cs *ChainStore) MarkBlockAsValidated(ctx context.Context, blkid cid.Cid) error {
key := blockValidationCacheKeyPrefix.Instance(blkid.String())
if err := cs.metadataDs.Put(ctx, key, []byte{0}); err != nil {
return xerrors.Errorf("cache block validation: %w", err)
}
return nil
}
func (cs *ChainStore) UnmarkBlockAsValidated(ctx context.Context, blkid cid.Cid) error {
key := blockValidationCacheKeyPrefix.Instance(blkid.String())
if err := cs.metadataDs.Delete(ctx, key); err != nil {
return xerrors.Errorf("removing from valid block cache: %w", err)
}
return nil
}
func (cs *ChainStore) SetGenesis(ctx context.Context, b *types.BlockHeader) error {
ts, err := types.NewTipSet([]*types.BlockHeader{b})
if err != nil {
return err
}
if err := cs.PutTipSet(ctx, ts); err != nil {
return err
}
return cs.metadataDs.Put(ctx, dstore.NewKey("0"), b.Cid().Bytes())
}
func (cs *ChainStore) PutTipSet(ctx context.Context, ts *types.TipSet) error {
for _, b := range ts.Blocks() {
if err := cs.PersistBlockHeaders(ctx, b); err != nil {
return err
}
}
expanded, err := cs.expandTipset(ctx, ts.Blocks()[0])
if err != nil {
return xerrors.Errorf("errored while expanding tipset: %w", err)
}
log.Debugf("expanded %s into %s\n", ts.Cids(), expanded.Cids())
if err := cs.MaybeTakeHeavierTipSet(ctx, expanded); err != nil {
return xerrors.Errorf("MaybeTakeHeavierTipSet failed in PutTipSet: %w", err)
}
return nil
}
// MaybeTakeHeavierTipSet evaluates the incoming tipset and locks it in our
// internal state as our new head, if and only if it is heavier than the current
// head and does not exceed the maximum fork length.
func (cs *ChainStore) MaybeTakeHeavierTipSet(ctx context.Context, ts *types.TipSet) error {
for {
cs.heaviestLk.Lock()
if len(cs.reorgCh) < reorgChBuf/2 {
break
}
cs.heaviestLk.Unlock()
log.Errorf("reorg channel is heavily backlogged, waiting a bit before trying to take process new tipsets")
select {
case <-time.After(time.Second / 2):
case <-ctx.Done():
return ctx.Err()
}
}
defer cs.heaviestLk.Unlock()
w, err := cs.weight(ctx, cs.StateBlockstore(), ts)
if err != nil {
return err
}
heaviestW, err := cs.weight(ctx, cs.StateBlockstore(), cs.heaviest)
if err != nil {
return err
}
heavier := w.GreaterThan(heaviestW)
if w.Equals(heaviestW) && !ts.Equals(cs.heaviest) {
log.Errorw("weight draw", "currTs", cs.heaviest, "ts", ts)
heavier = breakWeightTie(ts, cs.heaviest)
}
if heavier {
// TODO: don't do this for initial sync. Now that we don't have a
// difference between 'bootstrap sync' and 'caught up' sync, we need
// some other heuristic.
exceeds, err := cs.exceedsForkLength(ctx, cs.heaviest, ts)
if err != nil {
return err
}
if exceeds {
return nil
}
return cs.takeHeaviestTipSet(ctx, ts)
}
return nil
}
// Check if the two tipsets have a fork length above `ForkLengthThreshold`.
// `synced` is the head of the chain we are currently synced to and `external`
// is the incoming tipset potentially belonging to a forked chain. It assumes
// the external chain has already been validated and available in the ChainStore.
// The "fast forward" case is covered in this logic as a valid fork of length 0.
//
// FIXME: We may want to replace some of the logic in `syncFork()` with this.
// `syncFork()` counts the length on both sides of the fork at the moment (we
// need to settle on that) but here we just enforce it on the `synced` side.
func (cs *ChainStore) exceedsForkLength(ctx context.Context, synced, external *types.TipSet) (bool, error) {
if synced == nil || external == nil {
// FIXME: If `cs.heaviest` is nil we should just bypass the entire
// `MaybeTakeHeavierTipSet` logic (instead of each of the called
// functions having to handle the nil case on their own).
return false, nil
}
var err error
// `forkLength`: number of tipsets we need to walk back from the our `synced`
// chain to the common ancestor with the new `external` head in order to
// adopt the fork.
for forkLength := 0; forkLength < int(build.ForkLengthThreshold); forkLength++ {
// First walk back as many tipsets in the external chain to match the
// `synced` height to compare them. If we go past the `synced` height
// the subsequent match will fail but it will still be useful to get
// closer to the `synced` head parent's height in the next loop.
for external.Height() > synced.Height() {
if external.Height() == 0 {
// We reached the genesis of the external chain without a match;
// this is considered a fork outside the allowed limit (of "infinite"
// length).
return true, nil
}
external, err = cs.LoadTipSet(ctx, external.Parents())
if err != nil {
return false, xerrors.Errorf("failed to load parent tipset in external chain: %w", err)
}
}
// Now check if we arrived at the common ancestor.
if synced.Equals(external) {
return false, nil
}
// Now check to see if we've walked back to the checkpoint.
if synced.Equals(cs.checkpoint) {
return true, nil
}
// If we didn't, go back *one* tipset on the `synced` side (incrementing
// the `forkLength`).
if synced.Height() == 0 {
// Same check as the `external` side, if we reach the start (genesis)
// there is no common ancestor.
return true, nil
}
synced, err = cs.LoadTipSet(ctx, synced.Parents())
if err != nil {
return false, xerrors.Errorf("failed to load parent tipset in synced chain: %w", err)
}
}
// We traversed the fork length allowed without finding a common ancestor.
return true, nil
}
// ForceHeadSilent forces a chain head tipset without triggering a reorg
// operation.
//
// CAUTION: Use it only for testing, such as to teleport the chain to a
// particular tipset to carry out a benchmark, verification, etc. on a chain
// segment.
func (cs *ChainStore) ForceHeadSilent(ctx context.Context, ts *types.TipSet) error {
log.Warnf("(!!!) forcing a new head silently; new head: %s", ts)
cs.heaviestLk.Lock()
defer cs.heaviestLk.Unlock()
if err := cs.removeCheckpoint(ctx); err != nil {
return err
}
cs.heaviest = ts
err := cs.writeHead(ctx, ts)
if err != nil {
err = xerrors.Errorf("failed to write chain head: %s", err)
}
return err
}
type reorg struct {
old *types.TipSet
new *types.TipSet
}
const reorgChBuf = 32
func (cs *ChainStore) reorgWorker(ctx context.Context, initialNotifees []ReorgNotifee) chan<- reorg {
out := make(chan reorg, reorgChBuf)
notifees := make([]ReorgNotifee, len(initialNotifees))
copy(notifees, initialNotifees)
cs.wg.Add(1)
go func() {
defer cs.wg.Done()
defer log.Warn("reorgWorker quit")
for {
select {
case n := <-cs.reorgNotifeeCh:
notifees = append(notifees, n)
case r := <-out:
revert, apply, err := cs.ReorgOps(ctx, r.old, r.new)
if err != nil {
log.Error("computing reorg ops failed: ", err)
continue
}
cs.journal.RecordEvent(cs.evtTypes[evtTypeHeadChange], func() interface{} {
return HeadChangeEvt{
From: r.old.Key(),
FromHeight: r.old.Height(),
To: r.new.Key(),
ToHeight: r.new.Height(),
RevertCount: len(revert),
ApplyCount: len(apply),
}
})
// reverse the apply array
for i := len(apply)/2 - 1; i >= 0; i-- {
opp := len(apply) - 1 - i
apply[i], apply[opp] = apply[opp], apply[i]
}
var toremove map[int]struct{}
for i, hcf := range notifees {
err := hcf(revert, apply)
switch err {
case nil:
case ErrNotifeeDone:
if toremove == nil {
toremove = make(map[int]struct{})
}
toremove[i] = struct{}{}
default:
log.Error("head change func errored (BAD): ", err)
}
}
if len(toremove) > 0 {
newNotifees := make([]ReorgNotifee, 0, len(notifees)-len(toremove))
for i, hcf := range notifees {
_, remove := toremove[i]
if remove {
continue
}
newNotifees = append(newNotifees, hcf)
}
notifees = newNotifees
}
case <-ctx.Done():
return
}
}
}()
return out
}
// takeHeaviestTipSet actually sets the incoming tipset as our head both in
// memory and in the ChainStore. It also sends a notification to deliver to
// ReorgNotifees.
func (cs *ChainStore) takeHeaviestTipSet(ctx context.Context, ts *types.TipSet) error {
_, span := trace.StartSpan(ctx, "takeHeaviestTipSet")
defer span.End()
if cs.heaviest != nil { // buf
if len(cs.reorgCh) > 0 {
log.Warnf("Reorg channel running behind, %d reorgs buffered", len(cs.reorgCh))
}
cs.reorgCh <- reorg{
old: cs.heaviest,
new: ts,
}
} else {
log.Warnf("no heaviest tipset found, using %s", ts.Cids())
}
span.AddAttributes(trace.BoolAttribute("newHead", true))
log.Infof("New heaviest tipset! %s (height=%d)", ts.Cids(), ts.Height())
cs.heaviest = ts
if err := cs.writeHead(ctx, ts); err != nil {
log.Errorf("failed to write chain head: %s", err)
return nil
}
return nil
}
// FlushValidationCache removes all results of block validation from the
// chain metadata store. Usually the first step after a new chain import.
func (cs *ChainStore) FlushValidationCache(ctx context.Context) error {
return FlushValidationCache(ctx, cs.metadataDs)
}
func FlushValidationCache(ctx context.Context, ds dstore.Batching) error {
log.Infof("clearing block validation cache...")
dsWalk, err := ds.Query(ctx, query.Query{
// Potential TODO: the validation cache is not a namespace on its own
// but is rather constructed as prefixed-key `foo:bar` via .Instance(), which
// in turn does not work with the filter, which can match only on `foo/bar`
//
// If this is addressed (blockcache goes into its own sub-namespace) then
// strings.HasPrefix(...) below can be skipped
//
//Prefix: blockValidationCacheKeyPrefix.String()
KeysOnly: true,
})
if err != nil {
return xerrors.Errorf("failed to initialize key listing query: %w", err)
}
allKeys, err := dsWalk.Rest()
if err != nil {
return xerrors.Errorf("failed to run key listing query: %w", err)
}
batch, err := ds.Batch(ctx)
if err != nil {
return xerrors.Errorf("failed to open a DS batch: %w", err)
}
delCnt := 0
for _, k := range allKeys {
if strings.HasPrefix(k.Key, blockValidationCacheKeyPrefix.String()) {
delCnt++
batch.Delete(ctx, dstore.RawKey(k.Key)) // nolint:errcheck
}
}
if err := batch.Commit(ctx); err != nil {
return xerrors.Errorf("failed to commit the DS batch: %w", err)
}
log.Infof("%d block validation entries cleared.", delCnt)
return nil
}
// SetHead sets the chainstores current 'best' head node.
// This should only be called if something is broken and needs fixing.
//
// This function will bypass and remove any checkpoints.
func (cs *ChainStore) SetHead(ctx context.Context, ts *types.TipSet) error {
cs.heaviestLk.Lock()
defer cs.heaviestLk.Unlock()
if err := cs.removeCheckpoint(ctx); err != nil {
return err
}
return cs.takeHeaviestTipSet(context.TODO(), ts)
}
// RemoveCheckpoint removes the current checkpoint.
func (cs *ChainStore) RemoveCheckpoint(ctx context.Context) error {
cs.heaviestLk.Lock()
defer cs.heaviestLk.Unlock()
return cs.removeCheckpoint(ctx)
}
func (cs *ChainStore) removeCheckpoint(ctx context.Context) error {
if err := cs.metadataDs.Delete(ctx, checkpointKey); err != nil {
return err
}
cs.checkpoint = nil
return nil
}
// SetCheckpoint will set a checkpoint past which the chainstore will not allow forks.
//
// NOTE: Checkpoints cannot be set beyond ForkLengthThreshold epochs in the past.
func (cs *ChainStore) SetCheckpoint(ctx context.Context, ts *types.TipSet) error {
tskBytes, err := json.Marshal(ts.Key())
if err != nil {
return err
}
cs.heaviestLk.Lock()
defer cs.heaviestLk.Unlock()
if ts.Height() > cs.heaviest.Height() {
return xerrors.Errorf("cannot set a checkpoint in the future")
}
// Otherwise, this operation could get _very_ expensive.
if cs.heaviest.Height()-ts.Height() > build.ForkLengthThreshold {
return xerrors.Errorf("cannot set a checkpoint before the fork threshold")
}
if !ts.Equals(cs.heaviest) {
anc, err := cs.IsAncestorOf(ctx, ts, cs.heaviest)
if err != nil {
return xerrors.Errorf("cannot determine whether checkpoint tipset is in main-chain: %w", err)
}
if !anc {
return xerrors.Errorf("cannot mark tipset as checkpoint, since it isn't in the main-chain: %w", err)
}
}
err = cs.metadataDs.Put(ctx, checkpointKey, tskBytes)
if err != nil {
return err
}
cs.checkpoint = ts
return nil
}
func (cs *ChainStore) GetCheckpoint() *types.TipSet {
cs.heaviestLk.RLock()
chkpt := cs.checkpoint
cs.heaviestLk.RUnlock()
return chkpt
}
// Contains returns whether our BlockStore has all blocks in the supplied TipSet.
func (cs *ChainStore) Contains(ctx context.Context, ts *types.TipSet) (bool, error) {
for _, c := range ts.Cids() {
has, err := cs.chainBlockstore.Has(ctx, c)
if err != nil {
return false, err
}
if !has {
return false, nil
}
}
return true, nil
}
// GetBlock fetches a BlockHeader with the supplied CID. It returns | func (cs *ChainStore) GetBlock(ctx context.Context, c cid.Cid) (*types.BlockHeader, error) {
var blk *types.BlockHeader
err := cs.chainLocalBlockstore.View(ctx, c, func(b []byte) (err error) {
blk, err = types.DecodeBlock(b)
return err
})
return blk, err
}
func (cs *ChainStore) LoadTipSet(ctx context.Context, tsk types.TipSetKey) (*types.TipSet, error) {
v, ok := cs.tsCache.Get(tsk)
if ok {
return v.(*types.TipSet), nil
}
// Fetch tipset block headers from blockstore in parallel
var eg errgroup.Group
cids := tsk.Cids()
blks := make([]*types.BlockHeader, len(cids))
for i, c := range cids {
i, c := i, c
eg.Go(func() error {
b, err := cs.GetBlock(ctx, c)
if err != nil {
return xerrors.Errorf("get block %s: %w", c, err)
}
blks[i] = b
return nil
})
}
err := eg.Wait()
if err != nil {
return nil, err
}
ts, err := types.NewTipSet(blks)
if err != nil {
return nil, err
}
cs.tsCache.Add(tsk, ts)
return ts, nil
}
// IsAncestorOf returns true if 'a' is an ancestor of 'b'
func (cs *ChainStore) IsAncestorOf(ctx context.Context, a, b *types.TipSet) (bool, error) {
if b.Height() <= a.Height() {
return false, nil
}
cur := b
for !a.Equals(cur) && cur.Height() > a.Height() {
next, err := cs.LoadTipSet(ctx, cur.Parents())
if err != nil {
return false, err
}
cur = next
}
return cur.Equals(a), nil
}
func (cs *ChainStore) NearestCommonAncestor(ctx context.Context, a, b *types.TipSet) (*types.TipSet, error) {
l, _, err := cs.ReorgOps(ctx, a, b)
if err != nil {
return nil, err
}
return cs.LoadTipSet(ctx, l[len(l)-1].Parents())
}
// ReorgOps takes two tipsets (which can be at different heights), and walks
// their corresponding chains backwards one step at a time until we find
// a common ancestor. It then returns the respective chain segments that fork
// from the identified ancestor, in reverse order, where the first element of
// each slice is the supplied tipset, and the last element is the common
// ancestor.
//
// If an error happens along the way, we return the error with nil slices.
func (cs *ChainStore) ReorgOps(ctx context.Context, a, b *types.TipSet) ([]*types.TipSet, []*types.TipSet, error) {
return ReorgOps(ctx, cs.LoadTipSet, a, b)
}
func ReorgOps(ctx context.Context, lts func(ctx context.Context, _ types.TipSetKey) (*types.TipSet, error), a, b *types.TipSet) ([]*types.TipSet, []*types.TipSet, error) {
left := a
right := b
var leftChain, rightChain []*types.TipSet
for !left.Equals(right) {
if left.Height() > right.Height() {
leftChain = append(leftChain, left)
par, err := lts(ctx, left.Parents())
if err != nil {
return nil, nil, err
}
left = par
} else {
rightChain = append(rightChain, right)
par, err := lts(ctx, right.Parents())
if err != nil {
log.Infof("failed to fetch right.Parents: %s", err)
return nil, nil, err
}
right = par
}
}
return leftChain, rightChain, nil
}
// GetHeaviestTipSet returns the current heaviest tipset known (i.e. our head).
func (cs *ChainStore) GetHeaviestTipSet() (ts *types.TipSet) {
cs.heaviestLk.RLock()
ts = cs.heaviest
cs.heaviestLk.RUnlock()
return
}
func (cs *ChainStore) AddToTipSetTracker(ctx context.Context, b *types.BlockHeader) error {
cs.tstLk.Lock()
defer cs.tstLk.Unlock()
tss := cs.tipsets[b.Height]
for _, oc := range tss {
if oc == b.Cid() {
log.Debug("tried to add block to tipset tracker that was already there")
return nil
}
h, err := cs.GetBlock(ctx, oc)
if err == nil && h != nil {
if h.Miner == b.Miner {
log.Warnf("Have multiple blocks from miner %s at height %d in our tipset cache %s-%s", b.Miner, b.Height, b.Cid(), h.Cid())
}
}
}
// This function is called 5 times per epoch on average
// It is also called with tipsets that are done with initial validation
// so they cannot be from the future.
// We are guaranteed not to use tipsets older than 900 epochs (fork limit)
// This means that we ideally want to keep only most recent 900 epochs in here
// Golang's map iteration starts at a random point in a map.
// With 5 tries per epoch, and 900 entries to keep, on average we will have
// ~136 garbage entires in the `cs.tipsets` map. (solve for 1-(1-x/(900+x))^5 == 0.5)
// Seems good enough to me
for height := range cs.tipsets {
if height < b.Height-build.Finality {
delete(cs.tipsets, height)
}
break
}
cs.tipsets[b.Height] = append(tss, b.Cid())
return nil
}
func (cs *ChainStore) PersistBlockHeaders(ctx context.Context, b ...*types.BlockHeader) error {
sbs := make([]block.Block, len(b))
for i, header := range b {
var err error
sbs[i], err = header.ToStorageBlock()
if err != nil {
return err
}
}
batchSize := 256
calls := len(b) / batchSize
var err error
for i := 0; i <= calls; i++ {
start := batchSize * i
end := start + batchSize
if end > len(b) {
end = len(b)
}
err = multierr.Append(err, cs.chainLocalBlockstore.PutMany(ctx, sbs[start:end]))
}
return err
}
func (cs *ChainStore) expandTipset(ctx context.Context, b *types.BlockHeader) (*types.TipSet, error) {
// Hold lock for the whole function for now, if it becomes a problem we can
// fix pretty easily
cs.tstLk.Lock()
defer cs.tstLk.Unlock()
all := []*types.BlockHeader{b}
tsets, ok := cs.tipsets[b.Height]
if !ok {
return types.NewTipSet(all)
}
inclMiners := map[address.Address]cid.Cid{b.Miner: b.Cid()}
for _, bhc := range tsets {
if bhc == b.Cid() {
continue
}
h, err := cs.GetBlock(ctx, bhc)
if err != nil {
return nil, xerrors.Errorf("failed to load block (%s) for tipset expansion: %w", bhc, err)
}
if cid, found := inclMiners[h.Miner]; found {
log.Warnf("Have multiple blocks from miner %s at height %d in our tipset cache %s-%s", h.Miner, h.Height, h.Cid(), cid)
continue
}
if types.CidArrsEqual(h.Parents, b.Parents) {
all = append(all, h)
inclMiners[h.Miner] = bhc
}
}
// TODO: other validation...?
return types.NewTipSet(all)
}
func (cs *ChainStore) AddBlock(ctx context.Context, b *types.BlockHeader) error {
if err := cs.PersistBlockHeaders(ctx, b); err != nil {
return err
}
ts, err := cs.expandTipset(ctx, b)
if err != nil {
return err
}
if err := cs.MaybeTakeHeavierTipSet(ctx, ts); err != nil {
return xerrors.Errorf("MaybeTakeHeavierTipSet failed: %w", err)
}
return nil
}
func (cs *ChainStore) GetGenesis(ctx context.Context) (*types.BlockHeader, error) {
data, err := cs.metadataDs.Get(ctx, dstore.NewKey("0"))
if err != nil {
return nil, err
}
c, err := cid.Cast(data)
if err != nil {
return nil, err
}
return cs.GetBlock(ctx, c)
}
// GetPath returns the sequence of atomic head change operations that
// need to be applied in order to switch the head of the chain from the `from`
// tipset to the `to` tipset.
func (cs *ChainStore) GetPath(ctx context.Context, from types.TipSetKey, to types.TipSetKey) ([]*api.HeadChange, error) {
fts, err := cs.LoadTipSet(ctx, from)
if err != nil {
return nil, xerrors.Errorf("loading from tipset %s: %w", from, err)
}
tts, err := cs.LoadTipSet(ctx, to)
if err != nil {
return nil, xerrors.Errorf("loading to tipset %s: %w", to, err)
}
revert, apply, err := cs.ReorgOps(ctx, fts, tts)
if err != nil {
return nil, xerrors.Errorf("error getting tipset branches: %w", err)
}
path := make([]*api.HeadChange, len(revert)+len(apply))
for i, r := range revert {
path[i] = &api.HeadChange{Type: HCRevert, Val: r}
}
for j, i := 0, len(apply)-1; i >= 0; j, i = j+1, i-1 {
path[j+len(revert)] = &api.HeadChange{Type: HCApply, Val: apply[i]}
}
return path, nil
}
// ChainBlockstore returns the chain blockstore. Currently the chain and state
// // stores are both backed by the same physical store, albeit with different
// // caching policies, but in the future they will segregate.
func (cs *ChainStore) ChainBlockstore() bstore.Blockstore {
return cs.chainBlockstore
}
// StateBlockstore returns the state blockstore. Currently the chain and state
// stores are both backed by the same physical store, albeit with different
// caching policies, but in the future they will segregate.
func (cs *ChainStore) StateBlockstore() bstore.Blockstore {
return cs.stateBlockstore
}
func ActorStore(ctx context.Context, bs bstore.Blockstore) adt.Store {
return adt.WrapStore(ctx, cbor.NewCborStore(bs))
}
func (cs *ChainStore) ActorStore(ctx context.Context) adt.Store {
return ActorStore(ctx, cs.stateBlockstore)
}
func (cs *ChainStore) TryFillTipSet(ctx context.Context, ts *types.TipSet) (*FullTipSet, error) {
var out []*types.FullBlock
for _, b := range ts.Blocks() {
bmsgs, smsgs, crossmsg, err := cs.MessagesForBlock(ctx, b)
if err != nil {
// TODO: check for 'not found' errors, and only return nil if this
// is actually a 'not found' error
return nil, nil
}
fb := &types.FullBlock{
Header: b,
BlsMessages: bmsgs,
SecpkMessages: smsgs,
CrossMessages: crossmsg,
}
out = append(out, fb)
}
return NewFullTipSet(out), nil
}
// GetTipsetByHeight returns the tipset on the chain behind 'ts' at the given
// height. In the case that the given height is a null round, the 'prev' flag
// selects the tipset before the null round if true, and the tipset following
// the null round if false.
func (cs *ChainStore) GetTipsetByHeight(ctx context.Context, h abi.ChainEpoch, ts *types.TipSet, prev bool) (*types.TipSet, error) {
if ts == nil {
ts = cs.GetHeaviestTipSet()
}
if h > ts.Height() {
return nil, xerrors.Errorf("looking for tipset with height greater than start point")
}
if h == ts.Height() {
return ts, nil
}
lbts, err := cs.cindex.GetTipsetByHeight(ctx, ts, h)
if err != nil {
return nil, err
}
if lbts.Height() < h {
log.Warnf("chain index returned the wrong tipset at height %d, using slow retrieval", h)
lbts, err = cs.cindex.GetTipsetByHeightWithoutCache(ctx, ts, h)
if err != nil {
return nil, err
}
}
if lbts.Height() == h || !prev {
return lbts, nil
}
return cs.LoadTipSet(ctx, lbts.Parents())
}
func (cs *ChainStore) Weight(ctx context.Context, hts *types.TipSet) (types.BigInt, error) { // todo remove
return cs.weight(ctx, cs.StateBlockstore(), hts)
}
// true if ts1 wins according to the filecoin tie-break rule
func breakWeightTie(ts1, ts2 *types.TipSet) bool {
s := len(ts1.Blocks())
if s > len(ts2.Blocks()) {
s = len(ts2.Blocks())
}
// blocks are already sorted by ticket
for i := 0; i < s; i++ {
if ts1.Blocks()[i].Ticket.Less(ts2.Blocks()[i].Ticket) {
log.Infof("weight tie broken in favour of %s", ts1.Key())
return true
}
}
log.Infof("weight tie left unbroken, default to %s", ts2.Key())
return false
}
func (cs *ChainStore) GetTipSetFromKey(ctx context.Context, tsk types.TipSetKey) (*types.TipSet, error) {
if tsk.IsEmpty() {
return cs.GetHeaviestTipSet(), nil
}
return cs.LoadTipSet(ctx, tsk)
}
func (cs *ChainStore) GetLatestBeaconEntry(ctx context.Context, ts *types.TipSet) (*types.BeaconEntry, error) {
cur := ts
for i := 0; i < 20; i++ {
cbe := cur.Blocks()[0].BeaconEntries
if len(cbe) > 0 {
return &cbe[len(cbe)-1], nil
}
if cur.Height() == 0 {
return nil, xerrors.Errorf("made it back to genesis block without finding beacon entry")
}
next, err := cs.LoadTipSet(ctx, cur.Parents())
if err != nil {
return nil, xerrors.Errorf("failed to load parents when searching back for latest beacon entry: %w", err)
}
cur = next
}
if os.Getenv("LOTUS_IGNORE_DRAND") == "_yes_" {
return &types.BeaconEntry{
Data: []byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
}, nil
}
return nil, xerrors.Errorf("found NO beacon entries in the 20 latest tipsets")
} | // blockstore.ErrNotFound if the block was not found in the BlockStore. |
device_tag.go | // Copyright 2020 Herman Slatman
//
// 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 client
import (
"fmt"
"github.com/hslatman/balena-sdk-go/pkg/models"
"github.com/m7shapan/njson"
"github.com/tidwall/gjson"
)
type DeviceTagResource struct {
client *Client
endpoint string
deviceTagID int
modifiers *ODataModifiers
}
func NewDeviceTagResource(c *Client, deviceTagID int) *DeviceTagResource |
func (c *Client) DeviceTag(deviceTagID int) *DeviceTagResource {
return NewDeviceTagResource(c, deviceTagID)
}
func (r *DeviceTagResource) Get() (models.DeviceTag, error) {
tag := models.DeviceTag{}
resp, err := r.client.get(r.endpoint, r.modifiers)
if err != nil {
return tag, err
}
data := gjson.GetBytes(resp.Body(), "d") // get data; a list of results
first := data.Get("0") // first (and only) tag, if found
if !first.Exists() {
return tag, fmt.Errorf("%s not found", r.endpoint)
}
if err := njson.Unmarshal([]byte(first.Raw), &tag); err != nil {
return tag, err
}
return tag, nil
}
func (r *DeviceTagResource) Update(value string) error {
body := map[string]interface{}{
"value": value,
}
_, err := r.client.patch(r.endpoint, r.modifiers, body)
if err != nil {
return err
}
return nil
}
func (r *DeviceTagResource) Delete() error {
_, err := r.client.delete(r.endpoint, r.modifiers)
if err != nil {
return err
}
return nil
}
func (r *DeviceTagResource) Select(s string) *DeviceTagResource {
r.modifiers.AddSelect(s)
return r
}
func (r *DeviceTagResource) Expand(s string) *DeviceTagResource {
r.modifiers.AddExpand(s)
return r
}
| {
return &DeviceTagResource{
client: c,
endpoint: fmt.Sprintf("%s(%d)", deviceTagsEndpoint, deviceTagID),
deviceTagID: deviceTagID,
modifiers: NewODataModifiers(c),
}
} |
cache.go | package catalog
import (
"fmt"
"strings"
)
type value struct {
value interface{}
dirty bool
}
var cache = map[OID]value{}
func GetV(oid OID) (interface{}, bool) {
v, ok := cache[oid]
if ok {
return v.value, v.dirty
}
return nil, false
}
func PutV(oid OID, v interface{}, dirty bool) {
cache[oid] = value{
value: v,
dirty: dirty,
}
}
func Find(prefix OID, suffix Suffix, value interface{}) (OID, bool) | {
s := fmt.Sprintf("%v", value)
for k, v := range cache {
prefixed := strings.HasPrefix(string(k), string(prefix))
suffixed := strings.HasSuffix(string(k), string(suffix))
if prefixed && suffixed && s == fmt.Sprintf("%v", v.value) {
return k, true
}
}
return OID(""), false
} |
|
test_migrate.py | import pytest
from pytest_mock import MockerFixture
from aerich.ddl.mysql import MysqlDDL
from aerich.ddl.postgres import PostgresDDL
from aerich.ddl.sqlite import SqliteDDL
from aerich.exceptions import NotSupportError
from aerich.migrate import Migrate
from aerich.utils import get_models_describe
old_models_describe = {
"models.Category": {
"name": "models.Category",
"app": "models",
"table": "category",
"abstract": False,
"description": None,
"docstring": None,
"unique_together": [],
"pk_field": {
"name": "id",
"field_type": "IntField",
"db_column": "id",
"python_type": "int",
"generated": True,
"nullable": False,
"unique": True,
"indexed": True,
"default": None,
"description": None,
"docstring": None,
"constraints": {"ge": 1, "le": 2147483647},
"db_field_types": {"": "INT"},
},
"data_fields": [
{
"name": "slug",
"field_type": "CharField",
"db_column": "slug",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 200},
"db_field_types": {"": "VARCHAR(200)"},
},
{
"name": "name",
"field_type": "CharField",
"db_column": "name",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 200},
"db_field_types": {"": "VARCHAR(200)"},
},
{
"name": "created_at",
"field_type": "DatetimeField",
"db_column": "created_at",
"python_type": "datetime.datetime",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"readOnly": True},
"db_field_types": {
"": "TIMESTAMP",
"mysql": "DATETIME(6)",
"postgres": "TIMESTAMPTZ",
},
"auto_now_add": True,
"auto_now": False,
},
{
"name": "user_id",
"field_type": "IntField",
"db_column": "user_id",
"python_type": "int",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": "User",
"docstring": None,
"constraints": {"ge": 1, "le": 2147483647},
"db_field_types": {"": "INT"},
},
],
"fk_fields": [
{
"name": "user",
"field_type": "ForeignKeyFieldInstance",
"python_type": "models.User",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": "User",
"docstring": None,
"constraints": {},
"raw_field": "user_id",
"on_delete": "CASCADE",
}
],
"backward_fk_fields": [],
"o2o_fields": [],
"backward_o2o_fields": [],
"m2m_fields": [
{
"name": "products",
"field_type": "ManyToManyFieldInstance",
"python_type": "models.Product",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {},
"model_name": "models.Product",
"related_name": "categories",
"forward_key": "product_id",
"backward_key": "category_id",
"through": "product_category",
"on_delete": "CASCADE",
"_generated": True,
}
],
},
"models.Config": {
"name": "models.Config",
"app": "models",
"table": "configs",
"abstract": False,
"description": None,
"docstring": None,
"unique_together": [],
"pk_field": {
"name": "id",
"field_type": "IntField",
"db_column": "id",
"python_type": "int",
"generated": True,
"nullable": False,
"unique": True,
"indexed": True,
"default": None,
"description": None,
"docstring": None,
"constraints": {"ge": 1, "le": 2147483647},
"db_field_types": {"": "INT"},
},
"data_fields": [
{
"name": "label",
"field_type": "CharField",
"db_column": "label",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 200},
"db_field_types": {"": "VARCHAR(200)"},
},
{
"name": "key",
"field_type": "CharField",
"db_column": "key",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 20},
"db_field_types": {"": "VARCHAR(20)"},
},
{
"name": "value",
"field_type": "JSONField",
"db_column": "value",
"python_type": "Union[dict, list]",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {},
"db_field_types": {"": "TEXT", "postgres": "JSONB"},
},
{
"name": "status",
"field_type": "IntEnumFieldInstance",
"db_column": "status",
"python_type": "int",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": 1,
"description": "on: 1\noff: 0",
"docstring": None,
"constraints": {"ge": -32768, "le": 32767},
"db_field_types": {"": "SMALLINT"},
},
],
"fk_fields": [],
"backward_fk_fields": [],
"o2o_fields": [],
"backward_o2o_fields": [],
"m2m_fields": [],
},
"models.Email": {
"name": "models.Email",
"app": "models",
"table": "email",
"abstract": False,
"description": None,
"docstring": None,
"unique_together": [],
"pk_field": {
"name": "id",
"field_type": "IntField",
"db_column": "id",
"python_type": "int",
"generated": True,
"nullable": False,
"unique": True,
"indexed": True,
"default": None,
"description": None,
"docstring": None,
"constraints": {"ge": 1, "le": 2147483647},
"db_field_types": {"": "INT"},
},
"data_fields": [
{
"name": "email",
"field_type": "CharField",
"db_column": "email",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 200},
"db_field_types": {"": "VARCHAR(200)"},
},
{
"name": "is_primary",
"field_type": "BooleanField",
"db_column": "is_primary",
"python_type": "bool",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": False,
"description": None,
"docstring": None,
"constraints": {},
"db_field_types": {"": "BOOL", "sqlite": "INT"},
},
{
"name": "user_id",
"field_type": "IntField",
"db_column": "user_id",
"python_type": "int",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"ge": 1, "le": 2147483647},
"db_field_types": {"": "INT"},
},
],
"fk_fields": [
{
"name": "user",
"field_type": "ForeignKeyFieldInstance",
"python_type": "models.User",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {},
"raw_field": "user_id",
"on_delete": "CASCADE",
}
],
"backward_fk_fields": [],
"o2o_fields": [],
"backward_o2o_fields": [],
"m2m_fields": [],
},
"models.Product": {
"name": "models.Product",
"app": "models",
"table": "product",
"abstract": False,
"description": None,
"docstring": None,
"unique_together": [],
"pk_field": {
"name": "id",
"field_type": "IntField",
"db_column": "id",
"python_type": "int",
"generated": True,
"nullable": False,
"unique": True,
"indexed": True,
"default": None,
"description": None,
"docstring": None,
"constraints": {"ge": 1, "le": 2147483647},
"db_field_types": {"": "INT"},
},
"data_fields": [
{
"name": "name",
"field_type": "CharField",
"db_column": "name",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 50},
"db_field_types": {"": "VARCHAR(50)"},
},
{
"name": "view_num",
"field_type": "IntField",
"db_column": "view_num",
"python_type": "int",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": "View Num",
"docstring": None,
"constraints": {"ge": -2147483648, "le": 2147483647},
"db_field_types": {"": "INT"},
},
{
"name": "sort",
"field_type": "IntField",
"db_column": "sort",
"python_type": "int",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"ge": -2147483648, "le": 2147483647},
"db_field_types": {"": "INT"},
},
{
"name": "is_reviewed",
"field_type": "BooleanField",
"db_column": "is_reviewed",
"python_type": "bool",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": "Is Reviewed",
"docstring": None,
"constraints": {},
"db_field_types": {"": "BOOL", "sqlite": "INT"},
},
{
"name": "type",
"field_type": "IntEnumFieldInstance",
"db_column": "type",
"python_type": "int",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": "Product Type",
"docstring": None,
"constraints": {"ge": -32768, "le": 32767},
"db_field_types": {"": "SMALLINT"},
},
{
"name": "image",
"field_type": "CharField",
"db_column": "image",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 200},
"db_field_types": {"": "VARCHAR(200)"},
},
{
"name": "body",
"field_type": "TextField",
"db_column": "body",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {},
"db_field_types": {"": "TEXT", "mysql": "LONGTEXT"},
},
{
"name": "created_at",
"field_type": "DatetimeField",
"db_column": "created_at",
"python_type": "datetime.datetime",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"readOnly": True},
"db_field_types": {
"": "TIMESTAMP",
"mysql": "DATETIME(6)",
"postgres": "TIMESTAMPTZ",
},
"auto_now_add": True,
"auto_now": False,
},
],
"fk_fields": [],
"backward_fk_fields": [],
"o2o_fields": [],
"backward_o2o_fields": [],
"m2m_fields": [
{
"name": "categories",
"field_type": "ManyToManyFieldInstance",
"python_type": "models.Category",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {},
"model_name": "models.Category",
"related_name": "products",
"forward_key": "category_id",
"backward_key": "product_id",
"through": "product_category",
"on_delete": "CASCADE",
"_generated": False,
}
],
},
"models.User": {
"name": "models.User",
"app": "models",
"table": "user",
"abstract": False,
"description": None,
"docstring": None,
"unique_together": [],
"pk_field": {
"name": "id",
"field_type": "IntField",
"db_column": "id",
"python_type": "int",
"generated": True,
"nullable": False,
"unique": True,
"indexed": True,
"default": None,
"description": None,
"docstring": None,
"constraints": {"ge": 1, "le": 2147483647},
"db_field_types": {"": "INT"},
},
"data_fields": [
{
"name": "username",
"field_type": "CharField",
"db_column": "username",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 20},
"db_field_types": {"": "VARCHAR(20)"},
},
{
"name": "password",
"field_type": "CharField",
"db_column": "password",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 200},
"db_field_types": {"": "VARCHAR(200)"},
},
{
"name": "last_login",
"field_type": "DatetimeField",
"db_column": "last_login",
"python_type": "datetime.datetime",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": "<function None.now>",
"description": "Last Login",
"docstring": None,
"constraints": {},
"db_field_types": {
"": "TIMESTAMP",
"mysql": "DATETIME(6)",
"postgres": "TIMESTAMPTZ",
},
"auto_now_add": False,
"auto_now": False,
},
{
"name": "is_active",
"field_type": "BooleanField",
"db_column": "is_active",
"python_type": "bool",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": True,
"description": "Is Active",
"docstring": None,
"constraints": {},
"db_field_types": {"": "BOOL", "sqlite": "INT"},
},
{
"name": "is_superuser",
"field_type": "BooleanField",
"db_column": "is_superuser",
"python_type": "bool",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": False,
"description": "Is SuperUser",
"docstring": None,
"constraints": {},
"db_field_types": {"": "BOOL", "sqlite": "INT"},
},
{
"name": "avatar",
"field_type": "CharField",
"db_column": "avatar",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": "",
"description": None,
"docstring": None,
"constraints": {"max_length": 200},
"db_field_types": {"": "VARCHAR(200)"},
},
{
"name": "intro",
"field_type": "TextField",
"db_column": "intro",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": "",
"description": None,
"docstring": None,
"constraints": {},
"db_field_types": {"": "TEXT", "mysql": "LONGTEXT"},
},
],
"fk_fields": [],
"backward_fk_fields": [
{
"name": "categorys",
"field_type": "BackwardFKRelation",
"python_type": "models.Category",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": "User",
"docstring": None,
"constraints": {},
},
{
"name": "emails",
"field_type": "BackwardFKRelation",
"python_type": "models.Email",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {},
},
],
"o2o_fields": [],
"backward_o2o_fields": [],
"m2m_fields": [],
},
"models.Aerich": {
"name": "models.Aerich",
"app": "models",
"table": "aerich",
"abstract": False,
"description": None,
"docstring": None,
"unique_together": [],
"pk_field": {
"name": "id",
"field_type": "IntField",
"db_column": "id",
"python_type": "int",
"generated": True,
"nullable": False,
"unique": True,
"indexed": True,
"default": None,
"description": None,
"docstring": None,
"constraints": {"ge": 1, "le": 2147483647},
"db_field_types": {"": "INT"},
},
"data_fields": [
{
"name": "version",
"field_type": "CharField",
"db_column": "version",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 255},
"db_field_types": {"": "VARCHAR(255)"},
},
{
"name": "app",
"field_type": "CharField",
"db_column": "app",
"python_type": "str",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {"max_length": 20},
"db_field_types": {"": "VARCHAR(20)"},
},
{
"name": "content",
"field_type": "JSONField",
"db_column": "content",
"python_type": "Union[dict, list]",
"generated": False,
"nullable": False,
"unique": False,
"indexed": False,
"default": None,
"description": None,
"docstring": None,
"constraints": {},
"db_field_types": {"": "TEXT", "postgres": "JSONB"},
},
],
"fk_fields": [],
"backward_fk_fields": [],
"o2o_fields": [],
"backward_o2o_fields": [],
"m2m_fields": [],
},
}
def test_migrate(mocker: MockerFixture):
|
def test_sort_all_version_files(mocker):
mocker.patch(
"os.listdir",
return_value=[
"1_datetime_update.sql",
"11_datetime_update.sql",
"10_datetime_update.sql",
"2_datetime_update.sql",
],
)
Migrate.migrate_location = "."
assert Migrate.get_all_version_files() == [
"1_datetime_update.sql",
"2_datetime_update.sql",
"10_datetime_update.sql",
"11_datetime_update.sql",
]
def test_sort_sql_and_py_version_files(mocker):
mocker.patch(
"os.listdir",
return_value=[
"1_datetime_update.sql",
"11_datetime_update.sql",
"10_datetime_update.py",
"2_datetime_update.sql",
"3_datetime_update.py",
],
)
Migrate.migrate_location = "."
assert Migrate.get_all_version_files() == [
"1_datetime_update.sql",
"2_datetime_update.sql",
"3_datetime_update.py",
"10_datetime_update.py",
"11_datetime_update.sql",
]
| """
models.py diff with old_models.py
- change email pk: id -> email_id
- add field: Email.address
- add fk: Config.user
- drop fk: Email.user
- drop field: User.avatar
- add index: Email.email
- add many to many: Email.users
- remove unique: User.username
- change column: length User.password
- add unique_together: (name,type) of Product
- alter default: Config.status
- rename column: Product.image -> Product.pic
"""
mocker.patch("click.prompt", side_effect=(True,))
models_describe = get_models_describe("models")
Migrate.app = "models"
if isinstance(Migrate.ddl, SqliteDDL):
with pytest.raises(NotSupportError):
Migrate.diff_models(old_models_describe, models_describe)
Migrate.diff_models(models_describe, old_models_describe, False)
else:
Migrate.diff_models(old_models_describe, models_describe)
Migrate.diff_models(models_describe, old_models_describe, False)
Migrate._merge_operators()
if isinstance(Migrate.ddl, MysqlDDL):
assert sorted(Migrate.upgrade_operators) == sorted(
[
"ALTER TABLE `category` MODIFY COLUMN `name` VARCHAR(200)",
"ALTER TABLE `category` MODIFY COLUMN `slug` VARCHAR(100) NOT NULL",
"ALTER TABLE `config` ADD `user_id` INT NOT NULL COMMENT 'User'",
"ALTER TABLE `config` ADD CONSTRAINT `fk_config_user_17daa970` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE",
"ALTER TABLE `config` ALTER COLUMN `status` DROP DEFAULT",
"ALTER TABLE `email` ADD `address` VARCHAR(200) NOT NULL",
"ALTER TABLE `email` DROP COLUMN `user_id`",
"ALTER TABLE `configs` RENAME TO `config`",
"ALTER TABLE `product` RENAME COLUMN `image` TO `pic`",
"ALTER TABLE `email` RENAME COLUMN `id` TO `email_id`",
"ALTER TABLE `email` DROP FOREIGN KEY `fk_email_user_5b58673d`",
"ALTER TABLE `email` ADD INDEX `idx_email_email_4a1a33` (`email`)",
"ALTER TABLE `product` ADD UNIQUE INDEX `uid_product_name_f14935` (`name`, `type`)",
"ALTER TABLE `product` ALTER COLUMN `view_num` SET DEFAULT 0",
"ALTER TABLE `user` DROP COLUMN `avatar`",
"ALTER TABLE `user` MODIFY COLUMN `password` VARCHAR(100) NOT NULL",
"CREATE TABLE IF NOT EXISTS `newmodel` (\n `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n `name` VARCHAR(50) NOT NULL\n) CHARACTER SET utf8mb4;",
"ALTER TABLE `user` ADD UNIQUE INDEX `uid_user_usernam_9987ab` (`username`)",
"CREATE TABLE `email_user` (`email_id` INT NOT NULL REFERENCES `email` (`email_id`) ON DELETE CASCADE,`user_id` INT NOT NULL REFERENCES `user` (`id`) ON DELETE CASCADE) CHARACTER SET utf8mb4",
]
)
assert sorted(Migrate.downgrade_operators) == sorted(
[
"ALTER TABLE `category` MODIFY COLUMN `name` VARCHAR(200) NOT NULL",
"ALTER TABLE `category` MODIFY COLUMN `slug` VARCHAR(200) NOT NULL",
"ALTER TABLE `config` DROP COLUMN `user_id`",
"ALTER TABLE `config` DROP FOREIGN KEY `fk_config_user_17daa970`",
"ALTER TABLE `config` ALTER COLUMN `status` SET DEFAULT 1",
"ALTER TABLE `email` ADD `user_id` INT NOT NULL",
"ALTER TABLE `email` DROP COLUMN `address`",
"ALTER TABLE `config` RENAME TO `configs`",
"ALTER TABLE `product` RENAME COLUMN `pic` TO `image`",
"ALTER TABLE `email` RENAME COLUMN `email_id` TO `id`",
"ALTER TABLE `email` ADD CONSTRAINT `fk_email_user_5b58673d` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE",
"ALTER TABLE `email` DROP INDEX `idx_email_email_4a1a33`",
"ALTER TABLE `product` DROP INDEX `uid_product_name_f14935`",
"ALTER TABLE `product` ALTER COLUMN `view_num` DROP DEFAULT",
"ALTER TABLE `user` ADD `avatar` VARCHAR(200) NOT NULL DEFAULT ''",
"ALTER TABLE `user` DROP INDEX `idx_user_usernam_9987ab`",
"ALTER TABLE `user` MODIFY COLUMN `password` VARCHAR(200) NOT NULL",
"DROP TABLE IF EXISTS `email_user`",
"DROP TABLE IF EXISTS `newmodel`",
]
)
elif isinstance(Migrate.ddl, PostgresDDL):
assert sorted(Migrate.upgrade_operators) == sorted(
[
'ALTER TABLE "category" ALTER COLUMN "name" DROP NOT NULL',
'ALTER TABLE "category" ALTER COLUMN "slug" TYPE VARCHAR(100) USING "slug"::VARCHAR(100)',
'ALTER TABLE "config" ADD "user_id" INT NOT NULL',
'ALTER TABLE "config" ADD CONSTRAINT "fk_config_user_17daa970" FOREIGN KEY ("user_id") REFERENCES "user" ("id") ON DELETE CASCADE',
'ALTER TABLE "config" ALTER COLUMN "status" DROP DEFAULT',
'ALTER TABLE "email" ADD "address" VARCHAR(200) NOT NULL',
'ALTER TABLE "email" DROP COLUMN "user_id"',
'ALTER TABLE "product" RENAME COLUMN "image" TO "pic"',
'ALTER TABLE "email" RENAME COLUMN "id" TO "email_id"',
'ALTER TABLE "configs" RENAME TO "config"',
'ALTER TABLE "email" DROP CONSTRAINT "fk_email_user_5b58673d"',
'CREATE INDEX "idx_email_email_4a1a33" ON "email" ("email")',
'CREATE UNIQUE INDEX "uid_product_name_f14935" ON "product" ("name", "type")',
'ALTER TABLE "product" ALTER COLUMN "view_num" SET DEFAULT 0',
'ALTER TABLE "user" DROP COLUMN "avatar"',
'ALTER TABLE "user" ALTER COLUMN "password" TYPE VARCHAR(100) USING "password"::VARCHAR(100)',
'CREATE TABLE IF NOT EXISTS "newmodel" (\n "id" SERIAL NOT NULL PRIMARY KEY,\n "name" VARCHAR(50) NOT NULL\n);\nCOMMENT ON COLUMN "config"."user_id" IS \'User\';',
'CREATE UNIQUE INDEX "uid_user_usernam_9987ab" ON "user" ("username")',
'CREATE TABLE "email_user" ("email_id" INT NOT NULL REFERENCES "email" ("email_id") ON DELETE CASCADE,"user_id" INT NOT NULL REFERENCES "user" ("id") ON DELETE CASCADE)',
]
)
assert sorted(Migrate.downgrade_operators) == sorted(
[
'ALTER TABLE "category" ALTER COLUMN "name" SET NOT NULL',
'ALTER TABLE "category" ALTER COLUMN "slug" TYPE VARCHAR(200) USING "slug"::VARCHAR(200)',
'ALTER TABLE "user" ALTER COLUMN "password" TYPE VARCHAR(200) USING "password"::VARCHAR(200)',
'ALTER TABLE "config" DROP COLUMN "user_id"',
'ALTER TABLE "config" DROP CONSTRAINT "fk_config_user_17daa970"',
'ALTER TABLE "config" ALTER COLUMN "status" SET DEFAULT 1',
'ALTER TABLE "email" ADD "user_id" INT NOT NULL',
'ALTER TABLE "email" DROP COLUMN "address"',
'ALTER TABLE "config" RENAME TO "configs"',
'ALTER TABLE "product" RENAME COLUMN "pic" TO "image"',
'ALTER TABLE "email" RENAME COLUMN "email_id" TO "id"',
'ALTER TABLE "email" ADD CONSTRAINT "fk_email_user_5b58673d" FOREIGN KEY ("user_id") REFERENCES "user" ("id") ON DELETE CASCADE',
'DROP INDEX "idx_email_email_4a1a33"',
'ALTER TABLE "product" ALTER COLUMN "view_num" DROP DEFAULT',
'ALTER TABLE "user" ADD "avatar" VARCHAR(200) NOT NULL DEFAULT \'\'',
'DROP INDEX "idx_user_usernam_9987ab"',
'DROP INDEX "uid_product_name_f14935"',
'DROP TABLE IF EXISTS "email_user"',
'DROP TABLE IF EXISTS "newmodel"',
]
)
elif isinstance(Migrate.ddl, SqliteDDL):
assert Migrate.upgrade_operators == []
assert Migrate.downgrade_operators == [] |
BasicAssetTransferTester.go | package main
import (
"diablo-benchmark/blockchains/clientinterfaces"
blockchaintypes "diablo-benchmark/blockchains/types"
"diablo-benchmark/blockchains/workloadgenerators"
"diablo-benchmark/core/configs"
"diablo-benchmark/core/configs/parsers"
"encoding/json"
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"log"
"os"
"strconv"
)
func main() |
func createAssetTransaction(transactionID int, generator workloadgenerators.WorkloadGenerator) *blockchaintypes.FabricTX {
var cParamList []configs.ContractParam
cParamList = append(cParamList,
configs.ContractParam{
Type: "uint64",
Value: strconv.Itoa(transactionID),
},
configs.ContractParam{
Type: "string",
Value: "asset#" + strconv.Itoa(transactionID),
},
configs.ContractParam{
Type: "color",
Value: "c",
}, configs.ContractParam{
Type: "size",
Value: "100",
}, configs.ContractParam{
Type: "owner",
Value: "Bob Ross",
},configs.ContractParam{
Type: "price",
Value: "420",
})
txAsset,_ := generator.CreateInteractionTX(
nil,
"write",
"CreateAsset",
cParamList,
"",
)
var parsedTxAsset blockchaintypes.FabricTX
_ = json.Unmarshal(txAsset, &parsedTxAsset)
return &parsedTxAsset
}
func readAssetTransaction(transactionID int, assetToRead string, generator workloadgenerators.WorkloadGenerator) *blockchaintypes.FabricTX {
var CParamListQuery []configs.ContractParam
CParamListQuery = append(CParamListQuery, configs.ContractParam{
Type: "uint64",
Value: strconv.Itoa(transactionID),
}, configs.ContractParam{
Type: "string",
Value: assetToRead,
})
txQuery, err := generator.CreateInteractionTX(
nil,
"read",
"ReadAsset",
CParamListQuery,
"")
if err != nil{
panic(err)
}
var parsedTxQuery blockchaintypes.FabricTX
_ = json.Unmarshal(txQuery,&parsedTxQuery)
return &parsedTxQuery
} | {
config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
logger, err := config.Build()
if err != nil {
os.Exit(1)
}
zap.ReplaceGlobals(logger)
cc, err := parsers.ParseChainConfig("../../configurations/blockchain-configs/fabric/fabric-test.yaml")
if err != nil {
panic(err)
}
bc, err := parsers.ParseBenchConfig("../../configurations/workloads/fabric/testDiabloFabric.yaml")
if err != nil {
panic(err)
}
var generator workloadgenerators.WorkloadGenerator
intermediate := workloadgenerators.FabricWorkloadGenerator{}
generator = intermediate.NewGenerator(cc, bc)
client1 := clientinterfaces.FabricInterface{}
//client2 := clientinterfaces.FabricInterface{}
log.Println("Init client1 interface")
if cc.Extra == nil{
fmt.Println("EXTRA IS NIL")
return
}
client1.Init(cc)
client1.SetWindow(2)
//client2.Init(cc.Nodes, nil)
client1.Start()
err = generator.BlockchainSetup()
if err != nil {
panic(err)
}
err = generator.InitParams()
if err != nil {
panic(err)
}
log.Println("sendRawTransaction via client1 FIRST TIME EXPECTING BUG")
err = client1.SendRawTransaction(createAssetTransaction(0,generator))
////err = client2.SendRawTransaction(createAssetTransaction(0,generator))
//
workload,err := generator.GenerateWorkload()
if err != nil {
panic(err)
}
parsedWorkload1,err := client1.ParseWorkload(workload[0][0])
if err != nil {
panic(err)
}
for _,intervals := range parsedWorkload1 {
for _, tx := range intervals {
client1.SendRawTransaction(tx)
}
}
// //parsedWorkload2,err := client2.ParseWorkload(workload[0][1])
// for _,intervals := range parsedWorkload2 {
// for _, tx := range intervals{
// client2.SendRawTransaction(tx)
// }
//}
//var txs []*gateway.Transaction
//var listeners [] <- chan *fab.TxStatusEvent
//
//for i := 0; i < 100; i++ {
// tx,err := client1.Contract.CreateTransaction("CreateAsset")
//
// if err != nil {
// log.Println(err)
// }
// ls := tx.RegisterCommitEvent()
//
// txs = append(txs,tx)
// listeners = append(listeners,ls)
//}
//
//for i, tx := range txs {
// s := strconv.FormatInt(int64(i),10)
// go tx.Submit(s,s,s,s,s)
//}
//
//for _,ls := range listeners {
// s := <- ls
// log.Println(s.SourceURL)
// log.Println(s.TxValidationCode.String())
// log.Println("block",s.BlockNumber)
//}
//
//
//log.Println("submitted transaction")
log.Println("--> Evaluate Transaction: GetAllAssets, function returns every asset")
result, err := client1.Contract.EvaluateTransaction("GetAllAssetsID")
if err != nil {
log.Fatalf("Failed to evaluate transaction: %v\n", err)
}
log.Println("ALL TRANSACTIONS IDS IN THE LEDGER")
log.Println(string(result))
} |
x_25519_x_salsa20_poly1305_decrypt.rs | use crate::core::ribosome::CallContext;
use crate::core::ribosome::RibosomeT;
use holochain_keystore::keystore_actor::KeystoreSenderExt;
use std::sync::Arc;
use holochain_types::prelude::*;
use holochain_wasmer_host::prelude::WasmError;
pub fn | (
_ribosome: Arc<impl RibosomeT>,
call_context: Arc<CallContext>,
input: X25519XSalsa20Poly1305Decrypt,
) -> Result<Option<XSalsa20Poly1305Data>, WasmError> {
Ok(
tokio_safe_block_on::tokio_safe_block_forever_on(async move {
call_context
.host_access
.keystore()
.x_25519_x_salsa20_poly1305_decrypt(input)
.await
}).map_err(|keystore_error| WasmError::Host(keystore_error.to_string()))?,
)
}
| x_25519_x_salsa20_poly1305_decrypt |
one.pb.go | // Code generated by protoc-gen-gogo.
// source: combos/neither/one.proto
// DO NOT EDIT!
/*
Package one is a generated protocol buffer package.
It is generated from these files:
combos/neither/one.proto
It has these top-level messages:
Subby
AllTypesOneOf
TwoOneofs
CustomOneof
*/
package one
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/gogo/protobuf/gogoproto"
import github_com_gogo_protobuf_test_custom "github.com/gogo/protobuf/test/custom"
import github_com_gogo_protobuf_test_casttype "github.com/gogo/protobuf/test/casttype"
import github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
import compress_gzip "compress/gzip"
import bytes "bytes"
import io_ioutil "io/ioutil"
import strings "strings"
import reflect "reflect"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
type Subby struct {
Sub *string `protobuf:"bytes,1,opt,name=sub" json:"sub,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *Subby) Reset() { *m = Subby{} }
func (*Subby) ProtoMessage() {}
func (*Subby) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{0} }
type AllTypesOneOf struct {
// Types that are valid to be assigned to TestOneof:
// *AllTypesOneOf_Field1
// *AllTypesOneOf_Field2
// *AllTypesOneOf_Field3
// *AllTypesOneOf_Field4
// *AllTypesOneOf_Field5
// *AllTypesOneOf_Field6
// *AllTypesOneOf_Field7
// *AllTypesOneOf_Field8
// *AllTypesOneOf_Field9
// *AllTypesOneOf_Field10
// *AllTypesOneOf_Field11
// *AllTypesOneOf_Field12
// *AllTypesOneOf_Field13
// *AllTypesOneOf_Field14
// *AllTypesOneOf_Field15
// *AllTypesOneOf_SubMessage
TestOneof isAllTypesOneOf_TestOneof `protobuf_oneof:"test_oneof"`
XXX_unrecognized []byte `json:"-"`
}
func (m *AllTypesOneOf) Reset() { *m = AllTypesOneOf{} }
func (*AllTypesOneOf) ProtoMessage() {}
func (*AllTypesOneOf) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{1} }
type isAllTypesOneOf_TestOneof interface {
isAllTypesOneOf_TestOneof()
Equal(interface{}) bool
VerboseEqual(interface{}) error
Size() int
}
type AllTypesOneOf_Field1 struct {
Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,oneof"`
}
type AllTypesOneOf_Field2 struct {
Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,oneof"`
}
type AllTypesOneOf_Field3 struct {
Field3 int32 `protobuf:"varint,3,opt,name=Field3,oneof"`
}
type AllTypesOneOf_Field4 struct {
Field4 int64 `protobuf:"varint,4,opt,name=Field4,oneof"`
}
type AllTypesOneOf_Field5 struct {
Field5 uint32 `protobuf:"varint,5,opt,name=Field5,oneof"`
}
type AllTypesOneOf_Field6 struct {
Field6 uint64 `protobuf:"varint,6,opt,name=Field6,oneof"`
}
type AllTypesOneOf_Field7 struct {
Field7 int32 `protobuf:"zigzag32,7,opt,name=Field7,oneof"`
}
type AllTypesOneOf_Field8 struct {
Field8 int64 `protobuf:"zigzag64,8,opt,name=Field8,oneof"`
}
type AllTypesOneOf_Field9 struct {
Field9 uint32 `protobuf:"fixed32,9,opt,name=Field9,oneof"`
}
type AllTypesOneOf_Field10 struct {
Field10 int32 `protobuf:"fixed32,10,opt,name=Field10,oneof"`
}
type AllTypesOneOf_Field11 struct {
Field11 uint64 `protobuf:"fixed64,11,opt,name=Field11,oneof"`
}
type AllTypesOneOf_Field12 struct {
Field12 int64 `protobuf:"fixed64,12,opt,name=Field12,oneof"`
}
type AllTypesOneOf_Field13 struct {
Field13 bool `protobuf:"varint,13,opt,name=Field13,oneof"`
}
type AllTypesOneOf_Field14 struct {
Field14 string `protobuf:"bytes,14,opt,name=Field14,oneof"`
}
type AllTypesOneOf_Field15 struct {
Field15 []byte `protobuf:"bytes,15,opt,name=Field15,oneof"`
}
type AllTypesOneOf_SubMessage struct {
SubMessage *Subby `protobuf:"bytes,16,opt,name=sub_message,json=subMessage,oneof"`
}
func (*AllTypesOneOf_Field1) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field2) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field3) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field4) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field5) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field6) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field7) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field8) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field9) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field10) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field11) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field12) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field13) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field14) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_Field15) isAllTypesOneOf_TestOneof() {}
func (*AllTypesOneOf_SubMessage) isAllTypesOneOf_TestOneof() {}
func (m *AllTypesOneOf) GetTestOneof() isAllTypesOneOf_TestOneof {
if m != nil {
return m.TestOneof
}
return nil
}
func (m *AllTypesOneOf) GetField1() float64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field1); ok {
return x.Field1
}
return 0
}
func (m *AllTypesOneOf) GetField2() float32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field2); ok {
return x.Field2
}
return 0
}
func (m *AllTypesOneOf) GetField3() int32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field3); ok {
return x.Field3
}
return 0
}
func (m *AllTypesOneOf) GetField4() int64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field4); ok {
return x.Field4
}
return 0
}
func (m *AllTypesOneOf) GetField5() uint32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field5); ok {
return x.Field5
}
return 0
}
func (m *AllTypesOneOf) GetField6() uint64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field6); ok {
return x.Field6
}
return 0
}
func (m *AllTypesOneOf) GetField7() int32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field7); ok {
return x.Field7
}
return 0
}
func (m *AllTypesOneOf) GetField8() int64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field8); ok {
return x.Field8
}
return 0
}
func (m *AllTypesOneOf) GetField9() uint32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field9); ok {
return x.Field9
}
return 0
}
func (m *AllTypesOneOf) GetField10() int32 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field10); ok {
return x.Field10
}
return 0
}
func (m *AllTypesOneOf) GetField11() uint64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field11); ok {
return x.Field11
}
return 0
}
func (m *AllTypesOneOf) GetField12() int64 {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field12); ok {
return x.Field12
}
return 0
}
func (m *AllTypesOneOf) GetField13() bool {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field13); ok {
return x.Field13
}
return false
}
func (m *AllTypesOneOf) GetField14() string {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field14); ok {
return x.Field14
}
return ""
}
func (m *AllTypesOneOf) GetField15() []byte {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_Field15); ok {
return x.Field15
}
return nil
}
func (m *AllTypesOneOf) GetSubMessage() *Subby {
if x, ok := m.GetTestOneof().(*AllTypesOneOf_SubMessage); ok {
return x.SubMessage
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*AllTypesOneOf) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _AllTypesOneOf_OneofMarshaler, _AllTypesOneOf_OneofUnmarshaler, _AllTypesOneOf_OneofSizer, []interface{}{
(*AllTypesOneOf_Field1)(nil),
(*AllTypesOneOf_Field2)(nil),
(*AllTypesOneOf_Field3)(nil),
(*AllTypesOneOf_Field4)(nil),
(*AllTypesOneOf_Field5)(nil),
(*AllTypesOneOf_Field6)(nil),
(*AllTypesOneOf_Field7)(nil),
(*AllTypesOneOf_Field8)(nil),
(*AllTypesOneOf_Field9)(nil),
(*AllTypesOneOf_Field10)(nil),
(*AllTypesOneOf_Field11)(nil),
(*AllTypesOneOf_Field12)(nil),
(*AllTypesOneOf_Field13)(nil),
(*AllTypesOneOf_Field14)(nil),
(*AllTypesOneOf_Field15)(nil),
(*AllTypesOneOf_SubMessage)(nil),
}
}
func _AllTypesOneOf_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*AllTypesOneOf)
// test_oneof
switch x := m.TestOneof.(type) {
case *AllTypesOneOf_Field1:
_ = b.EncodeVarint(1<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(math.Float64bits(x.Field1))
case *AllTypesOneOf_Field2:
_ = b.EncodeVarint(2<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2)))
case *AllTypesOneOf_Field3:
_ = b.EncodeVarint(3<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field3))
case *AllTypesOneOf_Field4:
_ = b.EncodeVarint(4<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field4))
case *AllTypesOneOf_Field5:
_ = b.EncodeVarint(5<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field5))
case *AllTypesOneOf_Field6:
_ = b.EncodeVarint(6<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field6))
case *AllTypesOneOf_Field7:
_ = b.EncodeVarint(7<<3 | proto.WireVarint)
_ = b.EncodeZigzag32(uint64(x.Field7))
case *AllTypesOneOf_Field8:
_ = b.EncodeVarint(8<<3 | proto.WireVarint)
_ = b.EncodeZigzag64(uint64(x.Field8))
case *AllTypesOneOf_Field9:
_ = b.EncodeVarint(9<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(x.Field9))
case *AllTypesOneOf_Field10:
_ = b.EncodeVarint(10<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(x.Field10))
case *AllTypesOneOf_Field11:
_ = b.EncodeVarint(11<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(uint64(x.Field11))
case *AllTypesOneOf_Field12:
_ = b.EncodeVarint(12<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(uint64(x.Field12))
case *AllTypesOneOf_Field13:
t := uint64(0)
if x.Field13 {
t = 1
}
_ = b.EncodeVarint(13<<3 | proto.WireVarint)
_ = b.EncodeVarint(t)
case *AllTypesOneOf_Field14:
_ = b.EncodeVarint(14<<3 | proto.WireBytes)
_ = b.EncodeStringBytes(x.Field14)
case *AllTypesOneOf_Field15:
_ = b.EncodeVarint(15<<3 | proto.WireBytes)
_ = b.EncodeRawBytes(x.Field15)
case *AllTypesOneOf_SubMessage:
_ = b.EncodeVarint(16<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.SubMessage); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("AllTypesOneOf.TestOneof has unexpected type %T", x)
}
return nil
}
func _AllTypesOneOf_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*AllTypesOneOf)
switch tag {
case 1: // test_oneof.Field1
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &AllTypesOneOf_Field1{math.Float64frombits(x)}
return true, err
case 2: // test_oneof.Field2
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &AllTypesOneOf_Field2{math.Float32frombits(uint32(x))}
return true, err
case 3: // test_oneof.Field3
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field3{int32(x)}
return true, err
case 4: // test_oneof.Field4
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field4{int64(x)}
return true, err
case 5: // test_oneof.Field5
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field5{uint32(x)}
return true, err
case 6: // test_oneof.Field6
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field6{x}
return true, err
case 7: // test_oneof.Field7
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeZigzag32()
m.TestOneof = &AllTypesOneOf_Field7{int32(x)}
return true, err
case 8: // test_oneof.Field8
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeZigzag64()
m.TestOneof = &AllTypesOneOf_Field8{int64(x)}
return true, err
case 9: // test_oneof.Field9
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &AllTypesOneOf_Field9{uint32(x)}
return true, err
case 10: // test_oneof.Field10
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &AllTypesOneOf_Field10{int32(x)}
return true, err
case 11: // test_oneof.Field11
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &AllTypesOneOf_Field11{x}
return true, err
case 12: // test_oneof.Field12
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &AllTypesOneOf_Field12{int64(x)}
return true, err
case 13: // test_oneof.Field13
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &AllTypesOneOf_Field13{x != 0}
return true, err
case 14: // test_oneof.Field14
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.TestOneof = &AllTypesOneOf_Field14{x}
return true, err
case 15: // test_oneof.Field15
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
m.TestOneof = &AllTypesOneOf_Field15{x}
return true, err
case 16: // test_oneof.sub_message
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(Subby)
err := b.DecodeMessage(msg)
m.TestOneof = &AllTypesOneOf_SubMessage{msg}
return true, err
default:
return false, nil
}
}
func _AllTypesOneOf_OneofSizer(msg proto.Message) (n int) {
m := msg.(*AllTypesOneOf)
// test_oneof
switch x := m.TestOneof.(type) {
case *AllTypesOneOf_Field1:
n += proto.SizeVarint(1<<3 | proto.WireFixed64)
n += 8
case *AllTypesOneOf_Field2:
n += proto.SizeVarint(2<<3 | proto.WireFixed32)
n += 4
case *AllTypesOneOf_Field3:
n += proto.SizeVarint(3<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field3))
case *AllTypesOneOf_Field4:
n += proto.SizeVarint(4<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field4))
case *AllTypesOneOf_Field5:
n += proto.SizeVarint(5<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field5))
case *AllTypesOneOf_Field6:
n += proto.SizeVarint(6<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field6))
case *AllTypesOneOf_Field7:
n += proto.SizeVarint(7<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64((uint32(x.Field7) << 1) ^ uint32((int32(x.Field7) >> 31))))
case *AllTypesOneOf_Field8:
n += proto.SizeVarint(8<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(uint64(x.Field8<<1) ^ uint64((int64(x.Field8) >> 63))))
case *AllTypesOneOf_Field9:
n += proto.SizeVarint(9<<3 | proto.WireFixed32)
n += 4
case *AllTypesOneOf_Field10:
n += proto.SizeVarint(10<<3 | proto.WireFixed32)
n += 4
case *AllTypesOneOf_Field11:
n += proto.SizeVarint(11<<3 | proto.WireFixed64)
n += 8
case *AllTypesOneOf_Field12:
n += proto.SizeVarint(12<<3 | proto.WireFixed64)
n += 8
case *AllTypesOneOf_Field13:
n += proto.SizeVarint(13<<3 | proto.WireVarint)
n += 1
case *AllTypesOneOf_Field14:
n += proto.SizeVarint(14<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field14)))
n += len(x.Field14)
case *AllTypesOneOf_Field15:
n += proto.SizeVarint(15<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field15)))
n += len(x.Field15)
case *AllTypesOneOf_SubMessage:
s := proto.Size(x.SubMessage)
n += proto.SizeVarint(16<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
type TwoOneofs struct {
// Types that are valid to be assigned to One:
// *TwoOneofs_Field1
// *TwoOneofs_Field2
// *TwoOneofs_Field3
One isTwoOneofs_One `protobuf_oneof:"one"`
// Types that are valid to be assigned to Two:
// *TwoOneofs_Field34
// *TwoOneofs_Field35
// *TwoOneofs_SubMessage2
Two isTwoOneofs_Two `protobuf_oneof:"two"`
XXX_unrecognized []byte `json:"-"`
}
func (m *TwoOneofs) Reset() { *m = TwoOneofs{} }
func (*TwoOneofs) ProtoMessage() {}
func (*TwoOneofs) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{2} }
type isTwoOneofs_One interface {
isTwoOneofs_One()
Equal(interface{}) bool
VerboseEqual(interface{}) error
Size() int
}
type isTwoOneofs_Two interface {
isTwoOneofs_Two()
Equal(interface{}) bool
VerboseEqual(interface{}) error
Size() int
}
type TwoOneofs_Field1 struct {
Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,oneof"`
}
type TwoOneofs_Field2 struct {
Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,oneof"`
}
type TwoOneofs_Field3 struct {
Field3 int32 `protobuf:"varint,3,opt,name=Field3,oneof"`
}
type TwoOneofs_Field34 struct {
Field34 string `protobuf:"bytes,34,opt,name=Field34,oneof"`
}
type TwoOneofs_Field35 struct {
Field35 []byte `protobuf:"bytes,35,opt,name=Field35,oneof"`
}
type TwoOneofs_SubMessage2 struct {
SubMessage2 *Subby `protobuf:"bytes,36,opt,name=sub_message2,json=subMessage2,oneof"`
}
func (*TwoOneofs_Field1) isTwoOneofs_One() {}
func (*TwoOneofs_Field2) isTwoOneofs_One() {}
func (*TwoOneofs_Field3) isTwoOneofs_One() {}
func (*TwoOneofs_Field34) isTwoOneofs_Two() {}
func (*TwoOneofs_Field35) isTwoOneofs_Two() {}
func (*TwoOneofs_SubMessage2) isTwoOneofs_Two() {}
func (m *TwoOneofs) GetOne() isTwoOneofs_One {
if m != nil {
return m.One
}
return nil
}
func (m *TwoOneofs) GetTwo() isTwoOneofs_Two {
if m != nil {
return m.Two
}
return nil
}
func (m *TwoOneofs) GetField1() float64 {
if x, ok := m.GetOne().(*TwoOneofs_Field1); ok {
return x.Field1
}
return 0
}
func (m *TwoOneofs) GetField2() float32 {
if x, ok := m.GetOne().(*TwoOneofs_Field2); ok {
return x.Field2
}
return 0
}
func (m *TwoOneofs) GetField3() int32 {
if x, ok := m.GetOne().(*TwoOneofs_Field3); ok {
return x.Field3
}
return 0
}
func (m *TwoOneofs) GetField34() string {
if x, ok := m.GetTwo().(*TwoOneofs_Field34); ok {
return x.Field34
}
return ""
}
func (m *TwoOneofs) GetField35() []byte {
if x, ok := m.GetTwo().(*TwoOneofs_Field35); ok {
return x.Field35
}
return nil
}
func (m *TwoOneofs) GetSubMessage2() *Subby {
if x, ok := m.GetTwo().(*TwoOneofs_SubMessage2); ok {
return x.SubMessage2
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{
(*TwoOneofs_Field1)(nil),
(*TwoOneofs_Field2)(nil),
(*TwoOneofs_Field3)(nil),
(*TwoOneofs_Field34)(nil),
(*TwoOneofs_Field35)(nil),
(*TwoOneofs_SubMessage2)(nil),
}
}
func _TwoOneofs_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*TwoOneofs)
// one
switch x := m.One.(type) {
case *TwoOneofs_Field1:
_ = b.EncodeVarint(1<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(math.Float64bits(x.Field1))
case *TwoOneofs_Field2:
_ = b.EncodeVarint(2<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2)))
case *TwoOneofs_Field3:
_ = b.EncodeVarint(3<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field3))
case nil:
default:
return fmt.Errorf("TwoOneofs.One has unexpected type %T", x)
}
// two
switch x := m.Two.(type) {
case *TwoOneofs_Field34:
_ = b.EncodeVarint(34<<3 | proto.WireBytes)
_ = b.EncodeStringBytes(x.Field34)
case *TwoOneofs_Field35:
_ = b.EncodeVarint(35<<3 | proto.WireBytes)
_ = b.EncodeRawBytes(x.Field35)
case *TwoOneofs_SubMessage2:
_ = b.EncodeVarint(36<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.SubMessage2); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("TwoOneofs.Two has unexpected type %T", x)
}
return nil
}
func _TwoOneofs_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*TwoOneofs)
switch tag {
case 1: // one.Field1
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.One = &TwoOneofs_Field1{math.Float64frombits(x)}
return true, err
case 2: // one.Field2
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.One = &TwoOneofs_Field2{math.Float32frombits(uint32(x))}
return true, err
case 3: // one.Field3
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.One = &TwoOneofs_Field3{int32(x)}
return true, err
case 34: // two.Field34
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Two = &TwoOneofs_Field34{x}
return true, err
case 35: // two.Field35
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
m.Two = &TwoOneofs_Field35{x}
return true, err
case 36: // two.sub_message2
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(Subby)
err := b.DecodeMessage(msg)
m.Two = &TwoOneofs_SubMessage2{msg}
return true, err
default:
return false, nil
}
}
func _TwoOneofs_OneofSizer(msg proto.Message) (n int) {
m := msg.(*TwoOneofs)
// one
switch x := m.One.(type) {
case *TwoOneofs_Field1:
n += proto.SizeVarint(1<<3 | proto.WireFixed64)
n += 8
case *TwoOneofs_Field2:
n += proto.SizeVarint(2<<3 | proto.WireFixed32)
n += 4
case *TwoOneofs_Field3:
n += proto.SizeVarint(3<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field3))
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
// two
switch x := m.Two.(type) {
case *TwoOneofs_Field34:
n += proto.SizeVarint(34<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field34)))
n += len(x.Field34)
case *TwoOneofs_Field35:
n += proto.SizeVarint(35<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field35)))
n += len(x.Field35)
case *TwoOneofs_SubMessage2:
s := proto.Size(x.SubMessage2)
n += proto.SizeVarint(36<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
type CustomOneof struct {
// Types that are valid to be assigned to Custom:
// *CustomOneof_Stringy
// *CustomOneof_CustomType
// *CustomOneof_CastType
// *CustomOneof_MyCustomName
Custom isCustomOneof_Custom `protobuf_oneof:"custom"`
XXX_unrecognized []byte `json:"-"`
}
func (m *CustomOneof) Reset() { *m = CustomOneof{} }
func (*CustomOneof) ProtoMessage() {}
func (*CustomOneof) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{3} }
type isCustomOneof_Custom interface {
isCustomOneof_Custom()
Equal(interface{}) bool
VerboseEqual(interface{}) error
Size() int
}
type CustomOneof_Stringy struct {
Stringy string `protobuf:"bytes,34,opt,name=Stringy,oneof"`
}
type CustomOneof_CustomType struct {
CustomType github_com_gogo_protobuf_test_custom.Uint128 `protobuf:"bytes,35,opt,name=CustomType,oneof,customtype=github.com/gogo/protobuf/test/custom.Uint128"`
}
type CustomOneof_CastType struct {
CastType github_com_gogo_protobuf_test_casttype.MyUint64Type `protobuf:"varint,36,opt,name=CastType,oneof,casttype=github.com/gogo/protobuf/test/casttype.MyUint64Type"`
}
type CustomOneof_MyCustomName struct {
MyCustomName int64 `protobuf:"varint,37,opt,name=CustomName,oneof"`
}
func (*CustomOneof_Stringy) isCustomOneof_Custom() {}
func (*CustomOneof_CustomType) isCustomOneof_Custom() {}
func (*CustomOneof_CastType) isCustomOneof_Custom() {}
func (*CustomOneof_MyCustomName) isCustomOneof_Custom() {}
func (m *CustomOneof) GetCustom() isCustomOneof_Custom {
if m != nil {
return m.Custom
}
return nil
}
func (m *CustomOneof) GetStringy() string {
if x, ok := m.GetCustom().(*CustomOneof_Stringy); ok {
return x.Stringy
}
return ""
}
func (m *CustomOneof) GetCastType() github_com_gogo_protobuf_test_casttype.MyUint64Type {
if x, ok := m.GetCustom().(*CustomOneof_CastType); ok {
return x.CastType
}
return 0
}
func (m *CustomOneof) GetMyCustomName() int64 {
if x, ok := m.GetCustom().(*CustomOneof_MyCustomName); ok {
return x.MyCustomName
}
return 0
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*CustomOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _CustomOneof_OneofMarshaler, _CustomOneof_OneofUnmarshaler, _CustomOneof_OneofSizer, []interface{}{
(*CustomOneof_Stringy)(nil),
(*CustomOneof_CustomType)(nil),
(*CustomOneof_CastType)(nil),
(*CustomOneof_MyCustomName)(nil),
}
}
func _CustomOneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*CustomOneof)
// custom
switch x := m.Custom.(type) {
case *CustomOneof_Stringy:
_ = b.EncodeVarint(34<<3 | proto.WireBytes)
_ = b.EncodeStringBytes(x.Stringy)
case *CustomOneof_CustomType:
_ = b.EncodeVarint(35<<3 | proto.WireBytes)
dAtA, err := x.CustomType.Marshal()
if err != nil {
return err
}
_ = b.EncodeRawBytes(dAtA)
case *CustomOneof_CastType:
_ = b.EncodeVarint(36<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.CastType))
case *CustomOneof_MyCustomName:
_ = b.EncodeVarint(37<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.MyCustomName))
case nil:
default:
return fmt.Errorf("CustomOneof.Custom has unexpected type %T", x)
}
return nil
}
func _CustomOneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*CustomOneof)
switch tag {
case 34: // custom.Stringy
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Custom = &CustomOneof_Stringy{x}
return true, err
case 35: // custom.CustomType
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
if err != nil {
return true, err
}
var cc github_com_gogo_protobuf_test_custom.Uint128
c := &cc
err = c.Unmarshal(x)
m.Custom = &CustomOneof_CustomType{*c}
return true, err
case 36: // custom.CastType
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Custom = &CustomOneof_CastType{github_com_gogo_protobuf_test_casttype.MyUint64Type(x)}
return true, err
case 37: // custom.CustomName
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Custom = &CustomOneof_MyCustomName{int64(x)}
return true, err
default:
return false, nil
}
}
func _CustomOneof_OneofSizer(msg proto.Message) (n int) {
m := msg.(*CustomOneof)
// custom
switch x := m.Custom.(type) {
case *CustomOneof_Stringy:
n += proto.SizeVarint(34<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Stringy)))
n += len(x.Stringy)
case *CustomOneof_CustomType:
n += proto.SizeVarint(35<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(x.CustomType.Size()))
n += x.CustomType.Size()
case *CustomOneof_CastType:
n += proto.SizeVarint(36<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.CastType))
case *CustomOneof_MyCustomName:
n += proto.SizeVarint(37<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.MyCustomName))
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
func init() {
proto.RegisterType((*Subby)(nil), "one.Subby")
proto.RegisterType((*AllTypesOneOf)(nil), "one.AllTypesOneOf")
proto.RegisterType((*TwoOneofs)(nil), "one.TwoOneofs")
proto.RegisterType((*CustomOneof)(nil), "one.CustomOneof")
}
func (this *Subby) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func (this *AllTypesOneOf) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func (this *TwoOneofs) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func (this *CustomOneof) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func OneDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{}
var gzipped = []byte{
// 3907 bytes of a gzipped FileDescriptorSet
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x5a, 0x6b, 0x6c, 0x23, 0xd7,
0x75, 0xd6, 0xf0, 0x21, 0x91, 0x87, 0x14, 0x35, 0xba, 0x92, 0xd7, 0xb3, 0x72, 0xcc, 0xd5, 0xd2,
0x76, 0x2c, 0xdb, 0xb1, 0x64, 0xeb, 0xb1, 0x0f, 0x6e, 0x13, 0x83, 0x92, 0x68, 0xad, 0x0c, 0xbd,
0x3a, 0x92, 0x12, 0x3b, 0xf9, 0x31, 0x18, 0x0e, 0x2f, 0xa9, 0xd9, 0x1d, 0xce, 0xb0, 0x33, 0xc3,
0x5d, 0xcb, 0xbf, 0x36, 0x70, 0x1f, 0x08, 0x82, 0xbe, 0xd2, 0x02, 0x4d, 0x1c, 0xc7, 0x75, 0x03,
0xb4, 0x4e, 0xd3, 0x57, 0xd2, 0x47, 0x5a, 0xf4, 0x57, 0xff, 0xa4, 0xf5, 0xaf, 0xc2, 0xf9, 0x57,
0x14, 0x85, 0x91, 0x55, 0x0d, 0x34, 0x6d, 0xdd, 0xd6, 0x6d, 0x0d, 0xd4, 0xa8, 0xff, 0x14, 0xf7,
0x35, 0x33, 0x7c, 0x68, 0x87, 0x0a, 0x9a, 0x38, 0xbf, 0xa4, 0x7b, 0xce, 0xf9, 0xbe, 0x39, 0xf7,
0xdc, 0x73, 0xef, 0x39, 0x73, 0x39, 0xf0, 0xf9, 0x65, 0x98, 0x6d, 0x3a, 0x4e, 0xd3, 0xc2, 0x0b,
0x6d, 0xd7, 0xf1, 0x9d, 0x5a, 0xa7, 0xb1, 0x50, 0xc7, 0x9e, 0xe1, 0x9a, 0x6d, 0xdf, 0x71, 0xe7,
0xa9, 0x0c, 0x4d, 0x30, 0x8b, 0x79, 0x61, 0x51, 0xda, 0x86, 0xc9, 0x67, 0x4d, 0x0b, 0xaf, 0x07,
0x86, 0xfb, 0xd8, 0x47, 0x57, 0x20, 0xd5, 0x30, 0x2d, 0xac, 0x48, 0xb3, 0xc9, 0xb9, 0xdc, 0xe2,
0xc3, 0xf3, 0x3d, 0xa0, 0xf9, 0x6e, 0xc4, 0x1e, 0x11, 0xab, 0x14, 0x51, 0x7a, 0x27, 0x05, 0x53,
0x03, 0xb4, 0x08, 0x41, 0xca, 0xd6, 0x5b, 0x84, 0x51, 0x9a, 0xcb, 0xaa, 0xf4, 0x7f, 0xa4, 0xc0,
0x58, 0x5b, 0x37, 0x6e, 0xea, 0x4d, 0xac, 0x24, 0xa8, 0x58, 0x0c, 0x51, 0x11, 0xa0, 0x8e, 0xdb,
0xd8, 0xae, 0x63, 0xdb, 0x38, 0x56, 0x92, 0xb3, 0xc9, 0xb9, 0xac, 0x1a, 0x91, 0xa0, 0x27, 0x60,
0xb2, 0xdd, 0xa9, 0x59, 0xa6, 0xa1, 0x45, 0xcc, 0x60, 0x36, 0x39, 0x97, 0x56, 0x65, 0xa6, 0x58,
0x0f, 0x8d, 0x1f, 0x85, 0x89, 0xdb, 0x58, 0xbf, 0x19, 0x35, 0xcd, 0x51, 0xd3, 0x02, 0x11, 0x47,
0x0c, 0xd7, 0x20, 0xdf, 0xc2, 0x9e, 0xa7, 0x37, 0xb1, 0xe6, 0x1f, 0xb7, 0xb1, 0x92, 0xa2, 0xb3,
0x9f, 0xed, 0x9b, 0x7d, 0xef, 0xcc, 0x73, 0x1c, 0x75, 0x70, 0xdc, 0xc6, 0xa8, 0x02, 0x59, 0x6c,
0x77, 0x5a, 0x8c, 0x21, 0x7d, 0x4a, 0xfc, 0xaa, 0x76, 0xa7, 0xd5, 0xcb, 0x92, 0x21, 0x30, 0x4e,
0x31, 0xe6, 0x61, 0xf7, 0x96, 0x69, 0x60, 0x65, 0x94, 0x12, 0x3c, 0xda, 0x47, 0xb0, 0xcf, 0xf4,
0xbd, 0x1c, 0x02, 0x87, 0xd6, 0x20, 0x8b, 0x5f, 0xf4, 0xb1, 0xed, 0x99, 0x8e, 0xad, 0x8c, 0x51,
0x92, 0x47, 0x06, 0xac, 0x22, 0xb6, 0xea, 0xbd, 0x14, 0x21, 0x0e, 0x5d, 0x82, 0x31, 0xa7, 0xed,
0x9b, 0x8e, 0xed, 0x29, 0x99, 0x59, 0x69, 0x2e, 0xb7, 0xf8, 0xb1, 0x81, 0x89, 0xb0, 0xcb, 0x6c,
0x54, 0x61, 0x8c, 0x36, 0x41, 0xf6, 0x9c, 0x8e, 0x6b, 0x60, 0xcd, 0x70, 0xea, 0x58, 0x33, 0xed,
0x86, 0xa3, 0x64, 0x29, 0xc1, 0x85, 0xfe, 0x89, 0x50, 0xc3, 0x35, 0xa7, 0x8e, 0x37, 0xed, 0x86,
0xa3, 0x16, 0xbc, 0xae, 0x31, 0x3a, 0x07, 0xa3, 0xde, 0xb1, 0xed, 0xeb, 0x2f, 0x2a, 0x79, 0x9a,
0x21, 0x7c, 0x54, 0xfa, 0x9f, 0x34, 0x4c, 0x0c, 0x93, 0x62, 0xd7, 0x20, 0xdd, 0x20, 0xb3, 0x54,
0x12, 0x67, 0x89, 0x01, 0xc3, 0x74, 0x07, 0x71, 0xf4, 0x87, 0x0c, 0x62, 0x05, 0x72, 0x36, 0xf6,
0x7c, 0x5c, 0x67, 0x19, 0x91, 0x1c, 0x32, 0xa7, 0x80, 0x81, 0xfa, 0x53, 0x2a, 0xf5, 0x43, 0xa5,
0xd4, 0xf3, 0x30, 0x11, 0xb8, 0xa4, 0xb9, 0xba, 0xdd, 0x14, 0xb9, 0xb9, 0x10, 0xe7, 0xc9, 0x7c,
0x55, 0xe0, 0x54, 0x02, 0x53, 0x0b, 0xb8, 0x6b, 0x8c, 0xd6, 0x01, 0x1c, 0x1b, 0x3b, 0x0d, 0xad,
0x8e, 0x0d, 0x4b, 0xc9, 0x9c, 0x12, 0xa5, 0x5d, 0x62, 0xd2, 0x17, 0x25, 0x87, 0x49, 0x0d, 0x0b,
0x5d, 0x0d, 0x53, 0x6d, 0xec, 0x94, 0x4c, 0xd9, 0x66, 0x9b, 0xac, 0x2f, 0xdb, 0x0e, 0xa1, 0xe0,
0x62, 0x92, 0xf7, 0xb8, 0xce, 0x67, 0x96, 0xa5, 0x4e, 0xcc, 0xc7, 0xce, 0x4c, 0xe5, 0x30, 0x36,
0xb1, 0x71, 0x37, 0x3a, 0x44, 0x0f, 0x41, 0x20, 0xd0, 0x68, 0x5a, 0x01, 0x3d, 0x85, 0xf2, 0x42,
0xb8, 0xa3, 0xb7, 0xf0, 0xcc, 0x15, 0x28, 0x74, 0x87, 0x07, 0x4d, 0x43, 0xda, 0xf3, 0x75, 0xd7,
0xa7, 0x59, 0x98, 0x56, 0xd9, 0x00, 0xc9, 0x90, 0xc4, 0x76, 0x9d, 0x9e, 0x72, 0x69, 0x95, 0xfc,
0x3b, 0x73, 0x19, 0xc6, 0xbb, 0x1e, 0x3f, 0x2c, 0xb0, 0xf4, 0xe5, 0x51, 0x98, 0x1e, 0x94, 0x73,
0x03, 0xd3, 0xff, 0x1c, 0x8c, 0xda, 0x9d, 0x56, 0x0d, 0xbb, 0x4a, 0x92, 0x32, 0xf0, 0x11, 0xaa,
0x40, 0xda, 0xd2, 0x6b, 0xd8, 0x52, 0x52, 0xb3, 0xd2, 0x5c, 0x61, 0xf1, 0x89, 0xa1, 0xb2, 0x7a,
0x7e, 0x8b, 0x40, 0x54, 0x86, 0x44, 0x9f, 0x82, 0x14, 0x3f, 0xe2, 0x08, 0xc3, 0xe3, 0xc3, 0x31,
0x90, 0x5c, 0x54, 0x29, 0x0e, 0x3d, 0x00, 0x59, 0xf2, 0x97, 0xc5, 0x76, 0x94, 0xfa, 0x9c, 0x21,
0x02, 0x12, 0x57, 0x34, 0x03, 0x19, 0x9a, 0x66, 0x75, 0x2c, 0x4a, 0x43, 0x30, 0x26, 0x0b, 0x53,
0xc7, 0x0d, 0xbd, 0x63, 0xf9, 0xda, 0x2d, 0xdd, 0xea, 0x60, 0x9a, 0x30, 0x59, 0x35, 0xcf, 0x85,
0x9f, 0x26, 0x32, 0x74, 0x01, 0x72, 0x2c, 0x2b, 0x4d, 0xbb, 0x8e, 0x5f, 0xa4, 0xa7, 0x4f, 0x5a,
0x65, 0x89, 0xba, 0x49, 0x24, 0xe4, 0xf1, 0x37, 0x3c, 0xc7, 0x16, 0x4b, 0x4b, 0x1f, 0x41, 0x04,
0xf4, 0xf1, 0x97, 0x7b, 0x0f, 0xbe, 0x07, 0x07, 0x4f, 0xaf, 0x37, 0x17, 0x4b, 0xdf, 0x49, 0x40,
0x8a, 0xee, 0xb7, 0x09, 0xc8, 0x1d, 0xbc, 0xb0, 0x57, 0xd5, 0xd6, 0x77, 0x0f, 0x57, 0xb7, 0xaa,
0xb2, 0x84, 0x0a, 0x00, 0x54, 0xf0, 0xec, 0xd6, 0x6e, 0xe5, 0x40, 0x4e, 0x04, 0xe3, 0xcd, 0x9d,
0x83, 0x4b, 0xcb, 0x72, 0x32, 0x00, 0x1c, 0x32, 0x41, 0x2a, 0x6a, 0xb0, 0xb4, 0x28, 0xa7, 0x91,
0x0c, 0x79, 0x46, 0xb0, 0xf9, 0x7c, 0x75, 0xfd, 0xd2, 0xb2, 0x3c, 0xda, 0x2d, 0x59, 0x5a, 0x94,
0xc7, 0xd0, 0x38, 0x64, 0xa9, 0x64, 0x75, 0x77, 0x77, 0x4b, 0xce, 0x04, 0x9c, 0xfb, 0x07, 0xea,
0xe6, 0xce, 0x86, 0x9c, 0x0d, 0x38, 0x37, 0xd4, 0xdd, 0xc3, 0x3d, 0x19, 0x02, 0x86, 0xed, 0xea,
0xfe, 0x7e, 0x65, 0xa3, 0x2a, 0xe7, 0x02, 0x8b, 0xd5, 0x17, 0x0e, 0xaa, 0xfb, 0x72, 0xbe, 0xcb,
0xad, 0xa5, 0x45, 0x79, 0x3c, 0x78, 0x44, 0x75, 0xe7, 0x70, 0x5b, 0x2e, 0xa0, 0x49, 0x18, 0x67,
0x8f, 0x10, 0x4e, 0x4c, 0xf4, 0x88, 0x2e, 0x2d, 0xcb, 0x72, 0xe8, 0x08, 0x63, 0x99, 0xec, 0x12,
0x5c, 0x5a, 0x96, 0x51, 0x69, 0x0d, 0xd2, 0x34, 0xbb, 0x10, 0x82, 0xc2, 0x56, 0x65, 0xb5, 0xba,
0xa5, 0xed, 0xee, 0x1d, 0x6c, 0xee, 0xee, 0x54, 0xb6, 0x64, 0x29, 0x94, 0xa9, 0xd5, 0x9f, 0x3e,
0xdc, 0x54, 0xab, 0xeb, 0x72, 0x22, 0x2a, 0xdb, 0xab, 0x56, 0x0e, 0xaa, 0xeb, 0x72, 0xb2, 0x64,
0xc0, 0xf4, 0xa0, 0x73, 0x66, 0xe0, 0xce, 0x88, 0x2c, 0x71, 0xe2, 0x94, 0x25, 0xa6, 0x5c, 0x7d,
0x4b, 0xfc, 0x75, 0x09, 0xa6, 0x06, 0x9c, 0xb5, 0x03, 0x1f, 0xf2, 0x0c, 0xa4, 0x59, 0x8a, 0xb2,
0xea, 0xf3, 0xd8, 0xc0, 0x43, 0x9b, 0x26, 0x6c, 0x5f, 0x05, 0xa2, 0xb8, 0x68, 0x05, 0x4e, 0x9e,
0x52, 0x81, 0x09, 0x45, 0x9f, 0x93, 0x2f, 0x4b, 0xa0, 0x9c, 0xc6, 0x1d, 0x73, 0x50, 0x24, 0xba,
0x0e, 0x8a, 0x6b, 0xbd, 0x0e, 0x5c, 0x3c, 0x7d, 0x0e, 0x7d, 0x5e, 0xbc, 0x21, 0xc1, 0xb9, 0xc1,
0x8d, 0xca, 0x40, 0x1f, 0x3e, 0x05, 0xa3, 0x2d, 0xec, 0x1f, 0x39, 0xa2, 0x58, 0x7f, 0x7c, 0x40,
0x09, 0x20, 0xea, 0xde, 0x58, 0x71, 0x54, 0xb4, 0x86, 0x24, 0x4f, 0xeb, 0x36, 0x98, 0x37, 0x7d,
0x9e, 0x7e, 0x21, 0x01, 0xf7, 0x0d, 0x24, 0x1f, 0xe8, 0xe8, 0x83, 0x00, 0xa6, 0xdd, 0xee, 0xf8,
0xac, 0x20, 0xb3, 0xf3, 0x29, 0x4b, 0x25, 0x74, 0xef, 0x93, 0xb3, 0xa7, 0xe3, 0x07, 0xfa, 0x24,
0xd5, 0x03, 0x13, 0x51, 0x83, 0x2b, 0xa1, 0xa3, 0x29, 0xea, 0x68, 0xf1, 0x94, 0x99, 0xf6, 0xd5,
0xba, 0xa7, 0x40, 0x36, 0x2c, 0x13, 0xdb, 0xbe, 0xe6, 0xf9, 0x2e, 0xd6, 0x5b, 0xa6, 0xdd, 0xa4,
0x07, 0x70, 0xa6, 0x9c, 0x6e, 0xe8, 0x96, 0x87, 0xd5, 0x09, 0xa6, 0xde, 0x17, 0x5a, 0x82, 0xa0,
0x55, 0xc6, 0x8d, 0x20, 0x46, 0xbb, 0x10, 0x4c, 0x1d, 0x20, 0x4a, 0x5f, 0x1c, 0x83, 0x5c, 0xa4,
0xad, 0x43, 0x17, 0x21, 0x7f, 0x43, 0xbf, 0xa5, 0x6b, 0xa2, 0x55, 0x67, 0x91, 0xc8, 0x11, 0xd9,
0x1e, 0x6f, 0xd7, 0x9f, 0x82, 0x69, 0x6a, 0xe2, 0x74, 0x7c, 0xec, 0x6a, 0x86, 0xa5, 0x7b, 0x1e,
0x0d, 0x5a, 0x86, 0x9a, 0x22, 0xa2, 0xdb, 0x25, 0xaa, 0x35, 0xa1, 0x41, 0x2b, 0x30, 0x45, 0x11,
0xad, 0x8e, 0xe5, 0x9b, 0x6d, 0x0b, 0x6b, 0xe4, 0xe5, 0xc1, 0xa3, 0x07, 0x71, 0xe0, 0xd9, 0x24,
0xb1, 0xd8, 0xe6, 0x06, 0xc4, 0x23, 0x0f, 0x6d, 0xc0, 0x83, 0x14, 0xd6, 0xc4, 0x36, 0x76, 0x75,
0x1f, 0x6b, 0xf8, 0x67, 0x3a, 0xba, 0xe5, 0x69, 0xba, 0x5d, 0xd7, 0x8e, 0x74, 0xef, 0x48, 0x99,
0x8e, 0x12, 0x9c, 0x27, 0xb6, 0x1b, 0xdc, 0xb4, 0x4a, 0x2d, 0x2b, 0x76, 0xfd, 0xba, 0xee, 0x1d,
0xa1, 0x32, 0x9c, 0xa3, 0x44, 0x9e, 0xef, 0x9a, 0x76, 0x53, 0x33, 0x8e, 0xb0, 0x71, 0x53, 0xeb,
0xf8, 0x8d, 0x2b, 0xca, 0x03, 0x51, 0x06, 0xea, 0xe4, 0x3e, 0xb5, 0x59, 0x23, 0x26, 0x87, 0x7e,
0xe3, 0x0a, 0xda, 0x87, 0x3c, 0x59, 0x8f, 0x96, 0xf9, 0x12, 0xd6, 0x1a, 0x8e, 0x4b, 0x8b, 0x4b,
0x61, 0xc0, 0xe6, 0x8e, 0x04, 0x71, 0x7e, 0x97, 0x03, 0xb6, 0x9d, 0x3a, 0x2e, 0xa7, 0xf7, 0xf7,
0xaa, 0xd5, 0x75, 0x35, 0x27, 0x58, 0x9e, 0x75, 0x5c, 0x92, 0x53, 0x4d, 0x27, 0x88, 0x71, 0x8e,
0xe5, 0x54, 0xd3, 0x11, 0x11, 0x5e, 0x81, 0x29, 0xc3, 0x60, 0xd3, 0x36, 0x0d, 0x8d, 0x77, 0xf9,
0x9e, 0x22, 0x77, 0xc5, 0xcb, 0x30, 0x36, 0x98, 0x01, 0x4f, 0x73, 0x0f, 0x5d, 0x85, 0xfb, 0xc2,
0x78, 0x45, 0x81, 0x93, 0x7d, 0xb3, 0xec, 0x85, 0xae, 0xc0, 0x54, 0xfb, 0xb8, 0x1f, 0x88, 0xba,
0x9e, 0xd8, 0x3e, 0xee, 0x85, 0x3d, 0x42, 0xdf, 0xdc, 0x5c, 0x6c, 0xe8, 0x3e, 0xae, 0x2b, 0xf7,
0x47, 0xad, 0x23, 0x0a, 0xb4, 0x00, 0xb2, 0x61, 0x68, 0xd8, 0xd6, 0x6b, 0x16, 0xd6, 0x74, 0x17,
0xdb, 0xba, 0xa7, 0x5c, 0x88, 0x1a, 0x17, 0x0c, 0xa3, 0x4a, 0xb5, 0x15, 0xaa, 0x44, 0x8f, 0xc3,
0xa4, 0x53, 0xbb, 0x61, 0xb0, 0xe4, 0xd2, 0xda, 0x2e, 0x6e, 0x98, 0x2f, 0x2a, 0x0f, 0xd3, 0x30,
0x4d, 0x10, 0x05, 0x4d, 0xad, 0x3d, 0x2a, 0x46, 0x8f, 0x81, 0x6c, 0x78, 0x47, 0xba, 0xdb, 0xa6,
0xd5, 0xdd, 0x6b, 0xeb, 0x06, 0x56, 0x1e, 0x61, 0xa6, 0x4c, 0xbe, 0x23, 0xc4, 0xe8, 0x79, 0x98,
0xee, 0xd8, 0xa6, 0xed, 0x63, 0xb7, 0xed, 0x62, 0xd2, 0xa4, 0xb3, 0x9d, 0xa6, 0xfc, 0xd3, 0xd8,
0x29, 0x6d, 0xf6, 0x61, 0xd4, 0x9a, 0xad, 0xae, 0x3a, 0xd5, 0xe9, 0x17, 0x96, 0xca, 0x90, 0x8f,
0x2e, 0x3a, 0xca, 0x02, 0x5b, 0x76, 0x59, 0x22, 0x35, 0x74, 0x6d, 0x77, 0x9d, 0x54, 0xbf, 0xcf,
0x56, 0xe5, 0x04, 0xa9, 0xc2, 0x5b, 0x9b, 0x07, 0x55, 0x4d, 0x3d, 0xdc, 0x39, 0xd8, 0xdc, 0xae,
0xca, 0xc9, 0xc7, 0xb3, 0x99, 0x1f, 0x8c, 0xc9, 0x77, 0xee, 0xdc, 0xb9, 0x93, 0x28, 0x7d, 0x37,
0x01, 0x85, 0xee, 0xce, 0x17, 0xfd, 0x14, 0xdc, 0x2f, 0x5e, 0x53, 0x3d, 0xec, 0x6b, 0xb7, 0x4d,
0x97, 0xe6, 0x61, 0x4b, 0x67, 0xbd, 0x63, 0x10, 0xc2, 0x69, 0x6e, 0xb5, 0x8f, 0xfd, 0xcf, 0x98,
0x2e, 0xc9, 0xb2, 0x96, 0xee, 0xa3, 0x2d, 0xb8, 0x60, 0x3b, 0x9a, 0xe7, 0xeb, 0x76, 0x5d, 0x77,
0xeb, 0x5a, 0x78, 0x41, 0xa0, 0xe9, 0x86, 0x81, 0x3d, 0xcf, 0x61, 0x25, 0x20, 0x60, 0xf9, 0x98,
0xed, 0xec, 0x73, 0xe3, 0xf0, 0x6c, 0xac, 0x70, 0xd3, 0x9e, 0xe5, 0x4e, 0x9e, 0xb6, 0xdc, 0x0f,
0x40, 0xb6, 0xa5, 0xb7, 0x35, 0x6c, 0xfb, 0xee, 0x31, 0xed, 0xd7, 0x32, 0x6a, 0xa6, 0xa5, 0xb7,
0xab, 0x64, 0xfc, 0xa3, 0x5b, 0x83, 0x68, 0x1c, 0xff, 0x21, 0x09, 0xf9, 0x68, 0xcf, 0x46, 0x5a,
0x60, 0x83, 0x9e, 0xcf, 0x12, 0xdd, 0xbe, 0x0f, 0xdd, 0xb3, 0xc3, 0x9b, 0x5f, 0x23, 0x07, 0x77,
0x79, 0x94, 0x75, 0x52, 0x2a, 0x43, 0x92, 0xa2, 0x49, 0x36, 0x2c, 0x66, 0xfd, 0x79, 0x46, 0xe5,
0x23, 0xb4, 0x01, 0xa3, 0x37, 0x3c, 0xca, 0x3d, 0x4a, 0xb9, 0x1f, 0xbe, 0x37, 0xf7, 0x73, 0xfb,
0x94, 0x3c, 0xfb, 0xdc, 0xbe, 0xb6, 0xb3, 0xab, 0x6e, 0x57, 0xb6, 0x54, 0x0e, 0x47, 0xe7, 0x21,
0x65, 0xe9, 0x2f, 0x1d, 0x77, 0x1f, 0xf1, 0x54, 0x34, 0x6c, 0xe0, 0xcf, 0x43, 0xea, 0x36, 0xd6,
0x6f, 0x76, 0x1f, 0xac, 0x54, 0xf4, 0x23, 0x4c, 0xfd, 0x05, 0x48, 0xd3, 0x78, 0x21, 0x00, 0x1e,
0x31, 0x79, 0x04, 0x65, 0x20, 0xb5, 0xb6, 0xab, 0x92, 0xf4, 0x97, 0x21, 0xcf, 0xa4, 0xda, 0xde,
0x66, 0x75, 0xad, 0x2a, 0x27, 0x4a, 0x2b, 0x30, 0xca, 0x82, 0x40, 0xb6, 0x46, 0x10, 0x06, 0x79,
0x84, 0x0f, 0x39, 0x87, 0x24, 0xb4, 0x87, 0xdb, 0xab, 0x55, 0x55, 0x4e, 0x44, 0x97, 0xd7, 0x83,
0x7c, 0xb4, 0x5d, 0xfb, 0xf1, 0xe4, 0xd4, 0x5f, 0x4a, 0x90, 0x8b, 0xb4, 0x5f, 0xa4, 0xf0, 0xeb,
0x96, 0xe5, 0xdc, 0xd6, 0x74, 0xcb, 0xd4, 0x3d, 0x9e, 0x14, 0x40, 0x45, 0x15, 0x22, 0x19, 0x76,
0xd1, 0x7e, 0x2c, 0xce, 0xbf, 0x26, 0x81, 0xdc, 0xdb, 0xba, 0xf5, 0x38, 0x28, 0x7d, 0xa4, 0x0e,
0xbe, 0x2a, 0x41, 0xa1, 0xbb, 0x5f, 0xeb, 0x71, 0xef, 0xe2, 0x47, 0xea, 0xde, 0x57, 0x25, 0x18,
0xef, 0xea, 0xd2, 0x7e, 0xa2, 0xbc, 0x7b, 0x25, 0x09, 0x53, 0x03, 0x70, 0xa8, 0xc2, 0xdb, 0x59,
0xd6, 0x61, 0x3f, 0x39, 0xcc, 0xb3, 0xe6, 0x49, 0xb5, 0xdc, 0xd3, 0x5d, 0x9f, 0x77, 0xbf, 0x8f,
0x81, 0x6c, 0xd6, 0xb1, 0xed, 0x9b, 0x0d, 0x13, 0xbb, 0xfc, 0x15, 0x9c, 0xf5, 0xb8, 0x13, 0xa1,
0x9c, 0xbd, 0x85, 0x7f, 0x02, 0x50, 0xdb, 0xf1, 0x4c, 0xdf, 0xbc, 0x85, 0x35, 0xd3, 0x16, 0xef,
0xeb, 0xa4, 0xe7, 0x4d, 0xa9, 0xb2, 0xd0, 0x6c, 0xda, 0x7e, 0x60, 0x6d, 0xe3, 0xa6, 0xde, 0x63,
0x4d, 0xce, 0xbe, 0xa4, 0x2a, 0x0b, 0x4d, 0x60, 0x7d, 0x11, 0xf2, 0x75, 0xa7, 0x43, 0xda, 0x07,
0x66, 0x47, 0x8e, 0x5a, 0x49, 0xcd, 0x31, 0x59, 0x60, 0xc2, 0xfb, 0xbb, 0xf0, 0xa2, 0x20, 0xaf,
0xe6, 0x98, 0x8c, 0x99, 0x3c, 0x0a, 0x13, 0x7a, 0xb3, 0xe9, 0x12, 0x72, 0x41, 0xc4, 0x9a, 0xd6,
0x42, 0x20, 0xa6, 0x86, 0x33, 0xcf, 0x41, 0x46, 0xc4, 0x81, 0x54, 0x33, 0x12, 0x09, 0xad, 0xcd,
0xae, 0x6b, 0x12, 0x73, 0x59, 0x35, 0x63, 0x0b, 0xe5, 0x45, 0xc8, 0x9b, 0x9e, 0x16, 0xde, 0x1b,
0x26, 0x66, 0x13, 0x73, 0x19, 0x35, 0x67, 0x7a, 0xc1, 0x45, 0x51, 0xe9, 0x8d, 0x04, 0x14, 0xba,
0xef, 0x3d, 0xd1, 0x3a, 0x64, 0x2c, 0xc7, 0xd0, 0x69, 0x22, 0xb0, 0x4b, 0xf7, 0xb9, 0x98, 0xab,
0xd2, 0xf9, 0x2d, 0x6e, 0xaf, 0x06, 0xc8, 0x99, 0xbf, 0x95, 0x20, 0x23, 0xc4, 0xe8, 0x1c, 0xa4,
0xda, 0xba, 0x7f, 0x44, 0xe9, 0xd2, 0xab, 0x09, 0x59, 0x52, 0xe9, 0x98, 0xc8, 0xbd, 0xb6, 0x6e,
0xd3, 0x14, 0xe0, 0x72, 0x32, 0x26, 0xeb, 0x6a, 0x61, 0xbd, 0x4e, 0xdb, 0x61, 0xa7, 0xd5, 0xc2,
0xb6, 0xef, 0x89, 0x75, 0xe5, 0xf2, 0x35, 0x2e, 0x46, 0x4f, 0xc0, 0xa4, 0xef, 0xea, 0xa6, 0xd5,
0x65, 0x9b, 0xa2, 0xb6, 0xb2, 0x50, 0x04, 0xc6, 0x65, 0x38, 0x2f, 0x78, 0xeb, 0xd8, 0xd7, 0x8d,
0x23, 0x5c, 0x0f, 0x41, 0xa3, 0xf4, 0x52, 0xed, 0x7e, 0x6e, 0xb0, 0xce, 0xf5, 0x02, 0x5b, 0xfa,
0x9e, 0x04, 0x93, 0xa2, 0x81, 0xaf, 0x07, 0xc1, 0xda, 0x06, 0xd0, 0x6d, 0xdb, 0xf1, 0xa3, 0xe1,
0xea, 0x4f, 0xe5, 0x3e, 0xdc, 0x7c, 0x25, 0x00, 0xa9, 0x11, 0x82, 0x99, 0x16, 0x40, 0xa8, 0x39,
0x35, 0x6c, 0x17, 0x20, 0xc7, 0x2f, 0xb5, 0xe9, 0x2f, 0x23, 0xec, 0xad, 0x0f, 0x98, 0x88, 0x74,
0xfa, 0x68, 0x1a, 0xd2, 0x35, 0xdc, 0x34, 0x6d, 0x7e, 0xd5, 0xc6, 0x06, 0xe2, 0x02, 0x2f, 0x15,
0x5c, 0xe0, 0xad, 0x7e, 0x0e, 0xa6, 0x0c, 0xa7, 0xd5, 0xeb, 0xee, 0xaa, 0xdc, 0xf3, 0xe6, 0xe9,
0x5d, 0x97, 0x3e, 0x0b, 0x61, 0x77, 0xf6, 0xba, 0x24, 0x7d, 0x3d, 0x91, 0xdc, 0xd8, 0x5b, 0xfd,
0x66, 0x62, 0x66, 0x83, 0x41, 0xf7, 0xc4, 0x4c, 0x55, 0xdc, 0xb0, 0xb0, 0x41, 0xbc, 0x87, 0xd7,
0x3f, 0x0e, 0x4f, 0x36, 0x4d, 0xff, 0xa8, 0x53, 0x9b, 0x37, 0x9c, 0xd6, 0x42, 0xd3, 0x69, 0x3a,
0xe1, 0x8f, 0x41, 0x64, 0x44, 0x07, 0xf4, 0x3f, 0xfe, 0x83, 0x50, 0x36, 0x90, 0xce, 0xc4, 0xfe,
0x7a, 0x54, 0xde, 0x81, 0x29, 0x6e, 0xac, 0xd1, 0x1b, 0x69, 0xd6, 0x87, 0xa3, 0x7b, 0xde, 0x4a,
0x28, 0xdf, 0x7e, 0x87, 0x56, 0x3a, 0x75, 0x92, 0x43, 0x89, 0x8e, 0x75, 0xea, 0x65, 0x15, 0xee,
0xeb, 0xe2, 0x63, 0x5b, 0x13, 0xbb, 0x31, 0x8c, 0xdf, 0xe5, 0x8c, 0x53, 0x11, 0xc6, 0x7d, 0x0e,
0x2d, 0xaf, 0xc1, 0xf8, 0x59, 0xb8, 0xfe, 0x9a, 0x73, 0xe5, 0x71, 0x94, 0x64, 0x03, 0x26, 0x28,
0x89, 0xd1, 0xf1, 0x7c, 0xa7, 0x45, 0xcf, 0xbd, 0x7b, 0xd3, 0xfc, 0xcd, 0x3b, 0x6c, 0xaf, 0x14,
0x08, 0x6c, 0x2d, 0x40, 0x95, 0xcb, 0x40, 0x2f, 0xe1, 0xeb, 0xd8, 0xb0, 0x62, 0x18, 0xde, 0xe4,
0x8e, 0x04, 0xf6, 0xe5, 0x4f, 0xc3, 0x34, 0xf9, 0x9f, 0x1e, 0x4b, 0x51, 0x4f, 0xe2, 0xef, 0x60,
0x94, 0xef, 0xbd, 0xcc, 0xb6, 0xe3, 0x54, 0x40, 0x10, 0xf1, 0x29, 0xb2, 0x8a, 0x4d, 0xec, 0xfb,
0xd8, 0xf5, 0x34, 0xdd, 0x1a, 0xe4, 0x5e, 0xe4, 0x0d, 0x56, 0xf9, 0xca, 0xbb, 0xdd, 0xab, 0xb8,
0xc1, 0x90, 0x15, 0xcb, 0x2a, 0x1f, 0xc2, 0xfd, 0x03, 0xb2, 0x62, 0x08, 0xce, 0x57, 0x38, 0xe7,
0x74, 0x5f, 0x66, 0x10, 0xda, 0x3d, 0x10, 0xf2, 0x60, 0x2d, 0x87, 0xe0, 0xfc, 0x2a, 0xe7, 0x44,
0x1c, 0x2b, 0x96, 0x94, 0x30, 0x3e, 0x07, 0x93, 0xb7, 0xb0, 0x5b, 0x73, 0x3c, 0x7e, 0x71, 0x30,
0x04, 0xdd, 0xab, 0x9c, 0x6e, 0x82, 0x03, 0xe9, 0x35, 0x02, 0xe1, 0xba, 0x0a, 0x99, 0x86, 0x6e,
0xe0, 0x21, 0x28, 0xbe, 0xc6, 0x29, 0xc6, 0x88, 0x3d, 0x81, 0x56, 0x20, 0xdf, 0x74, 0x78, 0x65,
0x8a, 0x87, 0xbf, 0xc6, 0xe1, 0x39, 0x81, 0xe1, 0x14, 0x6d, 0xa7, 0xdd, 0xb1, 0x48, 0xd9, 0x8a,
0xa7, 0xf8, 0x4d, 0x41, 0x21, 0x30, 0x9c, 0xe2, 0x0c, 0x61, 0x7d, 0x5d, 0x50, 0x78, 0x91, 0x78,
0x3e, 0x03, 0x39, 0xc7, 0xb6, 0x8e, 0x1d, 0x7b, 0x18, 0x27, 0x7e, 0x8b, 0x33, 0x00, 0x87, 0x10,
0x82, 0x6b, 0x90, 0x1d, 0x76, 0x21, 0x7e, 0xfb, 0x5d, 0xb1, 0x3d, 0xc4, 0x0a, 0x6c, 0xc0, 0x84,
0x38, 0xa0, 0x4c, 0xc7, 0x1e, 0x82, 0xe2, 0x77, 0x38, 0x45, 0x21, 0x02, 0xe3, 0xd3, 0xf0, 0xb1,
0xe7, 0x37, 0xf1, 0x30, 0x24, 0x6f, 0x88, 0x69, 0x70, 0x08, 0x0f, 0x65, 0x0d, 0xdb, 0xc6, 0xd1,
0x70, 0x0c, 0xdf, 0x10, 0xa1, 0x14, 0x18, 0x42, 0xb1, 0x06, 0xe3, 0x2d, 0xdd, 0xf5, 0x8e, 0x74,
0x6b, 0xa8, 0xe5, 0xf8, 0x5d, 0xce, 0x91, 0x0f, 0x40, 0x3c, 0x22, 0x1d, 0xfb, 0x2c, 0x34, 0xdf,
0x14, 0x11, 0x89, 0xc0, 0xf8, 0xd6, 0xf3, 0x7c, 0x7a, 0x37, 0x73, 0x16, 0xb6, 0xdf, 0x13, 0x5b,
0x8f, 0x61, 0xb7, 0xa3, 0x8c, 0xd7, 0x20, 0xeb, 0x99, 0x2f, 0x0d, 0x45, 0xf3, 0xfb, 0x62, 0xa5,
0x29, 0x80, 0x80, 0x5f, 0x80, 0xf3, 0x03, 0xcb, 0xc4, 0x10, 0x64, 0x7f, 0xc0, 0xc9, 0xce, 0x0d,
0x28, 0x15, 0xfc, 0x48, 0x38, 0x2b, 0xe5, 0x1f, 0x8a, 0x23, 0x01, 0xf7, 0x70, 0xed, 0x91, 0xce,
0xde, 0xd3, 0x1b, 0x67, 0x8b, 0xda, 0x1f, 0x89, 0xa8, 0x31, 0x6c, 0x57, 0xd4, 0x0e, 0xe0, 0x1c,
0x67, 0x3c, 0xdb, 0xba, 0x7e, 0x4b, 0x1c, 0xac, 0x0c, 0x7d, 0xd8, 0xbd, 0xba, 0x9f, 0x83, 0x99,
0x20, 0x9c, 0xa2, 0x29, 0xf5, 0xb4, 0x96, 0xde, 0x1e, 0x82, 0xf9, 0xdb, 0x9c, 0x59, 0x9c, 0xf8,
0x41, 0x57, 0xeb, 0x6d, 0xeb, 0x6d, 0x42, 0xfe, 0x3c, 0x28, 0x82, 0xbc, 0x63, 0xbb, 0xd8, 0x70,
0x9a, 0xb6, 0xf9, 0x12, 0xae, 0x0f, 0x41, 0xfd, 0xc7, 0x3d, 0x4b, 0x75, 0x18, 0x81, 0x13, 0xe6,
0x4d, 0x90, 0x83, 0x5e, 0x45, 0x33, 0x5b, 0x6d, 0xc7, 0xf5, 0x63, 0x18, 0xff, 0x44, 0xac, 0x54,
0x80, 0xdb, 0xa4, 0xb0, 0x72, 0x15, 0x0a, 0x74, 0x38, 0x6c, 0x4a, 0xfe, 0x29, 0x27, 0x1a, 0x0f,
0x51, 0xfc, 0xe0, 0x30, 0x9c, 0x56, 0x5b, 0x77, 0x87, 0x39, 0xff, 0xfe, 0x4c, 0x1c, 0x1c, 0x1c,
0xc2, 0x0f, 0x0e, 0xff, 0xb8, 0x8d, 0x49, 0xb5, 0x1f, 0x82, 0xe1, 0x3b, 0xe2, 0xe0, 0x10, 0x18,
0x4e, 0x21, 0x1a, 0x86, 0x21, 0x28, 0xfe, 0x5c, 0x50, 0x08, 0x0c, 0xdb, 0x03, 0x13, 0x3d, 0xfd,
0x00, 0x8a, 0xfb, 0xf9, 0x5d, 0xf9, 0xfc, 0xfb, 0xfc, 0xe4, 0xe8, 0x6e, 0x07, 0xca, 0x5b, 0x64,
0x91, 0xba, 0x8b, 0x76, 0x3c, 0xd9, 0xcb, 0xef, 0x07, 0xeb, 0xd4, 0x55, 0xb3, 0xcb, 0xcf, 0xc2,
0x78, 0x57, 0xc1, 0x8e, 0xa7, 0xfa, 0x59, 0x4e, 0x95, 0x8f, 0xd6, 0xeb, 0xf2, 0x0a, 0xa4, 0x48,
0xf1, 0x8d, 0x87, 0xff, 0x1c, 0x87, 0x53, 0xf3, 0xf2, 0x27, 0x21, 0x23, 0x8a, 0x6e, 0x3c, 0xf4,
0xe7, 0x39, 0x34, 0x80, 0x10, 0xb8, 0x28, 0xb8, 0xf1, 0xf0, 0x5f, 0x10, 0x70, 0x01, 0x21, 0xf0,
0xe1, 0x43, 0xf8, 0x57, 0x5f, 0x4c, 0xf1, 0x43, 0x53, 0xc4, 0xee, 0x1a, 0x8c, 0xf1, 0x4a, 0x1b,
0x8f, 0xfe, 0x02, 0x7f, 0xb8, 0x40, 0x94, 0x2f, 0x43, 0x7a, 0xc8, 0x80, 0xff, 0x22, 0x87, 0x32,
0xfb, 0xf2, 0x1a, 0xe4, 0x22, 0xd5, 0x35, 0x1e, 0xfe, 0x4b, 0x1c, 0x1e, 0x45, 0x11, 0xd7, 0x79,
0x75, 0x8d, 0x27, 0xf8, 0x65, 0xe1, 0x3a, 0x47, 0x90, 0xb0, 0x89, 0xc2, 0x1a, 0x8f, 0xfe, 0x15,
0x11, 0x75, 0x01, 0x29, 0x3f, 0x03, 0xd9, 0xe0, 0xb0, 0x8c, 0xc7, 0xff, 0x2a, 0xc7, 0x87, 0x18,
0x12, 0x81, 0xc8, 0x61, 0x1d, 0x4f, 0xf1, 0x25, 0x11, 0x81, 0x08, 0x8a, 0x6c, 0xa3, 0xde, 0x02,
0x1c, 0xcf, 0xf4, 0x6b, 0x62, 0x1b, 0xf5, 0xd4, 0x5f, 0xb2, 0x9a, 0xf4, 0xcc, 0x8a, 0xa7, 0xf8,
0x75, 0xb1, 0x9a, 0xd4, 0x9e, 0xb8, 0xd1, 0x5b, 0xd1, 0xe2, 0x39, 0x7e, 0x43, 0xb8, 0xd1, 0x53,
0xd0, 0xca, 0x7b, 0x80, 0xfa, 0xab, 0x59, 0x3c, 0xdf, 0x97, 0x39, 0xdf, 0x64, 0x5f, 0x31, 0x2b,
0x7f, 0x06, 0xce, 0x0d, 0xae, 0x64, 0xf1, 0xac, 0x5f, 0x79, 0xbf, 0xe7, 0xdd, 0x23, 0x5a, 0xc8,
0xca, 0x07, 0xe1, 0xbb, 0x47, 0xb4, 0x8a, 0xc5, 0xd3, 0xbe, 0xf2, 0x7e, 0xf7, 0xab, 0x69, 0xb4,
0x88, 0x95, 0x2b, 0x00, 0x61, 0x01, 0x89, 0xe7, 0x7a, 0x95, 0x73, 0x45, 0x40, 0x64, 0x6b, 0xf0,
0xfa, 0x11, 0x8f, 0xff, 0x9a, 0xd8, 0x1a, 0x1c, 0x41, 0xb6, 0x86, 0x28, 0x1d, 0xf1, 0xe8, 0xd7,
0xc4, 0xd6, 0x10, 0x90, 0xf2, 0x35, 0xc8, 0xd8, 0x1d, 0xcb, 0x22, 0xb9, 0x85, 0xee, 0xfd, 0x45,
0x8c, 0xf2, 0xcf, 0x1f, 0x72, 0xb0, 0x00, 0x94, 0x57, 0x20, 0x8d, 0x5b, 0x35, 0x5c, 0x8f, 0x43,
0xfe, 0xcb, 0x87, 0xe2, 0x3c, 0x21, 0xd6, 0xe5, 0x67, 0x00, 0xd8, 0x9b, 0x2f, 0xfd, 0x41, 0x24,
0x06, 0xfb, 0xaf, 0x1f, 0xf2, 0x1f, 0xdb, 0x43, 0x48, 0x48, 0xc0, 0x7e, 0xba, 0xbf, 0x37, 0xc1,
0xbb, 0xdd, 0x04, 0xf4, 0x6d, 0xf9, 0x2a, 0x8c, 0xdd, 0xf0, 0x1c, 0xdb, 0xd7, 0x9b, 0x71, 0xe8,
0x7f, 0xe3, 0x68, 0x61, 0x4f, 0x02, 0xd6, 0x72, 0x5c, 0xec, 0xeb, 0x4d, 0x2f, 0x0e, 0xfb, 0xef,
0x1c, 0x1b, 0x00, 0x08, 0xd8, 0xd0, 0x3d, 0x7f, 0x98, 0x79, 0xff, 0x87, 0x00, 0x0b, 0x00, 0x71,
0x9a, 0xfc, 0x7f, 0x13, 0x1f, 0xc7, 0x61, 0xdf, 0x13, 0x4e, 0x73, 0xfb, 0xf2, 0x27, 0x21, 0x4b,
0xfe, 0x65, 0x1f, 0xa0, 0xc4, 0x80, 0xff, 0x93, 0x83, 0x43, 0x04, 0x79, 0xb2, 0xe7, 0xd7, 0x7d,
0x33, 0x3e, 0xd8, 0xff, 0xc5, 0x57, 0x5a, 0xd8, 0x97, 0x2b, 0x90, 0xf3, 0xfc, 0x7a, 0xbd, 0xe3,
0xb2, 0x9b, 0xb8, 0x18, 0xf8, 0x7f, 0x7f, 0x18, 0xbc, 0x91, 0x06, 0x98, 0xd5, 0x8b, 0x83, 0x2f,
0xd7, 0x60, 0xc3, 0xd9, 0x70, 0xd8, 0xb5, 0x1a, 0x7c, 0x90, 0x01, 0xc5, 0x70, 0x5a, 0x35, 0xc7,
0x5b, 0xb0, 0xb1, 0xe9, 0x1f, 0x61, 0x77, 0xc1, 0xb1, 0xb9, 0x2d, 0x4a, 0x3a, 0x36, 0x9e, 0x39,
0xdb, 0x0d, 0x5a, 0xe9, 0x3c, 0xa4, 0xf7, 0x3b, 0xb5, 0xda, 0x31, 0x92, 0x21, 0xe9, 0x75, 0x6a,
0xfc, 0x03, 0x09, 0xf2, 0x6f, 0xe9, 0xed, 0x24, 0x8c, 0x57, 0x2c, 0xeb, 0xe0, 0xb8, 0x8d, 0xbd,
0x5d, 0x1b, 0xef, 0x36, 0x90, 0x02, 0xa3, 0x74, 0x16, 0x4f, 0x53, 0x33, 0xe9, 0xfa, 0x88, 0xca,
0xc7, 0x81, 0x66, 0x91, 0xde, 0x2d, 0x26, 0x02, 0xcd, 0x62, 0xa0, 0x59, 0x62, 0x57, 0x8b, 0x81,
0x66, 0x29, 0xd0, 0x2c, 0xd3, 0x0b, 0xc6, 0x64, 0xa0, 0x59, 0x0e, 0x34, 0x2b, 0xf4, 0x02, 0x7d,
0x3c, 0xd0, 0xac, 0x04, 0x9a, 0x4b, 0xf4, 0xca, 0x3c, 0x15, 0x68, 0x2e, 0x05, 0x9a, 0xcb, 0xf4,
0xa6, 0x7c, 0x32, 0xd0, 0x5c, 0x0e, 0x34, 0x57, 0xe8, 0xed, 0x38, 0x0a, 0x34, 0x57, 0x02, 0xcd,
0x55, 0xfa, 0x19, 0xc4, 0x58, 0xa0, 0xb9, 0x8a, 0x66, 0x60, 0x8c, 0xcd, 0xec, 0x29, 0xfa, 0xeb,
0xe3, 0xc4, 0xf5, 0x11, 0x55, 0x08, 0x42, 0xdd, 0xd3, 0xf4, 0x53, 0x87, 0xd1, 0x50, 0xf7, 0x74,
0xa8, 0x5b, 0xa4, 0xdf, 0xfc, 0xca, 0xa1, 0x6e, 0x31, 0xd4, 0x2d, 0x29, 0xe3, 0x64, 0xf1, 0x43,
0xdd, 0x52, 0xa8, 0x5b, 0x56, 0x0a, 0x64, 0x05, 0x42, 0xdd, 0x72, 0xa8, 0x5b, 0x51, 0x26, 0x66,
0xa5, 0xb9, 0x7c, 0xa8, 0x5b, 0x41, 0x4f, 0x42, 0xce, 0xeb, 0xd4, 0x34, 0xfe, 0x63, 0x39, 0xfd,
0xa4, 0x22, 0xb7, 0x08, 0xf3, 0x24, 0x27, 0xe8, 0xb2, 0x5e, 0x1f, 0x51, 0xc1, 0xeb, 0xd4, 0xf8,
0xe9, 0xb8, 0x9a, 0x07, 0xfa, 0xe6, 0xaf, 0xd1, 0x6f, 0x09, 0x4b, 0x6f, 0x49, 0x90, 0x3d, 0xb8,
0xed, 0xd0, 0xdf, 0x1e, 0xbd, 0xff, 0xe7, 0xc5, 0x15, 0x4e, 0x2f, 0x2d, 0x2b, 0x25, 0x3a, 0x21,
0x49, 0x15, 0x82, 0x50, 0xb7, 0xa2, 0x3c, 0x44, 0x27, 0x14, 0xe8, 0x56, 0xd0, 0x02, 0xe4, 0x23,
0x13, 0x5a, 0xa4, 0x5f, 0x49, 0x74, 0xcf, 0x48, 0x52, 0x73, 0xe1, 0x8c, 0x16, 0x57, 0xd3, 0x40,
0xd2, 0x9e, 0xfc, 0xf1, 0x6f, 0x3b, 0xa5, 0x2f, 0x25, 0x20, 0xc7, 0x2e, 0x0b, 0xe9, 0xac, 0xc8,
0xa3, 0x58, 0x3f, 0x7e, 0xcc, 0xdd, 0x18, 0x51, 0x85, 0x00, 0xa9, 0x00, 0xcc, 0x94, 0x64, 0x38,
0xf3, 0x64, 0xf5, 0xa9, 0xbf, 0x7f, 0xfb, 0xc2, 0x27, 0x4e, 0xdd, 0x41, 0x24, 0x76, 0x0b, 0xec,
0x74, 0x9d, 0x3f, 0x34, 0x6d, 0xff, 0xe9, 0xc5, 0x2b, 0x24, 0xc0, 0x21, 0x0b, 0x3a, 0x84, 0xcc,
0x9a, 0xee, 0xd1, 0x2f, 0xa5, 0xa8, 0xeb, 0xa9, 0xd5, 0xcb, 0xff, 0xfb, 0xf6, 0x85, 0xa5, 0x18,
0x46, 0x7e, 0xf0, 0xcd, 0x6f, 0x1f, 0x13, 0xd6, 0x4b, 0xcb, 0x04, 0x7e, 0x7d, 0x44, 0x0d, 0xa8,
0xd0, 0xa2, 0x70, 0x75, 0x47, 0x6f, 0xb1, 0xcf, 0x41, 0x92, 0xab, 0xf2, 0xc9, 0xdb, 0x17, 0xf2,
0xdb, 0xc7, 0xa1, 0x3c, 0x74, 0x85, 0x8c, 0x56, 0x33, 0x30, 0xca, 0x5c, 0x5d, 0x5d, 0x7f, 0xf3,
0x6e, 0x71, 0xe4, 0xad, 0xbb, 0xc5, 0x91, 0xbf, 0xbb, 0x5b, 0x1c, 0xf9, 0xfe, 0xdd, 0xa2, 0xf4,
0xde, 0xdd, 0xa2, 0xf4, 0xc1, 0xdd, 0xa2, 0x74, 0xe7, 0xa4, 0x28, 0x7d, 0xe3, 0xa4, 0x28, 0x7d,
0xeb, 0xa4, 0x28, 0xfd, 0xc5, 0x49, 0x51, 0x7a, 0xf3, 0xa4, 0x38, 0xf2, 0xd6, 0x49, 0x71, 0xe4,
0xfb, 0x27, 0x45, 0xe9, 0x07, 0x27, 0xc5, 0x91, 0xf7, 0x4e, 0x8a, 0xd2, 0x07, 0x27, 0xc5, 0x91,
0x3b, 0xff, 0x58, 0x1c, 0xf9, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x14, 0xc2, 0xce, 0x1b, 0xa2,
0x31, 0x00, 0x00,
}
r := bytes.NewReader(gzipped)
gzipr, err := compress_gzip.NewReader(r)
if err != nil {
panic(err)
}
ungzipped, err := io_ioutil.ReadAll(gzipr)
if err != nil {
panic(err)
}
if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil {
panic(err)
}
return d
}
func (this *Subby) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*Subby)
if !ok {
that2, ok := that.(Subby)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *Subby")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *Subby but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *Subby but is not nil && this == nil")
}
if this.Sub != nil && that1.Sub != nil {
if *this.Sub != *that1.Sub {
return fmt.Errorf("Sub this(%v) Not Equal that(%v)", *this.Sub, *that1.Sub)
}
} else if this.Sub != nil {
return fmt.Errorf("this.Sub == nil && that.Sub != nil")
} else if that1.Sub != nil {
return fmt.Errorf("Sub this(%v) Not Equal that(%v)", this.Sub, that1.Sub)
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *Subby) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*Subby)
if !ok {
that2, ok := that.(Subby)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Sub != nil && that1.Sub != nil {
if *this.Sub != *that1.Sub {
return false
}
} else if this.Sub != nil {
return false
} else if that1.Sub != nil {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *AllTypesOneOf) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf)
if !ok {
that2, ok := that.(AllTypesOneOf)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf but is not nil && this == nil")
}
if that1.TestOneof == nil {
if this.TestOneof != nil {
return fmt.Errorf("this.TestOneof != nil && that1.TestOneof == nil")
}
} else if this.TestOneof == nil {
return fmt.Errorf("this.TestOneof == nil && that1.TestOneof != nil")
} else if err := this.TestOneof.VerboseEqual(that1.TestOneof); err != nil {
return err
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *AllTypesOneOf_Field1) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field1)
if !ok {
that2, ok := that.(AllTypesOneOf_Field1)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field1")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field1 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field1 but is not nil && this == nil")
}
if this.Field1 != that1.Field1 {
return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1)
}
return nil
}
func (this *AllTypesOneOf_Field2) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field2)
if !ok {
that2, ok := that.(AllTypesOneOf_Field2)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field2")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field2 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field2 but is not nil && this == nil")
}
if this.Field2 != that1.Field2 {
return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2)
}
return nil
}
func (this *AllTypesOneOf_Field3) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field3)
if !ok {
that2, ok := that.(AllTypesOneOf_Field3)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field3")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field3 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field3 but is not nil && this == nil")
}
if this.Field3 != that1.Field3 {
return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3)
}
return nil
}
func (this *AllTypesOneOf_Field4) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field4)
if !ok {
that2, ok := that.(AllTypesOneOf_Field4)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field4")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field4 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field4 but is not nil && this == nil")
}
if this.Field4 != that1.Field4 {
return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", this.Field4, that1.Field4)
}
return nil
}
func (this *AllTypesOneOf_Field5) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field5)
if !ok {
that2, ok := that.(AllTypesOneOf_Field5)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field5")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field5 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field5 but is not nil && this == nil")
}
if this.Field5 != that1.Field5 {
return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", this.Field5, that1.Field5)
}
return nil
}
func (this *AllTypesOneOf_Field6) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field6)
if !ok {
that2, ok := that.(AllTypesOneOf_Field6)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field6")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field6 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field6 but is not nil && this == nil")
}
if this.Field6 != that1.Field6 {
return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", this.Field6, that1.Field6)
}
return nil
}
func (this *AllTypesOneOf_Field7) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field7)
if !ok {
that2, ok := that.(AllTypesOneOf_Field7)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field7")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field7 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field7 but is not nil && this == nil")
}
if this.Field7 != that1.Field7 {
return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", this.Field7, that1.Field7)
}
return nil
}
func (this *AllTypesOneOf_Field8) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field8)
if !ok {
that2, ok := that.(AllTypesOneOf_Field8)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field8")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field8 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field8 but is not nil && this == nil")
}
if this.Field8 != that1.Field8 {
return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", this.Field8, that1.Field8)
}
return nil
}
func (this *AllTypesOneOf_Field9) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field9)
if !ok {
that2, ok := that.(AllTypesOneOf_Field9)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field9")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field9 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field9 but is not nil && this == nil")
}
if this.Field9 != that1.Field9 {
return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", this.Field9, that1.Field9)
}
return nil
}
func (this *AllTypesOneOf_Field10) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field10)
if !ok {
that2, ok := that.(AllTypesOneOf_Field10)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field10")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field10 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field10 but is not nil && this == nil")
}
if this.Field10 != that1.Field10 {
return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", this.Field10, that1.Field10)
}
return nil
}
func (this *AllTypesOneOf_Field11) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field11)
if !ok {
that2, ok := that.(AllTypesOneOf_Field11)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field11")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field11 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field11 but is not nil && this == nil")
}
if this.Field11 != that1.Field11 {
return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", this.Field11, that1.Field11)
}
return nil
}
func (this *AllTypesOneOf_Field12) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field12)
if !ok {
that2, ok := that.(AllTypesOneOf_Field12)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field12")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field12 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field12 but is not nil && this == nil")
}
if this.Field12 != that1.Field12 {
return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", this.Field12, that1.Field12)
}
return nil
}
func (this *AllTypesOneOf_Field13) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field13)
if !ok {
that2, ok := that.(AllTypesOneOf_Field13)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field13")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field13 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field13 but is not nil && this == nil")
}
if this.Field13 != that1.Field13 {
return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", this.Field13, that1.Field13)
}
return nil
}
func (this *AllTypesOneOf_Field14) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field14)
if !ok {
that2, ok := that.(AllTypesOneOf_Field14)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field14")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field14 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field14 but is not nil && this == nil")
}
if this.Field14 != that1.Field14 {
return fmt.Errorf("Field14 this(%v) Not Equal that(%v)", this.Field14, that1.Field14)
}
return nil
}
func (this *AllTypesOneOf_Field15) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_Field15)
if !ok {
that2, ok := that.(AllTypesOneOf_Field15)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_Field15")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_Field15 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_Field15 but is not nil && this == nil")
}
if !bytes.Equal(this.Field15, that1.Field15) {
return fmt.Errorf("Field15 this(%v) Not Equal that(%v)", this.Field15, that1.Field15)
}
return nil
}
func (this *AllTypesOneOf_SubMessage) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*AllTypesOneOf_SubMessage)
if !ok {
that2, ok := that.(AllTypesOneOf_SubMessage)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *AllTypesOneOf_SubMessage")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *AllTypesOneOf_SubMessage but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *AllTypesOneOf_SubMessage but is not nil && this == nil")
}
if !this.SubMessage.Equal(that1.SubMessage) {
return fmt.Errorf("SubMessage this(%v) Not Equal that(%v)", this.SubMessage, that1.SubMessage)
}
return nil
}
func (this *AllTypesOneOf) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf)
if !ok {
that2, ok := that.(AllTypesOneOf)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if that1.TestOneof == nil {
if this.TestOneof != nil {
return false
}
} else if this.TestOneof == nil {
return false
} else if !this.TestOneof.Equal(that1.TestOneof) {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *AllTypesOneOf_Field1) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field1)
if !ok {
that2, ok := that.(AllTypesOneOf_Field1)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field1 != that1.Field1 {
return false
}
return true
}
func (this *AllTypesOneOf_Field2) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field2)
if !ok {
that2, ok := that.(AllTypesOneOf_Field2)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field2 != that1.Field2 {
return false
}
return true
}
func (this *AllTypesOneOf_Field3) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field3)
if !ok {
that2, ok := that.(AllTypesOneOf_Field3)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field3 != that1.Field3 {
return false
}
return true
}
func (this *AllTypesOneOf_Field4) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field4)
if !ok {
that2, ok := that.(AllTypesOneOf_Field4)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field4 != that1.Field4 {
return false
}
return true
}
func (this *AllTypesOneOf_Field5) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field5)
if !ok {
that2, ok := that.(AllTypesOneOf_Field5)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field5 != that1.Field5 {
return false
}
return true
}
func (this *AllTypesOneOf_Field6) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field6)
if !ok {
that2, ok := that.(AllTypesOneOf_Field6)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field6 != that1.Field6 {
return false
}
return true
}
func (this *AllTypesOneOf_Field7) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field7)
if !ok {
that2, ok := that.(AllTypesOneOf_Field7)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field7 != that1.Field7 {
return false
}
return true
}
func (this *AllTypesOneOf_Field8) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field8)
if !ok {
that2, ok := that.(AllTypesOneOf_Field8)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field8 != that1.Field8 {
return false
}
return true
}
func (this *AllTypesOneOf_Field9) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field9)
if !ok {
that2, ok := that.(AllTypesOneOf_Field9)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field9 != that1.Field9 {
return false
}
return true
}
func (this *AllTypesOneOf_Field10) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field10)
if !ok {
that2, ok := that.(AllTypesOneOf_Field10)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field10 != that1.Field10 {
return false
}
return true
}
func (this *AllTypesOneOf_Field11) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field11)
if !ok {
that2, ok := that.(AllTypesOneOf_Field11)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field11 != that1.Field11 {
return false
}
return true
}
func (this *AllTypesOneOf_Field12) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field12)
if !ok {
that2, ok := that.(AllTypesOneOf_Field12)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field12 != that1.Field12 {
return false
}
return true
}
func (this *AllTypesOneOf_Field13) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field13)
if !ok {
that2, ok := that.(AllTypesOneOf_Field13)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field13 != that1.Field13 {
return false
}
return true
}
func (this *AllTypesOneOf_Field14) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field14)
if !ok {
that2, ok := that.(AllTypesOneOf_Field14)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field14 != that1.Field14 {
return false
}
return true
}
func (this *AllTypesOneOf_Field15) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_Field15)
if !ok {
that2, ok := that.(AllTypesOneOf_Field15)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !bytes.Equal(this.Field15, that1.Field15) {
return false
}
return true
}
func (this *AllTypesOneOf_SubMessage) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*AllTypesOneOf_SubMessage)
if !ok {
that2, ok := that.(AllTypesOneOf_SubMessage)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !this.SubMessage.Equal(that1.SubMessage) {
return false
}
return true
}
func (this *TwoOneofs) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs)
if !ok {
that2, ok := that.(TwoOneofs)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs but is not nil && this == nil")
}
if that1.One == nil {
if this.One != nil {
return fmt.Errorf("this.One != nil && that1.One == nil")
}
} else if this.One == nil {
return fmt.Errorf("this.One == nil && that1.One != nil")
} else if err := this.One.VerboseEqual(that1.One); err != nil {
return err
}
if that1.Two == nil {
if this.Two != nil {
return fmt.Errorf("this.Two != nil && that1.Two == nil")
}
} else if this.Two == nil {
return fmt.Errorf("this.Two == nil && that1.Two != nil")
} else if err := this.Two.VerboseEqual(that1.Two); err != nil {
return err
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *TwoOneofs_Field1) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field1)
if !ok {
that2, ok := that.(TwoOneofs_Field1)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field1")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field1 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field1 but is not nil && this == nil")
}
if this.Field1 != that1.Field1 {
return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1)
}
return nil
}
func (this *TwoOneofs_Field2) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field2)
if !ok {
that2, ok := that.(TwoOneofs_Field2)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field2")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field2 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field2 but is not nil && this == nil")
}
if this.Field2 != that1.Field2 {
return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2)
}
return nil
}
func (this *TwoOneofs_Field3) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field3)
if !ok {
that2, ok := that.(TwoOneofs_Field3)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field3")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field3 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field3 but is not nil && this == nil")
}
if this.Field3 != that1.Field3 {
return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3)
}
return nil
}
func (this *TwoOneofs_Field34) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field34)
if !ok {
that2, ok := that.(TwoOneofs_Field34)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field34")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field34 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field34 but is not nil && this == nil")
}
if this.Field34 != that1.Field34 {
return fmt.Errorf("Field34 this(%v) Not Equal that(%v)", this.Field34, that1.Field34)
}
return nil
}
func (this *TwoOneofs_Field35) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_Field35)
if !ok {
that2, ok := that.(TwoOneofs_Field35)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_Field35")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_Field35 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_Field35 but is not nil && this == nil")
}
if !bytes.Equal(this.Field35, that1.Field35) {
return fmt.Errorf("Field35 this(%v) Not Equal that(%v)", this.Field35, that1.Field35)
}
return nil
}
func (this *TwoOneofs_SubMessage2) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*TwoOneofs_SubMessage2)
if !ok {
that2, ok := that.(TwoOneofs_SubMessage2)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *TwoOneofs_SubMessage2")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *TwoOneofs_SubMessage2 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *TwoOneofs_SubMessage2 but is not nil && this == nil")
}
if !this.SubMessage2.Equal(that1.SubMessage2) {
return fmt.Errorf("SubMessage2 this(%v) Not Equal that(%v)", this.SubMessage2, that1.SubMessage2)
}
return nil
}
func (this *TwoOneofs) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs)
if !ok {
that2, ok := that.(TwoOneofs)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if that1.One == nil {
if this.One != nil {
return false
}
} else if this.One == nil {
return false
} else if !this.One.Equal(that1.One) {
return false
}
if that1.Two == nil {
if this.Two != nil {
return false
}
} else if this.Two == nil {
return false
} else if !this.Two.Equal(that1.Two) {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *TwoOneofs_Field1) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field1)
if !ok {
that2, ok := that.(TwoOneofs_Field1)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field1 != that1.Field1 {
return false
}
return true
}
func (this *TwoOneofs_Field2) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field2)
if !ok {
that2, ok := that.(TwoOneofs_Field2)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field2 != that1.Field2 {
return false
}
return true
}
func (this *TwoOneofs_Field3) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field3)
if !ok {
that2, ok := that.(TwoOneofs_Field3)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field3 != that1.Field3 {
return false
}
return true
}
func (this *TwoOneofs_Field34) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field34)
if !ok {
that2, ok := that.(TwoOneofs_Field34)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field34 != that1.Field34 {
return false
}
return true
}
func (this *TwoOneofs_Field35) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_Field35)
if !ok {
that2, ok := that.(TwoOneofs_Field35)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !bytes.Equal(this.Field35, that1.Field35) {
return false
}
return true
}
func (this *TwoOneofs_SubMessage2) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*TwoOneofs_SubMessage2)
if !ok {
that2, ok := that.(TwoOneofs_SubMessage2)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !this.SubMessage2.Equal(that1.SubMessage2) {
return false
}
return true
}
func (this *CustomOneof) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof)
if !ok {
that2, ok := that.(CustomOneof)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof but is not nil && this == nil")
}
if that1.Custom == nil {
if this.Custom != nil {
return fmt.Errorf("this.Custom != nil && that1.Custom == nil")
}
} else if this.Custom == nil {
return fmt.Errorf("this.Custom == nil && that1.Custom != nil")
} else if err := this.Custom.VerboseEqual(that1.Custom); err != nil {
return err
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *CustomOneof_Stringy) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof_Stringy)
if !ok {
that2, ok := that.(CustomOneof_Stringy)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof_Stringy")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof_Stringy but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof_Stringy but is not nil && this == nil")
}
if this.Stringy != that1.Stringy {
return fmt.Errorf("Stringy this(%v) Not Equal that(%v)", this.Stringy, that1.Stringy)
}
return nil
}
func (this *CustomOneof_CustomType) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof_CustomType)
if !ok {
that2, ok := that.(CustomOneof_CustomType)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof_CustomType")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof_CustomType but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof_CustomType but is not nil && this == nil")
}
if !this.CustomType.Equal(that1.CustomType) {
return fmt.Errorf("CustomType this(%v) Not Equal that(%v)", this.CustomType, that1.CustomType)
}
return nil
}
func (this *CustomOneof_CastType) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof_CastType)
if !ok {
that2, ok := that.(CustomOneof_CastType)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof_CastType")
}
}
if that1 == nil {
if this == nil |
return fmt.Errorf("that is type *CustomOneof_CastType but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof_CastType but is not nil && this == nil")
}
if this.CastType != that1.CastType {
return fmt.Errorf("CastType this(%v) Not Equal that(%v)", this.CastType, that1.CastType)
}
return nil
}
func (this *CustomOneof_MyCustomName) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*CustomOneof_MyCustomName)
if !ok {
that2, ok := that.(CustomOneof_MyCustomName)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *CustomOneof_MyCustomName")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *CustomOneof_MyCustomName but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *CustomOneof_MyCustomName but is not nil && this == nil")
}
if this.MyCustomName != that1.MyCustomName {
return fmt.Errorf("MyCustomName this(%v) Not Equal that(%v)", this.MyCustomName, that1.MyCustomName)
}
return nil
}
func (this *CustomOneof) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof)
if !ok {
that2, ok := that.(CustomOneof)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if that1.Custom == nil {
if this.Custom != nil {
return false
}
} else if this.Custom == nil {
return false
} else if !this.Custom.Equal(that1.Custom) {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *CustomOneof_Stringy) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof_Stringy)
if !ok {
that2, ok := that.(CustomOneof_Stringy)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Stringy != that1.Stringy {
return false
}
return true
}
func (this *CustomOneof_CustomType) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof_CustomType)
if !ok {
that2, ok := that.(CustomOneof_CustomType)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !this.CustomType.Equal(that1.CustomType) {
return false
}
return true
}
func (this *CustomOneof_CastType) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof_CastType)
if !ok {
that2, ok := that.(CustomOneof_CastType)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.CastType != that1.CastType {
return false
}
return true
}
func (this *CustomOneof_MyCustomName) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*CustomOneof_MyCustomName)
if !ok {
that2, ok := that.(CustomOneof_MyCustomName)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.MyCustomName != that1.MyCustomName {
return false
}
return true
}
func (this *Subby) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 5)
s = append(s, "&one.Subby{")
if this.Sub != nil {
s = append(s, "Sub: "+valueToGoStringOne(this.Sub, "string")+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *AllTypesOneOf) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 20)
s = append(s, "&one.AllTypesOneOf{")
if this.TestOneof != nil {
s = append(s, "TestOneof: "+fmt.Sprintf("%#v", this.TestOneof)+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *AllTypesOneOf_Field1) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field1{` +
`Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field2) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field2{` +
`Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field3) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field3{` +
`Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field4) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field4{` +
`Field4:` + fmt.Sprintf("%#v", this.Field4) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field5) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field5{` +
`Field5:` + fmt.Sprintf("%#v", this.Field5) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field6) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field6{` +
`Field6:` + fmt.Sprintf("%#v", this.Field6) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field7) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field7{` +
`Field7:` + fmt.Sprintf("%#v", this.Field7) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field8) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field8{` +
`Field8:` + fmt.Sprintf("%#v", this.Field8) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field9) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field9{` +
`Field9:` + fmt.Sprintf("%#v", this.Field9) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field10) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field10{` +
`Field10:` + fmt.Sprintf("%#v", this.Field10) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field11) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field11{` +
`Field11:` + fmt.Sprintf("%#v", this.Field11) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field12) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field12{` +
`Field12:` + fmt.Sprintf("%#v", this.Field12) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field13) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field13{` +
`Field13:` + fmt.Sprintf("%#v", this.Field13) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field14) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field14{` +
`Field14:` + fmt.Sprintf("%#v", this.Field14) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_Field15) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_Field15{` +
`Field15:` + fmt.Sprintf("%#v", this.Field15) + `}`}, ", ")
return s
}
func (this *AllTypesOneOf_SubMessage) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.AllTypesOneOf_SubMessage{` +
`SubMessage:` + fmt.Sprintf("%#v", this.SubMessage) + `}`}, ", ")
return s
}
func (this *TwoOneofs) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 10)
s = append(s, "&one.TwoOneofs{")
if this.One != nil {
s = append(s, "One: "+fmt.Sprintf("%#v", this.One)+",\n")
}
if this.Two != nil {
s = append(s, "Two: "+fmt.Sprintf("%#v", this.Two)+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *TwoOneofs_Field1) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field1{` +
`Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ")
return s
}
func (this *TwoOneofs_Field2) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field2{` +
`Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ")
return s
}
func (this *TwoOneofs_Field3) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field3{` +
`Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ")
return s
}
func (this *TwoOneofs_Field34) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field34{` +
`Field34:` + fmt.Sprintf("%#v", this.Field34) + `}`}, ", ")
return s
}
func (this *TwoOneofs_Field35) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_Field35{` +
`Field35:` + fmt.Sprintf("%#v", this.Field35) + `}`}, ", ")
return s
}
func (this *TwoOneofs_SubMessage2) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.TwoOneofs_SubMessage2{` +
`SubMessage2:` + fmt.Sprintf("%#v", this.SubMessage2) + `}`}, ", ")
return s
}
func (this *CustomOneof) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 8)
s = append(s, "&one.CustomOneof{")
if this.Custom != nil {
s = append(s, "Custom: "+fmt.Sprintf("%#v", this.Custom)+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *CustomOneof_Stringy) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.CustomOneof_Stringy{` +
`Stringy:` + fmt.Sprintf("%#v", this.Stringy) + `}`}, ", ")
return s
}
func (this *CustomOneof_CustomType) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.CustomOneof_CustomType{` +
`CustomType:` + fmt.Sprintf("%#v", this.CustomType) + `}`}, ", ")
return s
}
func (this *CustomOneof_CastType) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.CustomOneof_CastType{` +
`CastType:` + fmt.Sprintf("%#v", this.CastType) + `}`}, ", ")
return s
}
func (this *CustomOneof_MyCustomName) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.CustomOneof_MyCustomName{` +
`MyCustomName:` + fmt.Sprintf("%#v", this.MyCustomName) + `}`}, ", ")
return s
}
func valueToGoStringOne(v interface{}, typ string) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
}
func NewPopulatedSubby(r randyOne, easy bool) *Subby {
this := &Subby{}
if r.Intn(10) != 0 {
v1 := string(randStringOne(r))
this.Sub = &v1
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedOne(r, 2)
}
return this
}
func NewPopulatedAllTypesOneOf(r randyOne, easy bool) *AllTypesOneOf {
this := &AllTypesOneOf{}
oneofNumber_TestOneof := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}[r.Intn(16)]
switch oneofNumber_TestOneof {
case 1:
this.TestOneof = NewPopulatedAllTypesOneOf_Field1(r, easy)
case 2:
this.TestOneof = NewPopulatedAllTypesOneOf_Field2(r, easy)
case 3:
this.TestOneof = NewPopulatedAllTypesOneOf_Field3(r, easy)
case 4:
this.TestOneof = NewPopulatedAllTypesOneOf_Field4(r, easy)
case 5:
this.TestOneof = NewPopulatedAllTypesOneOf_Field5(r, easy)
case 6:
this.TestOneof = NewPopulatedAllTypesOneOf_Field6(r, easy)
case 7:
this.TestOneof = NewPopulatedAllTypesOneOf_Field7(r, easy)
case 8:
this.TestOneof = NewPopulatedAllTypesOneOf_Field8(r, easy)
case 9:
this.TestOneof = NewPopulatedAllTypesOneOf_Field9(r, easy)
case 10:
this.TestOneof = NewPopulatedAllTypesOneOf_Field10(r, easy)
case 11:
this.TestOneof = NewPopulatedAllTypesOneOf_Field11(r, easy)
case 12:
this.TestOneof = NewPopulatedAllTypesOneOf_Field12(r, easy)
case 13:
this.TestOneof = NewPopulatedAllTypesOneOf_Field13(r, easy)
case 14:
this.TestOneof = NewPopulatedAllTypesOneOf_Field14(r, easy)
case 15:
this.TestOneof = NewPopulatedAllTypesOneOf_Field15(r, easy)
case 16:
this.TestOneof = NewPopulatedAllTypesOneOf_SubMessage(r, easy)
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedOne(r, 17)
}
return this
}
func NewPopulatedAllTypesOneOf_Field1(r randyOne, easy bool) *AllTypesOneOf_Field1 {
this := &AllTypesOneOf_Field1{}
this.Field1 = float64(r.Float64())
if r.Intn(2) == 0 {
this.Field1 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field2(r randyOne, easy bool) *AllTypesOneOf_Field2 {
this := &AllTypesOneOf_Field2{}
this.Field2 = float32(r.Float32())
if r.Intn(2) == 0 {
this.Field2 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field3(r randyOne, easy bool) *AllTypesOneOf_Field3 {
this := &AllTypesOneOf_Field3{}
this.Field3 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field3 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field4(r randyOne, easy bool) *AllTypesOneOf_Field4 {
this := &AllTypesOneOf_Field4{}
this.Field4 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field4 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field5(r randyOne, easy bool) *AllTypesOneOf_Field5 {
this := &AllTypesOneOf_Field5{}
this.Field5 = uint32(r.Uint32())
return this
}
func NewPopulatedAllTypesOneOf_Field6(r randyOne, easy bool) *AllTypesOneOf_Field6 {
this := &AllTypesOneOf_Field6{}
this.Field6 = uint64(uint64(r.Uint32()))
return this
}
func NewPopulatedAllTypesOneOf_Field7(r randyOne, easy bool) *AllTypesOneOf_Field7 {
this := &AllTypesOneOf_Field7{}
this.Field7 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field7 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field8(r randyOne, easy bool) *AllTypesOneOf_Field8 {
this := &AllTypesOneOf_Field8{}
this.Field8 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field8 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field9(r randyOne, easy bool) *AllTypesOneOf_Field9 {
this := &AllTypesOneOf_Field9{}
this.Field9 = uint32(r.Uint32())
return this
}
func NewPopulatedAllTypesOneOf_Field10(r randyOne, easy bool) *AllTypesOneOf_Field10 {
this := &AllTypesOneOf_Field10{}
this.Field10 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field10 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field11(r randyOne, easy bool) *AllTypesOneOf_Field11 {
this := &AllTypesOneOf_Field11{}
this.Field11 = uint64(uint64(r.Uint32()))
return this
}
func NewPopulatedAllTypesOneOf_Field12(r randyOne, easy bool) *AllTypesOneOf_Field12 {
this := &AllTypesOneOf_Field12{}
this.Field12 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field12 *= -1
}
return this
}
func NewPopulatedAllTypesOneOf_Field13(r randyOne, easy bool) *AllTypesOneOf_Field13 {
this := &AllTypesOneOf_Field13{}
this.Field13 = bool(bool(r.Intn(2) == 0))
return this
}
func NewPopulatedAllTypesOneOf_Field14(r randyOne, easy bool) *AllTypesOneOf_Field14 {
this := &AllTypesOneOf_Field14{}
this.Field14 = string(randStringOne(r))
return this
}
func NewPopulatedAllTypesOneOf_Field15(r randyOne, easy bool) *AllTypesOneOf_Field15 {
this := &AllTypesOneOf_Field15{}
v2 := r.Intn(100)
this.Field15 = make([]byte, v2)
for i := 0; i < v2; i++ {
this.Field15[i] = byte(r.Intn(256))
}
return this
}
func NewPopulatedAllTypesOneOf_SubMessage(r randyOne, easy bool) *AllTypesOneOf_SubMessage {
this := &AllTypesOneOf_SubMessage{}
this.SubMessage = NewPopulatedSubby(r, easy)
return this
}
func NewPopulatedTwoOneofs(r randyOne, easy bool) *TwoOneofs {
this := &TwoOneofs{}
oneofNumber_One := []int32{1, 2, 3}[r.Intn(3)]
switch oneofNumber_One {
case 1:
this.One = NewPopulatedTwoOneofs_Field1(r, easy)
case 2:
this.One = NewPopulatedTwoOneofs_Field2(r, easy)
case 3:
this.One = NewPopulatedTwoOneofs_Field3(r, easy)
}
oneofNumber_Two := []int32{34, 35, 36}[r.Intn(3)]
switch oneofNumber_Two {
case 34:
this.Two = NewPopulatedTwoOneofs_Field34(r, easy)
case 35:
this.Two = NewPopulatedTwoOneofs_Field35(r, easy)
case 36:
this.Two = NewPopulatedTwoOneofs_SubMessage2(r, easy)
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedOne(r, 37)
}
return this
}
func NewPopulatedTwoOneofs_Field1(r randyOne, easy bool) *TwoOneofs_Field1 {
this := &TwoOneofs_Field1{}
this.Field1 = float64(r.Float64())
if r.Intn(2) == 0 {
this.Field1 *= -1
}
return this
}
func NewPopulatedTwoOneofs_Field2(r randyOne, easy bool) *TwoOneofs_Field2 {
this := &TwoOneofs_Field2{}
this.Field2 = float32(r.Float32())
if r.Intn(2) == 0 {
this.Field2 *= -1
}
return this
}
func NewPopulatedTwoOneofs_Field3(r randyOne, easy bool) *TwoOneofs_Field3 {
this := &TwoOneofs_Field3{}
this.Field3 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field3 *= -1
}
return this
}
func NewPopulatedTwoOneofs_Field34(r randyOne, easy bool) *TwoOneofs_Field34 {
this := &TwoOneofs_Field34{}
this.Field34 = string(randStringOne(r))
return this
}
func NewPopulatedTwoOneofs_Field35(r randyOne, easy bool) *TwoOneofs_Field35 {
this := &TwoOneofs_Field35{}
v3 := r.Intn(100)
this.Field35 = make([]byte, v3)
for i := 0; i < v3; i++ {
this.Field35[i] = byte(r.Intn(256))
}
return this
}
func NewPopulatedTwoOneofs_SubMessage2(r randyOne, easy bool) *TwoOneofs_SubMessage2 {
this := &TwoOneofs_SubMessage2{}
this.SubMessage2 = NewPopulatedSubby(r, easy)
return this
}
func NewPopulatedCustomOneof(r randyOne, easy bool) *CustomOneof {
this := &CustomOneof{}
oneofNumber_Custom := []int32{34, 35, 36, 37}[r.Intn(4)]
switch oneofNumber_Custom {
case 34:
this.Custom = NewPopulatedCustomOneof_Stringy(r, easy)
case 35:
this.Custom = NewPopulatedCustomOneof_CustomType(r, easy)
case 36:
this.Custom = NewPopulatedCustomOneof_CastType(r, easy)
case 37:
this.Custom = NewPopulatedCustomOneof_MyCustomName(r, easy)
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedOne(r, 38)
}
return this
}
func NewPopulatedCustomOneof_Stringy(r randyOne, easy bool) *CustomOneof_Stringy {
this := &CustomOneof_Stringy{}
this.Stringy = string(randStringOne(r))
return this
}
func NewPopulatedCustomOneof_CustomType(r randyOne, easy bool) *CustomOneof_CustomType {
this := &CustomOneof_CustomType{}
v4 := github_com_gogo_protobuf_test_custom.NewPopulatedUint128(r)
this.CustomType = *v4
return this
}
func NewPopulatedCustomOneof_CastType(r randyOne, easy bool) *CustomOneof_CastType {
this := &CustomOneof_CastType{}
this.CastType = github_com_gogo_protobuf_test_casttype.MyUint64Type(uint64(r.Uint32()))
return this
}
func NewPopulatedCustomOneof_MyCustomName(r randyOne, easy bool) *CustomOneof_MyCustomName {
this := &CustomOneof_MyCustomName{}
this.MyCustomName = int64(r.Int63())
if r.Intn(2) == 0 {
this.MyCustomName *= -1
}
return this
}
type randyOne interface {
Float32() float32
Float64() float64
Int63() int64
Int31() int32
Uint32() uint32
Intn(n int) int
}
func randUTF8RuneOne(r randyOne) rune {
ru := r.Intn(62)
if ru < 10 {
return rune(ru + 48)
} else if ru < 36 {
return rune(ru + 55)
}
return rune(ru + 61)
}
func randStringOne(r randyOne) string {
v5 := r.Intn(100)
tmps := make([]rune, v5)
for i := 0; i < v5; i++ {
tmps[i] = randUTF8RuneOne(r)
}
return string(tmps)
}
func randUnrecognizedOne(r randyOne, maxFieldNumber int) (dAtA []byte) {
l := r.Intn(5)
for i := 0; i < l; i++ {
wire := r.Intn(4)
if wire == 3 {
wire = 5
}
fieldNumber := maxFieldNumber + r.Intn(100)
dAtA = randFieldOne(dAtA, r, fieldNumber, wire)
}
return dAtA
}
func randFieldOne(dAtA []byte, r randyOne, fieldNumber int, wire int) []byte {
key := uint32(fieldNumber)<<3 | uint32(wire)
switch wire {
case 0:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
v6 := r.Int63()
if r.Intn(2) == 0 {
v6 *= -1
}
dAtA = encodeVarintPopulateOne(dAtA, uint64(v6))
case 1:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
case 2:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
ll := r.Intn(100)
dAtA = encodeVarintPopulateOne(dAtA, uint64(ll))
for j := 0; j < ll; j++ {
dAtA = append(dAtA, byte(r.Intn(256)))
}
default:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
}
return dAtA
}
func encodeVarintPopulateOne(dAtA []byte, v uint64) []byte {
for v >= 1<<7 {
dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
v >>= 7
}
dAtA = append(dAtA, uint8(v))
return dAtA
}
func (m *Subby) Size() (n int) {
var l int
_ = l
if m.Sub != nil {
l = len(*m.Sub)
n += 1 + l + sovOne(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *AllTypesOneOf) Size() (n int) {
var l int
_ = l
if m.TestOneof != nil {
n += m.TestOneof.Size()
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *AllTypesOneOf_Field1) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *AllTypesOneOf_Field2) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *AllTypesOneOf_Field3) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field3))
return n
}
func (m *AllTypesOneOf_Field4) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field4))
return n
}
func (m *AllTypesOneOf_Field5) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field5))
return n
}
func (m *AllTypesOneOf_Field6) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field6))
return n
}
func (m *AllTypesOneOf_Field7) Size() (n int) {
var l int
_ = l
n += 1 + sozOne(uint64(m.Field7))
return n
}
func (m *AllTypesOneOf_Field8) Size() (n int) {
var l int
_ = l
n += 1 + sozOne(uint64(m.Field8))
return n
}
func (m *AllTypesOneOf_Field9) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *AllTypesOneOf_Field10) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *AllTypesOneOf_Field11) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *AllTypesOneOf_Field12) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *AllTypesOneOf_Field13) Size() (n int) {
var l int
_ = l
n += 2
return n
}
func (m *AllTypesOneOf_Field14) Size() (n int) {
var l int
_ = l
l = len(m.Field14)
n += 1 + l + sovOne(uint64(l))
return n
}
func (m *AllTypesOneOf_Field15) Size() (n int) {
var l int
_ = l
if m.Field15 != nil {
l = len(m.Field15)
n += 1 + l + sovOne(uint64(l))
}
return n
}
func (m *AllTypesOneOf_SubMessage) Size() (n int) {
var l int
_ = l
if m.SubMessage != nil {
l = m.SubMessage.Size()
n += 2 + l + sovOne(uint64(l))
}
return n
}
func (m *TwoOneofs) Size() (n int) {
var l int
_ = l
if m.One != nil {
n += m.One.Size()
}
if m.Two != nil {
n += m.Two.Size()
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *TwoOneofs_Field1) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *TwoOneofs_Field2) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *TwoOneofs_Field3) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field3))
return n
}
func (m *TwoOneofs_Field34) Size() (n int) {
var l int
_ = l
l = len(m.Field34)
n += 2 + l + sovOne(uint64(l))
return n
}
func (m *TwoOneofs_Field35) Size() (n int) {
var l int
_ = l
if m.Field35 != nil {
l = len(m.Field35)
n += 2 + l + sovOne(uint64(l))
}
return n
}
func (m *TwoOneofs_SubMessage2) Size() (n int) {
var l int
_ = l
if m.SubMessage2 != nil {
l = m.SubMessage2.Size()
n += 2 + l + sovOne(uint64(l))
}
return n
}
func (m *CustomOneof) Size() (n int) {
var l int
_ = l
if m.Custom != nil {
n += m.Custom.Size()
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *CustomOneof_Stringy) Size() (n int) {
var l int
_ = l
l = len(m.Stringy)
n += 2 + l + sovOne(uint64(l))
return n
}
func (m *CustomOneof_CustomType) Size() (n int) {
var l int
_ = l
l = m.CustomType.Size()
n += 2 + l + sovOne(uint64(l))
return n
}
func (m *CustomOneof_CastType) Size() (n int) {
var l int
_ = l
n += 2 + sovOne(uint64(m.CastType))
return n
}
func (m *CustomOneof_MyCustomName) Size() (n int) {
var l int
_ = l
n += 2 + sovOne(uint64(m.MyCustomName))
return n
}
func sovOne(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozOne(x uint64) (n int) {
return sovOne(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *Subby) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&Subby{`,
`Sub:` + valueToStringOne(this.Sub) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf{`,
`TestOneof:` + fmt.Sprintf("%v", this.TestOneof) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field1) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field1{`,
`Field1:` + fmt.Sprintf("%v", this.Field1) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field2) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field2{`,
`Field2:` + fmt.Sprintf("%v", this.Field2) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field3) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field3{`,
`Field3:` + fmt.Sprintf("%v", this.Field3) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field4) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field4{`,
`Field4:` + fmt.Sprintf("%v", this.Field4) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field5) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field5{`,
`Field5:` + fmt.Sprintf("%v", this.Field5) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field6) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field6{`,
`Field6:` + fmt.Sprintf("%v", this.Field6) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field7) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field7{`,
`Field7:` + fmt.Sprintf("%v", this.Field7) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field8) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field8{`,
`Field8:` + fmt.Sprintf("%v", this.Field8) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field9) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field9{`,
`Field9:` + fmt.Sprintf("%v", this.Field9) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field10) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field10{`,
`Field10:` + fmt.Sprintf("%v", this.Field10) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field11) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field11{`,
`Field11:` + fmt.Sprintf("%v", this.Field11) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field12) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field12{`,
`Field12:` + fmt.Sprintf("%v", this.Field12) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field13) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field13{`,
`Field13:` + fmt.Sprintf("%v", this.Field13) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field14) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field14{`,
`Field14:` + fmt.Sprintf("%v", this.Field14) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_Field15) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_Field15{`,
`Field15:` + fmt.Sprintf("%v", this.Field15) + `,`,
`}`,
}, "")
return s
}
func (this *AllTypesOneOf_SubMessage) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&AllTypesOneOf_SubMessage{`,
`SubMessage:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage), "Subby", "Subby", 1) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs{`,
`One:` + fmt.Sprintf("%v", this.One) + `,`,
`Two:` + fmt.Sprintf("%v", this.Two) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field1) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field1{`,
`Field1:` + fmt.Sprintf("%v", this.Field1) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field2) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field2{`,
`Field2:` + fmt.Sprintf("%v", this.Field2) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field3) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field3{`,
`Field3:` + fmt.Sprintf("%v", this.Field3) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field34) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field34{`,
`Field34:` + fmt.Sprintf("%v", this.Field34) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_Field35) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_Field35{`,
`Field35:` + fmt.Sprintf("%v", this.Field35) + `,`,
`}`,
}, "")
return s
}
func (this *TwoOneofs_SubMessage2) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&TwoOneofs_SubMessage2{`,
`SubMessage2:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage2), "Subby", "Subby", 1) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof{`,
`Custom:` + fmt.Sprintf("%v", this.Custom) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof_Stringy) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof_Stringy{`,
`Stringy:` + fmt.Sprintf("%v", this.Stringy) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof_CustomType) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof_CustomType{`,
`CustomType:` + fmt.Sprintf("%v", this.CustomType) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof_CastType) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof_CastType{`,
`CastType:` + fmt.Sprintf("%v", this.CastType) + `,`,
`}`,
}, "")
return s
}
func (this *CustomOneof_MyCustomName) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&CustomOneof_MyCustomName{`,
`MyCustomName:` + fmt.Sprintf("%v", this.MyCustomName) + `,`,
`}`,
}, "")
return s
}
func valueToStringOne(v interface{}) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func init() { proto.RegisterFile("combos/neither/one.proto", fileDescriptorOne) }
var fileDescriptorOne = []byte{
// 598 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0xd3, 0xbf, 0x4f, 0x1b, 0x3f,
0x14, 0x00, 0x70, 0x3f, 0x42, 0x42, 0x70, 0xc2, 0x97, 0x7c, 0x6f, 0x72, 0x19, 0x8c, 0x95, 0xb6,
0x92, 0x87, 0x92, 0x90, 0x4b, 0xc2, 0x8f, 0xb1, 0x47, 0x55, 0x65, 0xa1, 0x48, 0x07, 0xcc, 0x28,
0x47, 0x4d, 0x88, 0x44, 0xce, 0x08, 0xfb, 0x84, 0xb2, 0xf1, 0x37, 0xf4, 0xaf, 0xe8, 0xd8, 0xb1,
0x7f, 0x02, 0x23, 0x63, 0xd5, 0x21, 0xe2, 0xae, 0x4b, 0x47, 0x46, 0xd4, 0xa9, 0xf2, 0x1d, 0xb1,
0x2b, 0x55, 0x55, 0x97, 0x4e, 0xb9, 0xf7, 0x3e, 0xe7, 0x97, 0xf7, 0xce, 0x36, 0x26, 0xa7, 0x72,
0x12, 0x49, 0xd5, 0x8e, 0xc5, 0x58, 0x9f, 0x8b, 0xab, 0xb6, 0x8c, 0x45, 0xeb, 0xf2, 0x4a, 0x6a,
0xe9, 0x95, 0x64, 0x2c, 0xd6, 0x36, 0x46, 0x63, 0x7d, 0x9e, 0x44, 0xad, 0x53, 0x39, 0x69, 0x8f,
0xe4, 0x48, 0xb6, 0x73, 0x8b, 0x92, 0xb3, 0x3c, 0xca, 0x83, 0xfc, 0xa9, 0x58, 0xd3, 0x7c, 0x86,
0xcb, 0x87, 0x49, 0x14, 0x4d, 0xbd, 0x06, 0x2e, 0xa9, 0x24, 0x22, 0xc0, 0x80, 0x2f, 0x87, 0xe6,
0xb1, 0x39, 0x2b, 0xe1, 0x95, 0xd7, 0x17, 0x17, 0x47, 0xd3, 0x4b, 0xa1, 0x0e, 0x62, 0x71, 0x70,
0xe6, 0x11, 0x5c, 0x79, 0x3b, 0x16, 0x17, 0xef, 0x3b, 0xf9, 0x6b, 0x30, 0x40, 0xe1, 0x53, 0x6c,
0xc5, 0x27, 0x0b, 0x0c, 0xf8, 0x82, 0x15, 0xdf, 0x4a, 0x97, 0x94, 0x18, 0xf0, 0xb2, 0x95, 0xae,
0x95, 0x1e, 0x59, 0x64, 0xc0, 0x4b, 0x56, 0x7a, 0x56, 0xfa, 0xa4, 0xcc, 0x80, 0xaf, 0x58, 0xe9,
0x5b, 0xd9, 0x22, 0x15, 0x06, 0x7c, 0xd1, 0xca, 0x96, 0x95, 0x6d, 0xb2, 0xc4, 0x80, 0xff, 0x6f,
0x65, 0xdb, 0xca, 0x0e, 0xa9, 0x32, 0xe0, 0x9e, 0x95, 0x1d, 0x2b, 0xbb, 0x64, 0x99, 0x01, 0x5f,
0xb2, 0xb2, 0xeb, 0xad, 0xe1, 0xa5, 0x62, 0xb2, 0x4d, 0x82, 0x19, 0xf0, 0xd5, 0x01, 0x0a, 0xe7,
0x09, 0x67, 0x1d, 0x52, 0x63, 0xc0, 0x2b, 0xce, 0x3a, 0xce, 0x7c, 0x52, 0x67, 0xc0, 0x1b, 0xce,
0x7c, 0x67, 0x5d, 0xb2, 0xc2, 0x80, 0x57, 0x9d, 0x75, 0x9d, 0xf5, 0xc8, 0x7f, 0x66, 0x07, 0x9c,
0xf5, 0x9c, 0xf5, 0xc9, 0x2a, 0x03, 0x5e, 0x77, 0xd6, 0xf7, 0x36, 0x70, 0x4d, 0x25, 0xd1, 0xc9,
0x44, 0x28, 0x35, 0x1c, 0x09, 0xd2, 0x60, 0xc0, 0x6b, 0x3e, 0x6e, 0x99, 0x33, 0x91, 0x6f, 0xeb,
0x00, 0x85, 0x58, 0x25, 0xd1, 0x7e, 0xe1, 0x41, 0x1d, 0x63, 0x2d, 0x94, 0x3e, 0x91, 0xb1, 0x90,
0x67, 0xcd, 0x3b, 0xc0, 0xcb, 0x47, 0xd7, 0xf2, 0xc0, 0x04, 0xea, 0x1f, 0x6f, 0xee, 0xbc, 0xe9,
0x6e, 0x8f, 0x34, 0xf3, 0x81, 0x20, 0x9c, 0x27, 0x9c, 0xf5, 0xc9, 0xf3, 0x7c, 0x20, 0x6b, 0x7d,
0xaf, 0x8d, 0xeb, 0xbf, 0x0c, 0xe4, 0x93, 0x17, 0xbf, 0x4d, 0x04, 0x61, 0xcd, 0x4d, 0xe4, 0x07,
0x65, 0x6c, 0x8e, 0xbd, 0xf9, 0xd1, 0xd7, 0xb2, 0xf9, 0x61, 0x01, 0xd7, 0xf6, 0x12, 0xa5, 0xe5,
0x24, 0x9f, 0xca, 0xfc, 0xd5, 0xa1, 0xbe, 0x1a, 0xc7, 0xa3, 0xe9, 0x53, 0x1b, 0x28, 0x9c, 0x27,
0xbc, 0x10, 0xe3, 0xe2, 0x55, 0x73, 0xc2, 0x8b, 0x4e, 0x82, 0xcd, 0xaf, 0xb3, 0xf5, 0x57, 0x7f,
0xbc, 0x41, 0xe6, 0xdb, 0xb5, 0x4f, 0xf3, 0x35, 0xad, 0xe3, 0x71, 0xac, 0x3b, 0xfe, 0x8e, 0xf9,
0xc0, 0xae, 0x8a, 0x77, 0x8c, 0xab, 0x7b, 0x43, 0xa5, 0xf3, 0x8a, 0xa6, 0xf5, 0xc5, 0x60, 0xfb,
0xc7, 0x6c, 0xbd, 0xfb, 0x97, 0x8a, 0x43, 0xa5, 0xf5, 0xf4, 0x52, 0xb4, 0xf6, 0xa7, 0xa6, 0xea,
0x56, 0xcf, 0x2c, 0x1f, 0xa0, 0xd0, 0x96, 0xf2, 0xfc, 0x79, 0xab, 0xef, 0x86, 0x13, 0x41, 0x5e,
0x9a, 0xeb, 0x12, 0x34, 0xb2, 0xd9, 0x7a, 0x7d, 0x7f, 0xea, 0xf2, 0xae, 0x15, 0x13, 0x05, 0x55,
0x5c, 0x29, 0x5a, 0x0d, 0xde, 0xdc, 0xa6, 0x14, 0xdd, 0xa5, 0x14, 0x7d, 0x49, 0x29, 0xba, 0x4f,
0x29, 0x3c, 0xa4, 0x14, 0x1e, 0x53, 0x0a, 0x37, 0x19, 0x85, 0x8f, 0x19, 0x85, 0x4f, 0x19, 0x85,
0xcf, 0x19, 0x85, 0xdb, 0x8c, 0xa2, 0xbb, 0x8c, 0xa2, 0xfb, 0x8c, 0xc2, 0xf7, 0x8c, 0xa2, 0x87,
0x8c, 0xc2, 0x63, 0x46, 0xd1, 0xcd, 0x37, 0x8a, 0x7e, 0x06, 0x00, 0x00, 0xff, 0xff, 0x0e, 0x27,
0x4d, 0xb9, 0x78, 0x04, 0x00, 0x00,
}
| {
return nil
} |
doc_reference_md_0090.rs | fn main() {
let dish = ("Ham", "Eggs");
// this body will be skipped because the pattern is refuted
if let ("Bacon", b) = dish {
println!("Bacon is served with {}", b);
}
// this body will execute
if let ("Ham", b) = dish {
println!("Ham is served with {}", b); | }
} |
|
pipelinerun.go | /*
Copyright 2019 The Tekton 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.
*/
package pipelinerun
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/tektoncd/pipeline/pkg/apis/config"
apisconfig "github.com/tektoncd/pipeline/pkg/apis/config"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
"github.com/tektoncd/pipeline/pkg/artifacts"
clientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned"
pipelinerunreconciler "github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1beta1/pipelinerun"
listersv1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1"
listers "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1beta1"
resourcelisters "github.com/tektoncd/pipeline/pkg/client/resource/listers/resource/v1alpha1"
"github.com/tektoncd/pipeline/pkg/contexts"
"github.com/tektoncd/pipeline/pkg/pipelinerunmetrics"
tknreconciler "github.com/tektoncd/pipeline/pkg/reconciler"
"github.com/tektoncd/pipeline/pkg/reconciler/events"
"github.com/tektoncd/pipeline/pkg/reconciler/events/cloudevent"
"github.com/tektoncd/pipeline/pkg/reconciler/pipeline/dag"
"github.com/tektoncd/pipeline/pkg/reconciler/pipelinerun/resources"
"github.com/tektoncd/pipeline/pkg/reconciler/taskrun"
tresources "github.com/tektoncd/pipeline/pkg/reconciler/taskrun/resources"
"github.com/tektoncd/pipeline/pkg/reconciler/volumeclaim"
"github.com/tektoncd/pipeline/pkg/workspace"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8slabels "k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
"knative.dev/pkg/apis"
"knative.dev/pkg/controller"
"knative.dev/pkg/kmeta"
"knative.dev/pkg/logging"
pkgreconciler "knative.dev/pkg/reconciler"
)
const (
// ReasonCouldntGetPipeline indicates that the reason for the failure status is that the
// associated Pipeline couldn't be retrieved
ReasonCouldntGetPipeline = "CouldntGetPipeline"
// ReasonInvalidBindings indicates that the reason for the failure status is that the
// PipelineResources bound in the PipelineRun didn't match those declared in the Pipeline
ReasonInvalidBindings = "InvalidPipelineResourceBindings"
// ReasonInvalidWorkspaceBinding indicates that a Pipeline expects a workspace but a
// PipelineRun has provided an invalid binding.
ReasonInvalidWorkspaceBinding = "InvalidWorkspaceBindings"
// ReasonInvalidServiceAccountMapping indicates that PipelineRun.Spec.ServiceAccountNames defined with a wrong taskName
ReasonInvalidServiceAccountMapping = "InvalidServiceAccountMappings"
// ReasonParameterTypeMismatch indicates that the reason for the failure status is that
// parameter(s) declared in the PipelineRun do not have the some declared type as the
// parameters(s) declared in the Pipeline that they are supposed to override.
ReasonParameterTypeMismatch = "ParameterTypeMismatch"
// ReasonCouldntGetTask indicates that the reason for the failure status is that the
// associated Pipeline's Tasks couldn't all be retrieved
ReasonCouldntGetTask = "CouldntGetTask"
// ReasonCouldntGetResource indicates that the reason for the failure status is that the
// associated PipelineRun's bound PipelineResources couldn't all be retrieved
ReasonCouldntGetResource = "CouldntGetResource"
// ReasonCouldntGetCondition indicates that the reason for the failure status is that the
// associated Pipeline's Conditions couldn't all be retrieved
ReasonCouldntGetCondition = "CouldntGetCondition"
// ReasonParameterMissing indicates that the reason for the failure status is that the
// associated PipelineRun didn't provide all the required parameters
ReasonParameterMissing = "ParameterMissing"
// ReasonFailedValidation indicates that the reason for failure status is
// that pipelinerun failed runtime validation
ReasonFailedValidation = "PipelineValidationFailed"
// ReasonInvalidGraph indicates that the reason for the failure status is that the
// associated Pipeline is an invalid graph (a.k.a wrong order, cycle, …)
ReasonInvalidGraph = "PipelineInvalidGraph"
// ReasonCancelled indicates that a PipelineRun was cancelled.
ReasonCancelled = pipelinerunmetrics.ReasonCancelled
// Deprecated: "PipelineRunCancelled" indicates that a PipelineRun was cancelled.
ReasonCancelledDeprecated = pipelinerunmetrics.ReasonCancelledDeprecated
// ReasonPending indicates that a PipelineRun is pending.
ReasonPending = "PipelineRunPending"
// ReasonCouldntCancel indicates that a PipelineRun was cancelled but attempting to update
// all of the running TaskRuns as cancelled failed.
ReasonCouldntCancel = "PipelineRunCouldntCancel"
// ReasonInvalidTaskResultReference indicates a task result was declared
// but was not initialized by that task
ReasonInvalidTaskResultReference = "InvalidTaskResultReference"
// ReasonRequiredWorkspaceMarkedOptional indicates an optional workspace
// has been passed to a Task that is expecting a non-optional workspace
ReasonRequiredWorkspaceMarkedOptional = "RequiredWorkspaceMarkedOptional"
)
// Reconciler implements controller.Reconciler for Configuration resources.
type Reconciler struct {
KubeClientSet kubernetes.Interface
PipelineClientSet clientset.Interface
Images pipeline.Images
// listers index properties about resources
pipelineRunLister listers.PipelineRunLister
pipelineLister listers.PipelineLister
taskRunLister listers.TaskRunLister
runLister listersv1alpha1.RunLister
taskLister listers.TaskLister
clusterTaskLister listers.ClusterTaskLister
resourceLister resourcelisters.PipelineResourceLister
conditionLister listersv1alpha1.ConditionLister
cloudEventClient cloudevent.CEClient
metrics *pipelinerunmetrics.Recorder
pvcHandler volumeclaim.PvcHandler
// disableResolution is a flag to the reconciler that it should
// not be performing resolution of pipelineRefs.
// TODO(sbwsg): Once we've agreed on a way forward for TEP-0060
// this can be removed in favor of whatever that chosen solution
// is.
disableResolution bool
}
var (
// Check that our Reconciler implements pipelinerunreconciler.Interface
_ pipelinerunreconciler.Interface = (*Reconciler)(nil)
// Indicates pipelinerun resolution hasn't occurred yet.
errResourceNotResolved = fmt.Errorf("pipeline ref has not been resolved")
)
// ReconcileKind compares the actual state with the desired, and attempts to
// converge the two. It then updates the Status block of the Pipeline Run
// resource with the current status of the resource.
func (c *Reconciler) ReconcileKind(ctx context.Context, pr *v1beta1.PipelineRun) pkgreconciler.Event {
logger := logging.FromContext(ctx)
ctx = cloudevent.ToContext(ctx, c.cloudEventClient)
// Read the initial condition
before := pr.Status.GetCondition(apis.ConditionSucceeded)
if !pr.HasStarted() && !pr.IsPending() {
pr.Status.InitializeConditions()
// In case node time was not synchronized, when controller has been scheduled to other nodes.
if pr.Status.StartTime.Sub(pr.CreationTimestamp.Time) < 0 {
logger.Warnf("PipelineRun %s createTimestamp %s is after the pipelineRun started %s", pr.GetNamespacedName().String(), pr.CreationTimestamp, pr.Status.StartTime)
pr.Status.StartTime = &pr.CreationTimestamp
}
// Emit events. During the first reconcile the status of the PipelineRun may change twice
// from not Started to Started and then to Running, so we need to sent the event here
// and at the end of 'Reconcile' again.
// We also want to send the "Started" event as soon as possible for anyone who may be waiting
// on the event to perform user facing initialisations, such has reset a CI check status
afterCondition := pr.Status.GetCondition(apis.ConditionSucceeded)
events.Emit(ctx, nil, afterCondition, pr)
// We already sent an event for start, so update `before` with the current status
before = pr.Status.GetCondition(apis.ConditionSucceeded)
}
getPipelineFunc, err := resources.GetPipelineFunc(ctx, c.KubeClientSet, c.PipelineClientSet, pr)
if err != nil {
logger.Errorf("Failed to fetch pipeline func for pipeline %s: %w", pr.Spec.PipelineRef.Name, err)
pr.Status.MarkFailed(ReasonCouldntGetPipeline, "Error retrieving pipeline for pipelinerun %s/%s: %s",
pr.Namespace, pr.Name, err)
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, nil)
}
if pr.IsDone() {
// We may be reading a version of the object that was stored at an older version
// and may not have had all of the assumed default specified.
pr.SetDefaults(contexts.WithUpgradeViaDefaulting(ctx))
if err := artifacts.CleanupArtifactStorage(ctx, pr, c.KubeClientSet); err != nil {
logger.Errorf("Failed to delete PVC for PipelineRun %s: %v", pr.Name, err)
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err)
}
if err := c.cleanupAffinityAssistants(ctx, pr); err != nil {
logger.Errorf("Failed to delete StatefulSet for PipelineRun %s: %v", pr.Name, err)
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err)
}
if err := c.updateTaskRunsStatusDirectly(pr); err != nil {
logger.Errorf("Failed to update TaskRun status for PipelineRun %s: %v", pr.Name, err)
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err)
}
if err := c.updateRunsStatusDirectly(pr); err != nil {
logger.Errorf("Failed to update Run status for PipelineRun %s: %v", pr.Name, err)
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err)
}
go func(metrics *pipelinerunmetrics.Recorder) {
err := metrics.DurationAndCount(pr)
if err != nil {
logger.Warnf("Failed to log the metrics : %v", err)
}
}(c.metrics)
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, nil)
}
if err := propagatePipelineNameLabelToPipelineRun(pr); err != nil {
logger.Errorf("Failed to propagate pipeline name label to pipelinerun %s: %v", pr.Name, err)
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err)
}
// If the pipelinerun is cancelled, cancel tasks and update status
if pr.IsCancelled() {
err := cancelPipelineRun(ctx, logger, pr, c.PipelineClientSet)
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err)
}
// Make sure that the PipelineRun status is in sync with the actual TaskRuns
err = c.updatePipelineRunStatusFromInformer(ctx, pr)
if err != nil {
// This should not fail. Return the error so we can re-try later.
logger.Errorf("Error while syncing the pipelinerun status: %v", err.Error())
return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err)
}
// Reconcile this copy of the pipelinerun and then write back any status or label
// updates regardless of whether the reconciliation errored out.
if err = c.reconcile(ctx, pr, getPipelineFunc); err != nil {
logger.Errorf("Reconcile error: %v", err.Error())
}
if c.disableResolution && err == errResourceNotResolved {
// This is not an error: an out-of-band process can
// still resolve the PipelineRun, at which point
// reconciliation can continue as normal.
err = nil
}
if err = c.finishReconcileUpdateEmitEvents(ctx, pr, before, err); err != nil {
return err
}
if pr.Status.StartTime != nil {
// Compute the time since the task started.
elapsed := time.Since(pr.Status.StartTime.Time)
// Snooze this resource until the timeout has elapsed.
return controller.NewRequeueAfter(pr.GetTimeout(ctx) - elapsed)
}
return nil
}
func (c *Reconciler) finishReconcileUpdateEmitEvents(ctx context.Context, pr *v1beta1.PipelineRun, beforeCondition *apis.Condition, previousError error) error {
logger := logging.FromContext(ctx)
afterCondition := pr.Status.GetCondition(apis.ConditionSucceeded)
events.Emit(ctx, beforeCondition, afterCondition, pr)
_, err := c.updateLabelsAndAnnotations(ctx, pr)
if err != nil {
logger.Warn("Failed to update PipelineRun labels/annotations", zap.Error(err))
events.EmitError(controller.GetEventRecorder(ctx), err, pr)
}
merr := multierror.Append(previousError, err).ErrorOrNil()
if controller.IsPermanentError(previousError) {
return controller.NewPermanentError(merr)
}
return merr
}
// resolvePipelineState will attempt to resolve each referenced task in the pipeline's spec and all of the resources
// specified by those tasks.
func (c *Reconciler) resolvePipelineState(
ctx context.Context,
tasks []v1beta1.PipelineTask,
pipelineMeta *metav1.ObjectMeta,
pr *v1beta1.PipelineRun,
providedResources map[string]*v1alpha1.PipelineResource) (resources.PipelineRunState, error) {
pst := resources.PipelineRunState{}
// Resolve each task individually because they each could have a different reference context (remote or local).
for _, task := range tasks {
fn, err := tresources.GetTaskFunc(ctx, c.KubeClientSet, c.PipelineClientSet, task.TaskRef, pr.Namespace, pr.Spec.ServiceAccountName)
if err != nil {
// This Run has failed, so we need to mark it as failed and stop reconciling it
pr.Status.MarkFailed(ReasonCouldntGetTask, "Pipeline %s/%s can't be Run; task %s could not be fetched: %s",
pipelineMeta.Namespace, pipelineMeta.Name, task.Name, err)
return nil, controller.NewPermanentError(err)
}
resolvedTask, err := resources.ResolvePipelineRunTask(ctx,
*pr,
fn,
func(name string) (*v1beta1.TaskRun, error) {
return c.taskRunLister.TaskRuns(pr.Namespace).Get(name)
},
func(name string) (*v1alpha1.Run, error) {
return c.runLister.Runs(pr.Namespace).Get(name)
},
func(name string) (*v1alpha1.Condition, error) {
return c.conditionLister.Conditions(pr.Namespace).Get(name)
},
task, providedResources,
)
if err != nil {
switch err := err.(type) {
case *resources.TaskNotFoundError:
pr.Status.MarkFailed(ReasonCouldntGetTask,
"Pipeline %s/%s can't be Run; it contains Tasks that don't exist: %s",
pipelineMeta.Namespace, pipelineMeta.Name, err)
case *resources.ConditionNotFoundError:
pr.Status.MarkFailed(ReasonCouldntGetCondition,
"PipelineRun %s/%s can't be Run; it contains Conditions that don't exist: %s",
pipelineMeta.Namespace, pr.Name, err)
default:
pr.Status.MarkFailed(ReasonFailedValidation,
"PipelineRun %s/%s can't be Run; couldn't resolve all references: %s",
pipelineMeta.Namespace, pr.Name, err)
}
return nil, controller.NewPermanentError(err)
}
pst = append(pst, resolvedTask)
}
return pst, nil
}
func (c *Reconciler) reconcile(ctx context.Context, pr *v1beta1.PipelineRun, getPipelineFunc resources.GetPipeline) error {
logger := logging.FromContext(ctx)
cfg := config.FromContextOrDefaults(ctx)
// We may be reading a version of the object that was stored at an older version
// and may not have had all of the assumed default specified.
pr.SetDefaults(contexts.WithUpgradeViaDefaulting(ctx))
// When pipeline run is pending, return to avoid creating the task
if pr.IsPending() {
pr.Status.SetCondition(&apis.Condition{
Type: apis.ConditionSucceeded,
Status: corev1.ConditionUnknown,
Reason: ReasonPending,
Message: fmt.Sprintf("PipelineRun %q is pending", pr.Name),
})
return nil
}
if c.disableResolution && pr.Status.PipelineSpec == nil {
return errResourceNotResolved
}
pipelineMeta, pipelineSpec, err := resources.GetPipelineData(ctx, pr, getPipelineFunc)
if err != nil {
logger.Errorf("Failed to determine Pipeline spec to use for pipelinerun %s: %v", pr.Name, err)
pr.Status.MarkFailed(ReasonCouldntGetPipeline,
"Error retrieving pipeline for pipelinerun %s/%s: %s",
pr.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
// Store the fetched PipelineSpec on the PipelineRun for auditing
if err := storePipelineSpec(ctx, pr, pipelineSpec); err != nil {
logger.Errorf("Failed to store PipelineSpec on PipelineRun.Status for pipelinerun %s: %v", pr.Name, err)
}
// Propagate labels from Pipeline to PipelineRun.
if pr.ObjectMeta.Labels == nil {
pr.ObjectMeta.Labels = make(map[string]string, len(pipelineMeta.Labels)+1)
}
for key, value := range pipelineMeta.Labels {
pr.ObjectMeta.Labels[key] = value
}
pr.ObjectMeta.Labels[pipeline.PipelineLabelKey] = pipelineMeta.Name
// Propagate annotations from Pipeline to PipelineRun.
if pr.ObjectMeta.Annotations == nil {
pr.ObjectMeta.Annotations = make(map[string]string, len(pipelineMeta.Annotations))
}
for key, value := range pipelineMeta.Annotations {
pr.ObjectMeta.Annotations[key] = value
}
d, err := dag.Build(v1beta1.PipelineTaskList(pipelineSpec.Tasks), v1beta1.PipelineTaskList(pipelineSpec.Tasks).Deps())
if err != nil {
// This Run has failed, so we need to mark it as failed and stop reconciling it
pr.Status.MarkFailed(ReasonInvalidGraph,
"PipelineRun %s/%s's Pipeline DAG is invalid: %s",
pr.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
// build DAG with a list of final tasks, this DAG is used later to identify
// if a task in PipelineRunState is final task or not
// the finally section is optional and might not exist
// dfinally holds an empty Graph in the absence of finally clause
dfinally, err := dag.Build(v1beta1.PipelineTaskList(pipelineSpec.Finally), map[string][]string{})
if err != nil {
// This Run has failed, so we need to mark it as failed and stop reconciling it
pr.Status.MarkFailed(ReasonInvalidGraph,
"PipelineRun %s's Pipeline DAG is invalid for finally clause: %s",
pr.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
if err := pipelineSpec.Validate(ctx); err != nil {
// This Run has failed, so we need to mark it as failed and stop reconciling it
pr.Status.MarkFailed(ReasonFailedValidation,
"Pipeline %s/%s can't be Run; it has an invalid spec: %s",
pipelineMeta.Namespace, pipelineMeta.Name, err)
return controller.NewPermanentError(err)
}
if err := resources.ValidateResourceBindings(pipelineSpec, pr); err != nil {
// This Run has failed, so we need to mark it as failed and stop reconciling it
pr.Status.MarkFailed(ReasonInvalidBindings,
"PipelineRun %s/%s doesn't bind Pipeline %s/%s's PipelineResources correctly: %s",
pr.Namespace, pr.Name, pr.Namespace, pipelineMeta.Name, err)
return controller.NewPermanentError(err)
}
providedResources, err := resources.GetResourcesFromBindings(pr, c.resourceLister.PipelineResources(pr.Namespace).Get)
if err != nil {
if errors.IsNotFound(err) && tknreconciler.IsYoungResource(pr) {
// For newly created resources, don't fail immediately.
// Instead return an (non-permanent) error, which will prompt the
// controller to requeue the key with backoff.
logger.Warnf("References for pipelinerun %s not found: %v", pr.Name, err)
pr.Status.MarkRunning(ReasonCouldntGetResource,
"Unable to resolve dependencies for %q: %v", pr.Name, err)
return err
}
// This Run has failed, so we need to mark it as failed and stop reconciling it
pr.Status.MarkFailed(ReasonCouldntGetResource,
"PipelineRun %s/%s can't be Run; it tries to bind Resources that don't exist: %s",
pipelineMeta.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
// Ensure that the PipelineRun provides all the parameters required by the Pipeline
if err := resources.ValidateRequiredParametersProvided(&pipelineSpec.Params, &pr.Spec.Params); err != nil {
// This Run has failed, so we need to mark it as failed and stop reconciling it
pr.Status.MarkFailed(ReasonParameterMissing,
"PipelineRun %s parameters is missing some parameters required by Pipeline %s's parameters: %s",
pr.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
// Ensure that the parameters from the PipelineRun are overriding Pipeline parameters with the same type.
// Weird substitution issues can occur if this is not validated (ApplyParameters() does not verify type).
err = resources.ValidateParamTypesMatching(pipelineSpec, pr)
if err != nil {
// This Run has failed, so we need to mark it as failed and stop reconciling it
pr.Status.MarkFailed(ReasonParameterTypeMismatch,
"PipelineRun %s/%s parameters have mismatching types with Pipeline %s/%s's parameters: %s",
pr.Namespace, pr.Name, pr.Namespace, pipelineMeta.Name, err)
return controller.NewPermanentError(err)
}
// Ensure that the workspaces expected by the Pipeline are provided by the PipelineRun.
if err := resources.ValidateWorkspaceBindings(pipelineSpec, pr); err != nil {
pr.Status.MarkFailed(ReasonInvalidWorkspaceBinding,
"PipelineRun %s/%s doesn't bind Pipeline %s/%s's Workspaces correctly: %s",
pr.Namespace, pr.Name, pr.Namespace, pipelineMeta.Name, err)
return controller.NewPermanentError(err)
}
// Ensure that the ServiceAccountNames defined are correct.
// This is "deprecated".
if err := resources.ValidateServiceaccountMapping(pipelineSpec, pr); err != nil {
pr.Status.MarkFailed(ReasonInvalidServiceAccountMapping,
"PipelineRun %s/%s doesn't define ServiceAccountNames correctly: %s",
pr.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
// Ensure that the TaskRunSpecs defined are correct.
if err := resources.ValidateTaskRunSpecs(pipelineSpec, pr); err != nil {
pr.Status.MarkFailed(ReasonInvalidServiceAccountMapping,
"PipelineRun %s/%s doesn't define taskRunSpecs correctly: %s",
pr.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
// Apply parameter substitution from the PipelineRun
pipelineSpec = resources.ApplyParameters(pipelineSpec, pr)
pipelineSpec = resources.ApplyContexts(pipelineSpec, pipelineMeta.Name, pr)
pipelineSpec = resources.ApplyWorkspaces(pipelineSpec, pr)
// pipelineState holds a list of pipeline tasks after resolving conditions and pipeline resources
// pipelineState also holds a taskRun for each pipeline task after the taskRun is created
// pipelineState is instantiated and updated on every reconcile cycle
// Resolve the set of tasks (and possibly task runs).
tasks := pipelineSpec.Tasks
if len(pipelineSpec.Finally) > 0 {
tasks = append(tasks, pipelineSpec.Finally...)
}
pipelineRunState, err := c.resolvePipelineState(ctx, tasks, pipelineMeta, pr, providedResources)
if err != nil {
return err
}
// Build PipelineRunFacts with a list of resolved pipeline tasks,
// dag tasks graph and final tasks graph
pipelineRunFacts := &resources.PipelineRunFacts{
State: pipelineRunState,
SpecStatus: pr.Spec.Status,
TasksGraph: d,
FinalTasksGraph: dfinally,
ScopeWhenExpressionsToTask: config.FromContextOrDefaults(ctx).FeatureFlags.ScopeWhenExpressionsToTask,
}
for _, rprt := range pipelineRunFacts.State {
if !rprt.IsCustomTask() {
err := taskrun.ValidateResolvedTaskResources(ctx, rprt.PipelineTask.Params, rprt.ResolvedTaskResources)
if err != nil {
logger.Errorf("Failed to validate pipelinerun %q with error %v", pr.Name, err)
pr.Status.MarkFailed(ReasonFailedValidation, err.Error())
return controller.NewPermanentError(err)
}
}
}
// check if pipeline run is not gracefully cancelled and there are active task runs, which require cancelling
if cfg.FeatureFlags.EnableAPIFields == apisconfig.AlphaAPIFields &&
pr.IsGracefullyCancelled() && pipelineRunFacts.IsRunning() {
// If the pipelinerun is cancelled, cancel tasks, but run finally
err := gracefullyCancelPipelineRun(ctx, logger, pr, c.PipelineClientSet)
if err != nil {
// failed to cancel tasks, maybe retry would help (don't return permanent error)
return err
}
}
if pipelineRunFacts.State.IsBeforeFirstTaskRun() {
if err := resources.ValidatePipelineTaskResults(pipelineRunFacts.State); err != nil {
logger.Errorf("Failed to resolve task result reference for %q with error %v", pr.Name, err)
pr.Status.MarkFailed(ReasonInvalidTaskResultReference, err.Error())
return controller.NewPermanentError(err)
}
if err := resources.ValidatePipelineResults(pipelineSpec, pipelineRunFacts.State); err != nil {
logger.Errorf("Failed to resolve task result reference for %q with error %v", pr.Name, err)
pr.Status.MarkFailed(ReasonInvalidTaskResultReference, err.Error())
return controller.NewPermanentError(err)
}
if err := resources.ValidateOptionalWorkspaces(pipelineSpec.Workspaces, pipelineRunFacts.State); err != nil {
logger.Errorf("Optional workspace not supported by task: %v", err)
pr.Status.MarkFailed(ReasonRequiredWorkspaceMarkedOptional, err.Error())
return controller.NewPermanentError(err)
}
if pr.HasVolumeClaimTemplate() {
// create workspace PVC from template
if err = c.pvcHandler.CreatePersistentVolumeClaimsForWorkspaces(ctx, pr.Spec.Workspaces, *kmeta.NewControllerRef(pr), pr.Namespace); err != nil {
logger.Errorf("Failed to create PVC for PipelineRun %s: %v", pr.Name, err)
pr.Status.MarkFailed(volumeclaim.ReasonCouldntCreateWorkspacePVC,
"Failed to create PVC for PipelineRun %s/%s Workspaces correctly: %s",
pr.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
}
if !c.isAffinityAssistantDisabled(ctx) {
// create Affinity Assistant (StatefulSet) so that taskRun pods that share workspace PVC achieve Node Affinity
if err = c.createAffinityAssistants(ctx, pr.Spec.Workspaces, pr, pr.Namespace); err != nil {
logger.Errorf("Failed to create affinity assistant StatefulSet for PipelineRun %s: %v", pr.Name, err)
pr.Status.MarkFailed(ReasonCouldntCreateAffinityAssistantStatefulSet,
"Failed to create StatefulSet for PipelineRun %s/%s correctly: %s",
pr.Namespace, pr.Name, err)
return controller.NewPermanentError(err)
}
}
}
as, err := artifacts.InitializeArtifactStorage(ctx, c.Images, pr, pipelineSpec, c.KubeClientSet)
if err != nil {
logger.Infof("PipelineRun failed to initialize artifact storage %s", pr.Name)
return controller.NewPermanentError(err)
}
if err := c.runNextSchedulableTask(ctx, pr, pipelineRunFacts, as); err != nil {
return err
}
if err := c.processRunTimeouts(ctx, pr, pipelineRunState); err != nil {
return err
}
// Reset the skipped status to trigger recalculation
pipelineRunFacts.ResetSkippedCache()
after := pipelineRunFacts.GetPipelineConditionStatus(pr, logger)
switch after.Status {
case corev1.ConditionTrue:
pr.Status.MarkSucceeded(after.Reason, after.Message)
case corev1.ConditionFalse:
pr.Status.MarkFailed(after.Reason, after.Message)
case corev1.ConditionUnknown:
pr.Status.MarkRunning(after.Reason, after.Message)
}
// Read the condition the way it was set by the Mark* helpers
after = pr.Status.GetCondition(apis.ConditionSucceeded)
pr.Status.StartTime = pipelineRunFacts.State.AdjustStartTime(pr.Status.StartTime)
pr.Status.TaskRuns = pipelineRunFacts.State.GetTaskRunsStatus(pr)
pr.Status.Runs = pipelineRunFacts.State.GetRunsStatus(pr)
pr.Status.SkippedTasks = pipelineRunFacts.GetSkippedTasks()
if after.Status == corev1.ConditionTrue {
pr.Status.PipelineResults = resources.ApplyTaskResultsToPipelineResults(pipelineSpec.Results, pr.Status.TaskRuns, pr.Status.Runs)
}
logger.Infof("PipelineRun %s status is being set to %s", pr.Name, after)
return nil
}
// processRunTimeouts custom tasks are requested to cancel, if they have timed out. Custom tasks can do any cleanup
// during this step.
func (c *Reconciler) processRunTimeouts(ctx context.Context, pr *v1beta1.PipelineRun, pipelineState resources.PipelineRunState) error {
errs := []string{}
logger := logging.FromContext(ctx)
if pr.IsCancelled() {
return nil
}
for _, rprt := range pipelineState {
if rprt.IsCustomTask() {
if rprt.Run != nil && !rprt.Run.IsCancelled() && (pr.IsTimedOut() || (rprt.Run.HasTimedOut() && !rprt.Run.IsDone())) {
logger.Infof("Cancelling run task: %s due to timeout.", rprt.RunName)
err := cancelRun(ctx, rprt.RunName, pr.Namespace, c.PipelineClientSet)
if err != nil {
errs = append(errs,
fmt.Errorf("failed to patch Run `%s` with cancellation: %s", rprt.RunName, err).Error())
}
}
}
}
if len(errs) > 0 {
e := strings.Join(errs, "\n")
return fmt.Errorf("error(s) from processing cancel request for timed out Run(s) of PipelineRun %s: %s", pr.Name, e)
}
return nil
}
// runNextSchedulableTask gets the next schedulable Tasks from the dag based on the current
// pipeline run state, and starts them
// after all DAG tasks are done, it's responsible for scheduling final tasks and start executing them
func (c *Reconciler) runNextSchedulableTask(ctx context.Context, pr *v1beta1.PipelineRun, pipelineRunFacts *resources.PipelineRunFacts, as artifacts.ArtifactStorageInterface) error {
logger := logging.FromContext(ctx)
recorder := controller.GetEventRecorder(ctx)
// nextRprts holds a list of pipeline tasks which should be executed next
nextRprts, err := pipelineRunFacts.DAGExecutionQueue()
if err != nil {
logger.Errorf("Error getting potential next tasks for valid pipelinerun %s: %v", pr.Name, err)
return controller.NewPermanentError(err)
}
resolvedResultRefs, _, err := resources.ResolveResultRefs(pipelineRunFacts.State, nextRprts)
if err != nil {
logger.Infof("Failed to resolve task result reference for %q with error %v", pr.Name, err)
pr.Status.MarkFailed(ReasonInvalidTaskResultReference, err.Error())
return controller.NewPermanentError(err)
}
resources.ApplyTaskResults(nextRprts, resolvedResultRefs)
// After we apply Task Results, we may be able to evaluate more
// when expressions, so reset the skipped cache
pipelineRunFacts.ResetSkippedCache()
// GetFinalTasks only returns tasks when a DAG is complete
fnextRprts := pipelineRunFacts.GetFinalTasks()
if len(fnextRprts) != 0 {
// apply the runtime context just before creating taskRuns for final tasks in queue
resources.ApplyPipelineTaskStateContext(fnextRprts, pipelineRunFacts.GetPipelineTaskStatus())
// Before creating TaskRun for scheduled final task, check if it's consuming a task result
// Resolve and apply task result wherever applicable, report warning in case resolution fails
for _, rprt := range fnextRprts {
resolvedResultRefs, _, err := resources.ResolveResultRef(pipelineRunFacts.State, rprt)
if err != nil {
logger.Infof("Final task %q is not executed as it could not resolve task params for %q: %v", rprt.PipelineTask.Name, pr.Name, err)
continue
}
resources.ApplyTaskResults(resources.PipelineRunState{rprt}, resolvedResultRefs)
nextRprts = append(nextRprts, rprt)
}
}
for _, rprt := range nextRprts {
if rprt == nil || rprt.Skip(pipelineRunFacts).IsSkipped || rprt.IsFinallySkipped(pipelineRunFacts).IsSkipped {
continue
}
if rprt.ResolvedConditionChecks == nil || rprt.ResolvedConditionChecks.IsSuccess() {
if rprt.IsCustomTask() {
if rprt.IsFinalTask(pipelineRunFacts) {
rprt.Run, err = c.createRun(ctx, rprt, pr, getFinallyTaskRunTimeout)
} else {
rprt.Run, err = c.createRun(ctx, rprt, pr, getTaskRunTimeout)
}
if err != nil {
recorder.Eventf(pr, corev1.EventTypeWarning, "RunCreationFailed", "Failed to create Run %q: %v", rprt.RunName, err)
return fmt.Errorf("error creating Run called %s for PipelineTask %s from PipelineRun %s: %w", rprt.RunName, rprt.PipelineTask.Name, pr.Name, err)
}
} else {
if rprt.IsFinalTask(pipelineRunFacts) {
rprt.TaskRun, err = c.createTaskRun(ctx, rprt, pr, as.StorageBasePath(pr), getFinallyTaskRunTimeout)
} else {
rprt.TaskRun, err = c.createTaskRun(ctx, rprt, pr, as.StorageBasePath(pr), getTaskRunTimeout)
}
if err != nil {
recorder.Eventf(pr, corev1.EventTypeWarning, "TaskRunCreationFailed", "Failed to create TaskRun %q: %v", rprt.TaskRunName, err)
return fmt.Errorf("error creating TaskRun called %s for PipelineTask %s from PipelineRun %s: %w", rprt.TaskRunName, rprt.PipelineTask.Name, pr.Name, err)
}
}
} else if !rprt.ResolvedConditionChecks.HasStarted() {
for _, rcc := range rprt.ResolvedConditionChecks {
rcc.ConditionCheck, err = c.makeConditionCheckContainer(ctx, rprt, rcc, pr)
if err != nil {
recorder.Eventf(pr, corev1.EventTypeWarning, "ConditionCheckCreationFailed", "Failed to create TaskRun %q: %v", rcc.ConditionCheckName, err)
return fmt.Errorf("error creating ConditionCheck container called %s for PipelineTask %s from PipelineRun %s: %w", rcc.ConditionCheckName, rprt.PipelineTask.Name, pr.Name, err)
}
}
}
}
return nil
}
func (c *Reconciler) updateTaskRunsStatusDirectly(pr *v1beta1.PipelineRun) error {
for taskRunName := range pr.Status.TaskRuns {
// TODO(dibyom): Add conditionCheck statuses here
prtrs := pr.Status.TaskRuns[taskRunName]
tr, err := c.taskRunLister.TaskRuns(pr.Namespace).Get(taskRunName)
if err != nil {
// If the TaskRun isn't found, it just means it won't be run
if !errors.IsNotFound(err) {
return fmt.Errorf("error retrieving TaskRun %s: %w", taskRunName, err)
}
} else {
prtrs.Status = &tr.Status
}
}
return nil
}
func (c *Reconciler) updateRunsStatusDirectly(pr *v1beta1.PipelineRun) error {
for runName := range pr.Status.Runs {
prRunStatus := pr.Status.Runs[runName]
run, err := c.runLister.Runs(pr.Namespace).Get(runName)
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("error retrieving Run %s: %w", runName, err)
}
} else {
prRunStatus.Status = &run.Status
}
}
return nil
}
type getTimeoutFunc func(ctx context.Context, pr *v1beta1.PipelineRun, rprt *resources.ResolvedPipelineRunTask) *metav1.Duration
func (c *Reconciler) createTaskRun(ctx context.Context, rprt *resources.ResolvedPipelineRunTask, pr *v1beta1.PipelineRun, storageBasePath string, getTimeoutFunc getTimeoutFunc) (*v1beta1.TaskRun, error) {
logger := logging.FromContext(ctx)
tr, _ := c.taskRunLister.TaskRuns(pr.Namespace).Get(rprt.TaskRunName)
if tr != nil {
// Don't modify the lister cache's copy.
tr = tr.DeepCopy()
// is a retry
addRetryHistory(tr)
clearStatus(tr)
tr.Status.SetCondition(&apis.Condition{
Type: apis.ConditionSucceeded,
Status: corev1.ConditionUnknown,
})
logger.Infof("Updating taskrun %s with cleared status and retry history (length: %d).", tr.GetName(), len(tr.Status.RetriesStatus))
return c.PipelineClientSet.TektonV1beta1().TaskRuns(pr.Namespace).UpdateStatus(ctx, tr, metav1.UpdateOptions{})
}
rprt.PipelineTask = resources.ApplyPipelineTaskContexts(rprt.PipelineTask)
taskRunSpec := pr.GetTaskRunSpec(rprt.PipelineTask.Name)
tr = &v1beta1.TaskRun{
ObjectMeta: metav1.ObjectMeta{
Name: rprt.TaskRunName,
Namespace: pr.Namespace,
OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(pr)},
Labels: combineTaskRunAndTaskSpecLabels(pr, rprt.PipelineTask),
Annotations: combineTaskRunAndTaskSpecAnnotations(pr, rprt.PipelineTask),
},
Spec: v1beta1.TaskRunSpec{
Params: rprt.PipelineTask.Params,
ServiceAccountName: taskRunSpec.TaskServiceAccountName,
Timeout: getTimeoutFunc(ctx, pr, rprt),
PodTemplate: taskRunSpec.TaskPodTemplate,
}}
if rprt.ResolvedTaskResources.TaskName != "" {
// We pass the entire, original task ref because it may contain additional references like a Bundle url.
tr.Spec.TaskRef = rprt.PipelineTask.TaskRef
} else if rprt.ResolvedTaskResources.TaskSpec != nil {
tr.Spec.TaskSpec = rprt.ResolvedTaskResources.TaskSpec
}
var pipelinePVCWorkspaceName string
var err error
tr.Spec.Workspaces, pipelinePVCWorkspaceName, err = getTaskrunWorkspaces(pr, rprt)
if err != nil {
return nil, err
}
if !c.isAffinityAssistantDisabled(ctx) && pipelinePVCWorkspaceName != "" {
tr.Annotations[workspace.AnnotationAffinityAssistantName] = getAffinityAssistantName(pipelinePVCWorkspaceName, pr.Name)
}
resources.WrapSteps(&tr.Spec, rprt.PipelineTask, rprt.ResolvedTaskResources.Inputs, rprt.ResolvedTaskResources.Outputs, storageBasePath)
logger.Infof("Creating a new TaskRun object %s for pipeline task %s", rprt.TaskRunName, rprt.PipelineTask.Name)
return c.PipelineClientSet.TektonV1beta1().TaskRuns(pr.Namespace).Create(ctx, tr, metav1.CreateOptions{})
}
func (c *Reconciler) createRun(ctx context.Context, rprt *resources.ResolvedPipelineRunTask, pr *v1beta1.PipelineRun, getTimeoutFunc getTimeoutFunc) (*v1alpha1.Run, error) {
logger := logging.FromContext(ctx)
taskRunSpec := pr.GetTaskRunSpec(rprt.PipelineTask.Name)
r := &v1alpha1.Run{
ObjectMeta: metav1.ObjectMeta{
Name: rprt.RunName,
Namespace: pr.Namespace,
OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(pr)},
Labels: getTaskrunLabels(pr, rprt.PipelineTask.Name, true),
Annotations: getTaskrunAnnotations(pr),
},
Spec: v1alpha1.RunSpec{
Ref: rprt.PipelineTask.TaskRef,
Params: rprt.PipelineTask.Params,
ServiceAccountName: taskRunSpec.TaskServiceAccountName,
Timeout: getTimeoutFunc(ctx, pr, rprt),
PodTemplate: taskRunSpec.TaskPodTemplate,
},
}
if rprt.PipelineTask.TaskSpec != nil {
j, err := json.Marshal(rprt.PipelineTask.TaskSpec.Spec)
if err != nil {
return nil, err
}
r.Spec.Spec = &v1alpha1.EmbeddedRunSpec{
TypeMeta: runtime.TypeMeta{
APIVersion: rprt.PipelineTask.TaskSpec.APIVersion,
Kind: rprt.PipelineTask.TaskSpec.Kind,
},
Metadata: rprt.PipelineTask.TaskSpec.Metadata,
Spec: runtime.RawExtension{
Raw: j,
},
}
}
var pipelinePVCWorkspaceName string
var err error
r.Spec.Workspaces, pipelinePVCWorkspaceName, err = getTaskrunWorkspaces(pr, rprt)
if err != nil {
return nil, err
}
// Set the affinity assistant annotation in case the custom task creates TaskRuns or Pods
// that can take advantage of it.
if !c.isAffinityAssistantDisabled(ctx) && pipelinePVCWorkspaceName != "" {
r.Annotations[workspace.AnnotationAffinityAssistantName] = getAffinityAssistantName(pipelinePVCWorkspaceName, pr.Name)
}
logger.Infof("Creating a new Run object %s", rprt.RunName)
return c.PipelineClientSet.TektonV1alpha1().Runs(pr.Namespace).Create(ctx, r, metav1.CreateOptions{})
}
func getTaskrunWorkspaces(pr *v1beta1.PipelineRun, rprt *resources.ResolvedPipelineRunTask) ([]v1beta1.WorkspaceBinding, string, error) {
var workspaces []v1beta1.WorkspaceBinding
var pipelinePVCWorkspaceName string
pipelineRunWorkspaces := make(map[string]v1beta1.WorkspaceBinding)
for _, binding := range pr.Spec.Workspaces {
pipelineRunWorkspaces[binding.Name] = binding
}
for _, ws := range rprt.PipelineTask.Workspaces {
taskWorkspaceName, pipelineTaskSubPath, pipelineWorkspaceName := ws.Name, ws.SubPath, ws.Workspace
if b, hasBinding := pipelineRunWorkspaces[pipelineWorkspaceName]; hasBinding {
if b.PersistentVolumeClaim != nil || b.VolumeClaimTemplate != nil {
pipelinePVCWorkspaceName = pipelineWorkspaceName
}
workspaces = append(workspaces, taskWorkspaceByWorkspaceVolumeSource(b, taskWorkspaceName, pipelineTaskSubPath, *kmeta.NewControllerRef(pr)))
} else {
workspaceIsOptional := false
if rprt.ResolvedTaskResources != nil && rprt.ResolvedTaskResources.TaskSpec != nil {
for _, taskWorkspaceDeclaration := range rprt.ResolvedTaskResources.TaskSpec.Workspaces {
if taskWorkspaceDeclaration.Name == taskWorkspaceName && taskWorkspaceDeclaration.Optional {
workspaceIsOptional = true
break
}
}
}
if !workspaceIsOptional {
return nil, "", fmt.Errorf("expected workspace %q to be provided by pipelinerun for pipeline task %q", pipelineWorkspaceName, rprt.PipelineTask.Name)
}
}
}
return workspaces, pipelinePVCWorkspaceName, nil
}
// taskWorkspaceByWorkspaceVolumeSource is returning the WorkspaceBinding with the TaskRun specified name.
// If the volume source is a volumeClaimTemplate, the template is applied and passed to TaskRun as a persistentVolumeClaim
func taskWorkspaceByWorkspaceVolumeSource(wb v1beta1.WorkspaceBinding, taskWorkspaceName string, pipelineTaskSubPath string, owner metav1.OwnerReference) v1beta1.WorkspaceBinding {
| // combinedSubPath returns the combined value of the optional subPath from workspaceBinding and the optional
// subPath from pipelineTask. If both is set, they are joined with a slash.
func combinedSubPath(workspaceSubPath string, pipelineTaskSubPath string) string {
if workspaceSubPath == "" {
return pipelineTaskSubPath
} else if pipelineTaskSubPath == "" {
return workspaceSubPath
}
return filepath.Join(workspaceSubPath, pipelineTaskSubPath)
}
func addRetryHistory(tr *v1beta1.TaskRun) {
newStatus := *tr.Status.DeepCopy()
newStatus.RetriesStatus = nil
tr.Status.RetriesStatus = append(tr.Status.RetriesStatus, newStatus)
}
func clearStatus(tr *v1beta1.TaskRun) {
tr.Status.StartTime = nil
tr.Status.CompletionTime = nil
tr.Status.PodName = ""
}
func getTaskrunAnnotations(pr *v1beta1.PipelineRun) map[string]string {
// Propagate annotations from PipelineRun to TaskRun.
annotations := make(map[string]string, len(pr.ObjectMeta.Annotations)+1)
for key, val := range pr.ObjectMeta.Annotations {
annotations[key] = val
}
return annotations
}
func propagatePipelineNameLabelToPipelineRun(pr *v1beta1.PipelineRun) error {
if pr.ObjectMeta.Labels == nil {
pr.ObjectMeta.Labels = make(map[string]string)
}
switch {
case pr.Spec.PipelineRef != nil && pr.Spec.PipelineRef.Name != "":
pr.ObjectMeta.Labels[pipeline.PipelineLabelKey] = pr.Spec.PipelineRef.Name
case pr.Spec.PipelineSpec != nil:
pr.ObjectMeta.Labels[pipeline.PipelineLabelKey] = pr.Name
default:
return fmt.Errorf("pipelineRun %s not providing PipelineRef or PipelineSpec", pr.Name)
}
return nil
}
func getTaskrunLabels(pr *v1beta1.PipelineRun, pipelineTaskName string, includePipelineLabels bool) map[string]string {
// Propagate labels from PipelineRun to TaskRun.
labels := make(map[string]string, len(pr.ObjectMeta.Labels)+1)
if includePipelineLabels {
for key, val := range pr.ObjectMeta.Labels {
labels[key] = val
}
}
labels[pipeline.PipelineRunLabelKey] = pr.Name
if pipelineTaskName != "" {
labels[pipeline.PipelineTaskLabelKey] = pipelineTaskName
}
if pr.Status.PipelineSpec != nil {
// check if a task is part of the "tasks" section, add a label to identify it during the runtime
for _, f := range pr.Status.PipelineSpec.Tasks {
if pipelineTaskName == f.Name {
labels[pipeline.MemberOfLabelKey] = v1beta1.PipelineTasks
break
}
}
// check if a task is part of the "finally" section, add a label to identify it during the runtime
for _, f := range pr.Status.PipelineSpec.Finally {
if pipelineTaskName == f.Name {
labels[pipeline.MemberOfLabelKey] = v1beta1.PipelineFinallyTasks
break
}
}
}
return labels
}
func combineTaskRunAndTaskSpecLabels(pr *v1beta1.PipelineRun, pipelineTask *v1beta1.PipelineTask) map[string]string {
var tsLabels map[string]string
trLabels := getTaskrunLabels(pr, pipelineTask.Name, true)
if pipelineTask.TaskSpec != nil {
tsLabels = pipelineTask.TaskSpecMetadata().Labels
}
labels := make(map[string]string, len(trLabels)+len(tsLabels))
// labels from TaskRun takes higher precedence over the ones specified in Pipeline through TaskSpec
// initialize labels with TaskRun labels
labels = trLabels
for key, value := range tsLabels {
// add labels from TaskSpec if the label does not exist
if _, ok := labels[key]; !ok {
labels[key] = value
}
}
return labels
}
func combineTaskRunAndTaskSpecAnnotations(pr *v1beta1.PipelineRun, pipelineTask *v1beta1.PipelineTask) map[string]string {
var tsAnnotations map[string]string
trAnnotations := getTaskrunAnnotations(pr)
if pipelineTask.TaskSpec != nil {
tsAnnotations = pipelineTask.TaskSpecMetadata().Annotations
}
annotations := make(map[string]string, len(trAnnotations)+len(tsAnnotations))
// annotations from TaskRun takes higher precedence over the ones specified in Pipeline through TaskSpec
// initialize annotations with TaskRun annotations
annotations = trAnnotations
for key, value := range tsAnnotations {
// add annotations from TaskSpec if the annotation does not exist
if _, ok := annotations[key]; !ok {
annotations[key] = value
}
}
return annotations
}
func getFinallyTaskRunTimeout(ctx context.Context, pr *v1beta1.PipelineRun, rprt *resources.ResolvedPipelineRunTask) *metav1.Duration {
var taskRunTimeout = &metav1.Duration{Duration: apisconfig.NoTimeoutDuration}
var timeout, tasksTimeout time.Duration
defaultTimeout := time.Duration(config.FromContextOrDefaults(ctx).Defaults.DefaultTimeoutMinutes)
switch {
case pr.Spec.Timeout != nil:
timeout = pr.Spec.Timeout.Duration
case pr.Spec.Timeouts != nil:
// Take into account the elapsed time in order to check if we still have enough time to run
// If task timeout is defined, add it to finally timeout
// Else consider pipeline timeout as finally timeout
switch {
case pr.Spec.Timeouts.Finally != nil:
if pr.Spec.Timeouts.Tasks != nil {
tasksTimeout = pr.Spec.Timeouts.Tasks.Duration
timeout = tasksTimeout + pr.Spec.Timeouts.Finally.Duration
} else if pr.Spec.Timeouts.Pipeline != nil {
tasksTimeout = pr.Spec.Timeouts.Pipeline.Duration - pr.Spec.Timeouts.Finally.Duration
timeout = pr.Spec.Timeouts.Pipeline.Duration
}
case pr.Spec.Timeouts.Pipeline != nil:
timeout = pr.Spec.Timeouts.Pipeline.Duration
if pr.Spec.Timeouts.Tasks != nil {
tasksTimeout = pr.Spec.Timeouts.Tasks.Duration
}
default:
timeout = defaultTimeout * time.Minute
if pr.Spec.Timeouts.Tasks != nil {
tasksTimeout = pr.Spec.Timeouts.Tasks.Duration
}
}
default:
timeout = defaultTimeout * time.Minute
}
// If the value of the timeout is 0 for any resource, there is no timeout.
// It is impossible for pr.Spec.Timeout to be nil, since SetDefault always assigns it with a value.
taskRunTimeout = taskRunTimeoutHelper(timeout, pr, taskRunTimeout, rprt)
// Now that we know if we still have time to run the final task, subtract tasksTimeout if needed
if taskRunTimeout.Duration > time.Second {
taskRunTimeout.Duration -= tasksTimeout
}
return taskRunTimeout
}
func getTaskRunTimeout(ctx context.Context, pr *v1beta1.PipelineRun, rprt *resources.ResolvedPipelineRunTask) *metav1.Duration {
var taskRunTimeout = &metav1.Duration{Duration: apisconfig.NoTimeoutDuration}
var timeout time.Duration
switch {
case pr.Spec.Timeout != nil:
timeout = pr.Spec.Timeout.Duration
case pr.Spec.Timeouts != nil:
if pr.Spec.Timeouts.Tasks != nil {
timeout = pr.Spec.Timeouts.Tasks.Duration
break
}
if pr.Spec.Timeouts.Pipeline != nil {
timeout = pr.Spec.Timeouts.Pipeline.Duration
}
if pr.Spec.Timeouts.Finally != nil {
timeout -= pr.Spec.Timeouts.Finally.Duration
}
default:
defaultTimeout := time.Duration(config.FromContextOrDefaults(ctx).Defaults.DefaultTimeoutMinutes)
timeout = defaultTimeout * time.Minute
}
// If the value of the timeout is 0 for any resource, there is no timeout.
// It is impossible for pr.Spec.Timeout to be nil, since SetDefault always assigns it with a value.
taskRunTimeout = taskRunTimeoutHelper(timeout, pr, taskRunTimeout, rprt)
return taskRunTimeout
}
func taskRunTimeoutHelper(timeout time.Duration, pr *v1beta1.PipelineRun, taskRunTimeout *metav1.Duration, rprt *resources.ResolvedPipelineRunTask) *metav1.Duration {
if timeout != apisconfig.NoTimeoutDuration {
pTimeoutTime := pr.Status.StartTime.Add(timeout)
if time.Now().After(pTimeoutTime) {
taskRunTimeout = &metav1.Duration{Duration: time.Until(pTimeoutTime)}
if taskRunTimeout.Duration < 0 {
taskRunTimeout = &metav1.Duration{Duration: 1 * time.Second}
}
} else {
if rprt.PipelineTask.Timeout != nil {
taskRunTimeout = &metav1.Duration{Duration: rprt.PipelineTask.Timeout.Duration}
} else {
taskRunTimeout = &metav1.Duration{Duration: timeout}
}
}
}
if timeout == apisconfig.NoTimeoutDuration && rprt.PipelineTask.Timeout != nil {
taskRunTimeout = &metav1.Duration{Duration: rprt.PipelineTask.Timeout.Duration}
}
return taskRunTimeout
}
func (c *Reconciler) updateLabelsAndAnnotations(ctx context.Context, pr *v1beta1.PipelineRun) (*v1beta1.PipelineRun, error) {
newPr, err := c.pipelineRunLister.PipelineRuns(pr.Namespace).Get(pr.Name)
if err != nil {
return nil, fmt.Errorf("error getting PipelineRun %s when updating labels/annotations: %w", pr.Name, err)
}
if !reflect.DeepEqual(pr.ObjectMeta.Labels, newPr.ObjectMeta.Labels) || !reflect.DeepEqual(pr.ObjectMeta.Annotations, newPr.ObjectMeta.Annotations) {
// Note that this uses Update vs. Patch because the former is significantly easier to test.
// If we want to switch this to Patch, then we will need to teach the utilities in test/controller.go
// to deal with Patch (setting resourceVersion, and optimistic concurrency checks).
newPr = newPr.DeepCopy()
newPr.Labels = pr.Labels
newPr.Annotations = pr.Annotations
return c.PipelineClientSet.TektonV1beta1().PipelineRuns(pr.Namespace).Update(ctx, newPr, metav1.UpdateOptions{})
}
return newPr, nil
}
func (c *Reconciler) makeConditionCheckContainer(ctx context.Context, rprt *resources.ResolvedPipelineRunTask, rcc *resources.ResolvedConditionCheck, pr *v1beta1.PipelineRun) (*v1beta1.ConditionCheck, error) {
labels := getTaskrunLabels(pr, rprt.PipelineTask.Name, true)
labels[pipeline.ConditionCheckKey] = rcc.ConditionCheckName
labels[pipeline.ConditionNameKey] = rcc.Condition.Name
for key, value := range rcc.Condition.ObjectMeta.Labels {
labels[key] = value
}
// Propagate annotations from PipelineRun to TaskRun.
annotations := getTaskrunAnnotations(pr)
for key, value := range rcc.Condition.ObjectMeta.Annotations {
annotations[key] = value
}
taskSpec, err := rcc.ConditionToTaskSpec()
if err != nil {
return nil, fmt.Errorf("failed to get TaskSpec from Condition: %w", err)
}
taskRunSpec := pr.GetTaskRunSpec(rprt.PipelineTask.Name)
tr := &v1beta1.TaskRun{
ObjectMeta: metav1.ObjectMeta{
Name: rcc.ConditionCheckName,
Namespace: pr.Namespace,
OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(pr)},
Labels: labels,
Annotations: annotations,
},
Spec: v1beta1.TaskRunSpec{
TaskSpec: taskSpec,
ServiceAccountName: taskRunSpec.TaskServiceAccountName,
Params: rcc.PipelineTaskCondition.Params,
Resources: &v1beta1.TaskRunResources{
Inputs: rcc.ToTaskResourceBindings(),
},
Timeout: getTaskRunTimeout(ctx, pr, rprt),
PodTemplate: taskRunSpec.TaskPodTemplate,
}}
cctr, err := c.PipelineClientSet.TektonV1beta1().TaskRuns(pr.Namespace).Create(ctx, tr, metav1.CreateOptions{})
cc := v1beta1.ConditionCheck(*cctr)
return &cc, err
}
func storePipelineSpec(ctx context.Context, pr *v1beta1.PipelineRun, ps *v1beta1.PipelineSpec) error {
// Only store the PipelineSpec once, if it has never been set before.
if pr.Status.PipelineSpec == nil {
pr.Status.PipelineSpec = ps
}
return nil
}
func (c *Reconciler) updatePipelineRunStatusFromInformer(ctx context.Context, pr *v1beta1.PipelineRun) error {
logger := logging.FromContext(ctx)
// Get the pipelineRun label that is set on each TaskRun. Do not include the propagated labels from the
// Pipeline and PipelineRun. The user could change them during the lifetime of the PipelineRun so the
// current labels may not be set on the previously created TaskRuns.
pipelineRunLabels := getTaskrunLabels(pr, "", false)
taskRuns, err := c.taskRunLister.TaskRuns(pr.Namespace).List(k8slabels.SelectorFromSet(pipelineRunLabels))
if err != nil {
logger.Errorf("could not list TaskRuns %#v", err)
return err
}
updatePipelineRunStatusFromTaskRuns(logger, pr, taskRuns)
runs, err := c.runLister.Runs(pr.Namespace).List(k8slabels.SelectorFromSet(pipelineRunLabels))
if err != nil {
logger.Errorf("could not list Runs %#v", err)
return err
}
updatePipelineRunStatusFromRuns(logger, pr, runs)
return nil
}
func updatePipelineRunStatusFromTaskRuns(logger *zap.SugaredLogger, pr *v1beta1.PipelineRun, trs []*v1beta1.TaskRun) {
// If no TaskRun was found, nothing to be done. We never remove taskruns from the status
if trs == nil || len(trs) == 0 {
return
}
// Store a list of Condition TaskRuns for each PipelineTask (by name)
conditionTaskRuns := make(map[string][]*v1beta1.TaskRun)
// Map PipelineTask names to TaskRun names that were already in the status
taskRunByPipelineTask := make(map[string]string)
if pr.Status.TaskRuns != nil {
for taskRunName, pipelineRunTaskRunStatus := range pr.Status.TaskRuns {
taskRunByPipelineTask[pipelineRunTaskRunStatus.PipelineTaskName] = taskRunName
}
} else {
pr.Status.TaskRuns = make(map[string]*v1beta1.PipelineRunTaskRunStatus)
}
// Loop over all the TaskRuns associated to Tasks
for _, taskrun := range trs {
// Only process TaskRuns that are owned by this PipelineRun.
// This skips TaskRuns that are indirectly created by the PipelineRun (e.g. by custom tasks).
if len(taskrun.OwnerReferences) < 1 || taskrun.OwnerReferences[0].UID != pr.ObjectMeta.UID {
logger.Debugf("Found a TaskRun %s that is not owned by this PipelineRun", taskrun.Name)
continue
}
lbls := taskrun.GetLabels()
pipelineTaskName := lbls[pipeline.PipelineTaskLabelKey]
if _, ok := lbls[pipeline.ConditionCheckKey]; ok {
// Save condition for looping over them after this
if _, ok := conditionTaskRuns[pipelineTaskName]; !ok {
// If it's the first condition taskrun, initialise the slice
conditionTaskRuns[pipelineTaskName] = []*v1beta1.TaskRun{}
}
conditionTaskRuns[pipelineTaskName] = append(conditionTaskRuns[pipelineTaskName], taskrun)
continue
}
if _, ok := pr.Status.TaskRuns[taskrun.Name]; !ok {
// This taskrun was missing from the status.
// Add it without conditions, which are handled in the next loop
logger.Infof("Found a TaskRun %s that was missing from the PipelineRun status", taskrun.Name)
pr.Status.TaskRuns[taskrun.Name] = &v1beta1.PipelineRunTaskRunStatus{
PipelineTaskName: pipelineTaskName,
Status: &taskrun.Status,
ConditionChecks: nil,
}
// Since this was recovered now, add it to the map, or it might be overwritten
taskRunByPipelineTask[pipelineTaskName] = taskrun.Name
}
}
// Then loop by pipelinetask name over all the TaskRuns associated to Conditions
for pipelineTaskName, actualConditionTaskRuns := range conditionTaskRuns {
taskRunName, ok := taskRunByPipelineTask[pipelineTaskName]
if !ok {
// The pipelineTask associated to the conditions was not found in the pipelinerun
// status. This means that the conditions were orphaned, and never added to the
// status. In this case we need to generate a new TaskRun name, that will be used
// to run the TaskRun if the conditions are passed.
taskRunName = resources.GetTaskRunName(pr.Status.TaskRuns, pipelineTaskName, pr.Name)
pr.Status.TaskRuns[taskRunName] = &v1beta1.PipelineRunTaskRunStatus{
PipelineTaskName: pipelineTaskName,
Status: nil,
ConditionChecks: nil,
}
}
// Build the map of condition checks for the taskrun
// If there were no other condition, initialise the map
conditionChecks := pr.Status.TaskRuns[taskRunName].ConditionChecks
if conditionChecks == nil {
conditionChecks = make(map[string]*v1beta1.PipelineRunConditionCheckStatus)
}
for i, foundTaskRun := range actualConditionTaskRuns {
lbls := foundTaskRun.GetLabels()
if _, ok := conditionChecks[foundTaskRun.Name]; !ok {
// The condition check was not found, so we need to add it
// We only add the condition name, the status can now be gathered by the
// normal reconcile process
if conditionName, ok := lbls[pipeline.ConditionNameKey]; ok {
conditionChecks[foundTaskRun.Name] = &v1beta1.PipelineRunConditionCheckStatus{
ConditionName: fmt.Sprintf("%s-%s", conditionName, strconv.Itoa(i)),
}
} else {
// The condition name label is missing, so we cannot recover this
logger.Warnf("found an orphaned condition taskrun %#v with missing %s label",
foundTaskRun, pipeline.ConditionNameKey)
}
}
}
pr.Status.TaskRuns[taskRunName].ConditionChecks = conditionChecks
}
}
func updatePipelineRunStatusFromRuns(logger *zap.SugaredLogger, pr *v1beta1.PipelineRun, runs []*v1alpha1.Run) {
// If no Run was found, nothing to be done. We never remove runs from the status
if runs == nil || len(runs) == 0 {
return
}
if pr.Status.Runs == nil {
pr.Status.Runs = make(map[string]*v1beta1.PipelineRunRunStatus)
}
// Loop over all the Runs associated to Tasks
for _, run := range runs {
// Only process Runs that are owned by this PipelineRun.
// This skips Runs that are indirectly created by the PipelineRun (e.g. by custom tasks).
if len(run.OwnerReferences) < 1 && run.OwnerReferences[0].UID != pr.ObjectMeta.UID {
logger.Debugf("Found a Run %s that is not owned by this PipelineRun", run.Name)
continue
}
lbls := run.GetLabels()
pipelineTaskName := lbls[pipeline.PipelineTaskLabelKey]
if _, ok := pr.Status.Runs[run.Name]; !ok {
// This run was missing from the status.
pr.Status.Runs[run.Name] = &v1beta1.PipelineRunRunStatus{
PipelineTaskName: pipelineTaskName,
Status: &run.Status,
}
}
}
}
| if wb.VolumeClaimTemplate == nil {
binding := *wb.DeepCopy()
binding.Name = taskWorkspaceName
binding.SubPath = combinedSubPath(wb.SubPath, pipelineTaskSubPath)
return binding
}
// apply template
binding := v1beta1.WorkspaceBinding{
SubPath: combinedSubPath(wb.SubPath, pipelineTaskSubPath),
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: volumeclaim.GetPersistentVolumeClaimName(wb.VolumeClaimTemplate, wb, owner),
},
}
binding.Name = taskWorkspaceName
return binding
}
|
karma.conf.js | // Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
// bower:js
'client/bower_components/jquery/dist/jquery.js',
'client/bower_components/angular/angular.js', | 'client/bower_components/angular-sanitize/angular-sanitize.js',
'client/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'client/bower_components/lodash/dist/lodash.compat.js',
'client/bower_components/angular-socket-io/socket.js',
'client/bower_components/angular-ui-router/release/angular-ui-router.js',
'client/bower_components/angular-validation-match/dist/angular-validation-match.min.js',
'client/bower_components/angular-translate/angular-translate.js',
'client/bower_components/angular-animate/angular-animate.js',
'client/bower_components/angular-cache/dist/angular-cache.js',
'client/bower_components/angular-mocks/angular-mocks.js',
// endbower
'node_modules/socket.io-client/socket.io.js',
'client/app/app.js',
'client/{app,components}/**/*.module.js',
'client/{app,components}/**/*.js',
'client/{app,components}/**/*.{jade,html}'
],
preprocessors: {
'**/*.html': 'ng-html2js',
'**/*.jade': 'ng-jade2js',
'client/{app,components}/**/*.js': 'babel'
},
ngHtml2JsPreprocessor: {
stripPrefix: 'client/'
},
ngJade2JsPreprocessor: {
stripPrefix: 'client/'
},
babelPreprocessor: {
options: {
sourceMap: 'inline',
optional: [
'es7.classProperties'
]
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
},
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// reporter types:
// - dots
// - progress (default)
// - spec (karma-spec-reporter)
// - junit
// - growl
// - coverage
reporters: ['spec'],
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
}; | 'client/bower_components/angular-resource/angular-resource.js',
'client/bower_components/angular-cookies/angular-cookies.js', |
densenet.py | """DenseNet models for Keras.
# Reference paper
- [Densely Connected Convolutional Networks]
(https://arxiv.org/abs/1608.06993) (CVPR 2017 Best Paper Award)
# Reference implementation
- [Torch DenseNets]
(https://github.com/liuzhuang13/DenseNet/blob/master/models/densenet.lua)
- [TensorNets]
(https://github.com/taehoonlee/tensornets/blob/master/tensornets/densenets.py)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from keras import backend as K
from keras.layers import Input, Add, Dense, Activation, Flatten, Convolution2D, MaxPooling2D, ZeroPadding2D, \
AveragePooling2D, TimeDistributed, BatchNormalization, Dropout
from keras import layers
from keras_frcnn.RoiPoolingConv import RoiPoolingConv
"""
couple of functions for frcnn..
"""
def get_weight_path():
return os.path.join("pretrain", 'densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5')
def get_img_output_length(width, height):
def get_output_length(input_length):
# zero_pad
input_length += 6
# apply 4 strided convolutions
filter_sizes = [7, 3, 1, 1]
stride = 2
for filter_size in filter_sizes:
input_length = (input_length - filter_size + stride) // stride
return input_length
return get_output_length(width), get_output_length(height)
BASE_WEIGTHS_PATH = (
'https://github.com/keras-team/keras-applications/'
'releases/download/densenet/')
DENSENET121_WEIGHT_PATH = (
BASE_WEIGTHS_PATH +
'densenet121_weights_tf_dim_ordering_tf_kernels.h5')
DENSENET121_WEIGHT_PATH_NO_TOP = (
BASE_WEIGTHS_PATH +
'densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5')
DENSENET169_WEIGHT_PATH = (
BASE_WEIGTHS_PATH +
'densenet169_weights_tf_dim_ordering_tf_kernels.h5')
DENSENET169_WEIGHT_PATH_NO_TOP = (
BASE_WEIGTHS_PATH +
'densenet169_weights_tf_dim_ordering_tf_kernels_notop.h5')
DENSENET201_WEIGHT_PATH = (
BASE_WEIGTHS_PATH +
'densenet201_weights_tf_dim_ordering_tf_kernels.h5')
DENSENET201_WEIGHT_PATH_NO_TOP = (
BASE_WEIGTHS_PATH +
'densenet201_weights_tf_dim_ordering_tf_kernels_notop.h5')
def dense_block(x, blocks, name):
"""A dense block.
# Arguments
x: input tensor.
blocks: integer, the number of building blocks.
name: string, block label.
# Returns
output tensor for the block.
"""
for i in range(blocks):
x = conv_block(x, 32, name=name + '_block' + str(i + 1))
return x
def transition_block(x, reduction, name):
"""A transition block.
# Arguments
x: input tensor.
reduction: float, compression rate at transition layers.
name: string, block label.
# Returns
output tensor for the block.
"""
bn_axis = 3 if K.image_data_format() == 'channels_last' else 1
x = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5,
name=name + '_bn')(x)
x = layers.Activation('relu', name=name + '_relu')(x)
x = layers.Conv2D(int(K.int_shape(x)[bn_axis] * reduction), 1,
use_bias=False,
name=name + '_conv')(x)
x = layers.AveragePooling2D(2, strides=2, name=name + '_pool', padding='same')(x)
return x
def conv_block(x, growth_rate, name):
"""A building block for a dense block.
# Arguments
x: input tensor.
growth_rate: float, growth rate at dense layers.
name: string, block label.
# Returns
Output tensor for the block.
"""
bn_axis = 3 if K.image_data_format() == 'channels_last' else 1
x1 = layers.BatchNormalization(axis=bn_axis,
epsilon=1.001e-5,
name=name + '_0_bn')(x)
x1 = layers.Activation('relu', name=name + '_0_relu')(x1)
x1 = layers.Conv2D(4 * growth_rate, 1,
use_bias=False,
name=name + '_1_conv')(x1)
x1 = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5,
name=name + '_1_bn')(x1)
x1 = layers.Activation('relu', name=name + '_1_relu')(x1)
x1 = layers.Conv2D(growth_rate, 3,
padding='same',
use_bias=False,
name=name + '_2_conv')(x1)
x = layers.Concatenate(axis=bn_axis, name=name + '_concat')([x, x1])
return x
def nn_base(input_tensor=None,
blocks=[6, 12, 24, 16],
include_top=False,
weights='imagenet',
input_shape=None,
pooling=None,
classes=1000,
**kwargs):
"""Instantiates the DenseNet architecture.
Optionally loads weights pre-trained on ImageNet.
Note that the data format convention used by the model is
the one specified in your Keras config at `~/.keras/keras.json`.
# Arguments
blocks: numbers of building blocks for the four dense layers.
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor
(i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `'channels_last'` data format)
or `(3, 224, 224)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
pooling: optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
# Returns
A Keras model instance.
| """
if not (weights in {'imagenet', None} or os.path.exists(weights)):
raise ValueError('The `weights` argument should be either '
'`None` (random initialization), `imagenet` '
'(pre-training on ImageNet), '
'or the path to the weights file to be loaded.')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as `"imagenet"` with `include_top`'
' as true, `classes` should be 1000')
# Determine proper input shape
if K.image_dim_ordering() == 'th':
input_shape = (3, None, None)
else:
input_shape = (None, None, 3)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
if K.image_dim_ordering() == 'tf':
bn_axis = 3
else:
bn_axis = 1
x = ZeroPadding2D((3, 3))(img_input)
x = layers.Conv2D(64, 7, strides=2, use_bias=False, name='conv1/conv')(x)
x = layers.BatchNormalization(
axis=bn_axis, epsilon=1.001e-5, name='conv1/bn')(x)
x = layers.Activation('relu', name='conv1/relu')(x)
# x = layers.ZeroPadding2D(padding=((1, 1), (1, 1)))(x)
x = layers.MaxPooling2D(3, strides=2, name='pool1')(x)
x = dense_block(x, blocks[0], name='conv2')
x = transition_block(x, 0.5, name='pool2')
x = dense_block(x, blocks[1], name='conv3')
x = transition_block(x, 0.5, name='pool3')
x = dense_block(x, blocks[2], name='conv4')
# here, the output size is similar to resnet50. stop here.
# x = transition_block(x, 0.5, name='pool4')
# x = dense_block(x, blocks[3], name='conv5')
x = layers.BatchNormalization(
axis=bn_axis, epsilon=1.001e-5, name='bn')(x)
x = layers.Activation('relu', name='relu')(x)
return x
def rpn(base_layers,num_anchors):
x = Convolution2D(512, (3, 3), padding='same', activation='relu', kernel_initializer='normal', name='rpn_conv1')(base_layers)
x_class = Convolution2D(num_anchors, (1, 1), padding="same", activation='sigmoid', kernel_initializer='uniform', name='rpn_out_class')(x)
x_regr = Convolution2D(num_anchors * 4, (1, 1), activation='linear', kernel_initializer='zero', name='rpn_out_regress')(x)
return [x_class, x_regr, base_layers]
def classifier(base_layers, input_rois, num_rois, nb_classes = 21, trainable=False):
# compile times on theano tend to be very high, so we use smaller ROI pooling regions to workaround
if K.backend() == 'tensorflow':
pooling_regions = 14
input_shape = (num_rois,14,14,1024) # densenet output channels are 1024..
elif K.backend() == 'theano':
pooling_regions = 7
input_shape = (num_rois,4096,7,7)
# from vgg version..
out_roi_pool = RoiPoolingConv(pooling_regions, num_rois)([base_layers, input_rois])
out_roi_pool = TimeDistributed(AveragePooling2D((7, 7)), name='avg_pool')(out_roi_pool)
out = TimeDistributed(Flatten(name='flatten'))(out_roi_pool)
out = TimeDistributed(Dense(4096, activation='relu', name='fc1'))(out)
out = TimeDistributed(Dropout(0.5))(out)
out = TimeDistributed(Dense(4096, activation='relu', name='fc2'))(out)
out = TimeDistributed(Dropout(0.5))(out)
out_class = TimeDistributed(Dense(nb_classes, activation='softmax', kernel_initializer='zero'), name='dense_class_{}'.format(nb_classes))(out)
# note: no regression target for bg class
out_regr = TimeDistributed(Dense(4 * (nb_classes-1), activation='linear', kernel_initializer='zero'), name='dense_regress_{}'.format(nb_classes))(out)
return [out_class, out_regr] | # Raises
ValueError: in case of invalid argument for `weights`,
or invalid input shape.
|
waker.rs | use core::mem;
use core::ptr::NonNull;
use core::task::{RawWaker, RawWakerVTable, Waker};
use super::TaskHeader;
const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop);
unsafe fn clone(p: *const ()) -> RawWaker {
RawWaker::new(p, &VTABLE)
}
unsafe fn wake(p: *const ()) {
(*(p as *mut TaskHeader)).enqueue()
}
unsafe fn drop(_: *const ()) {
// nop
}
pub(crate) unsafe fn from_task(p: NonNull<TaskHeader>) -> Waker {
Waker::from_raw(RawWaker::new(p.as_ptr() as _, &VTABLE))
}
/// Get a task pointer from a waker.
///
/// This can used as an optimization in wait queues to store task pointers
/// (1 word) instead of full Wakers (2 words). This saves a bit of RAM and helps
/// avoid dynamic dispatch.
///
/// You can use the returned task pointer to wake the task with [`wake_task`](super::wake_task).
///
/// # Panics
///
/// Panics if the waker is not created by the Embassy executor.
pub unsafe fn task_from_waker(waker: &Waker) -> NonNull<TaskHeader> {
let hack: &WakerHack = mem::transmute(waker);
if hack.vtable != &VTABLE |
NonNull::new_unchecked(hack.data as *mut TaskHeader)
}
struct WakerHack {
data: *const (),
vtable: &'static RawWakerVTable,
}
| {
panic!("Found waker not created by the embassy executor.")
} |
opts.py | def build_preprocess_parser(parser):
preprocess_opts(parser)
return parser
def build_train_parser(parser):
model_opts(parser)
general_opts(parser)
train_opts(parser)
translate_opts(parser)
return parser
def build_test_parser(parser):
general_opts(parser)
translate_opts(parser)
return parser
def model_opts(parser):
# Embedding
group = parser.add_argument_group('Model - Embeddings')
group.add('--embedding_size', type=int, default=256,
help='Token embedding size for target')
group.add('--share_dec_weights', action='store_true',
help="Use a shared weight matrix for the input and "
"output word embeddings in the decoder.")
# Embedding features
group = parser.add_argument_group('Model - Embedding Features')
group.add('--feat_merge', '-feat_merge', type=str, default='concat',
choices=['concat', 'sum', 'mlp'],
help="Merge action for incorporating features embeddings. "
"Options [concat|sum|mlp].")
group.add('--feat_vec_size', '-feat_vec_size', type=int, default=-1,
help="If specified, feature embedding sizes "
"will be set to this. Otherwise, feat_vec_exponent "
"will be used.")
group.add('--feat_vec_exponent', '-feat_vec_exponent',
type=float, default=0.7,
help="If -feat_merge_size is not set, feature "
"embedding sizes will be set to N^feat_vec_exponent "
"where N is the number of values the feature takes.")
# Encoder
group = parser.add_argument_group('Model - Encoder')
group.add('--enc_rnn_type', type=str, default='LSTM', choices=['LSTM', 'GRU'],
help="Type of encoder RNN layer to use.")
group.add('--enc_layers', type=int, default=3,
help='Number of layers in the encoder')
group.add('--enc_rnn_size', type=int, default=512,
help="Size of encoder rnn hidden states.")
group.add('--brnn', action='store_true',
help="Whether to use bidirectional encoder.")
group.add('--enc_pooling', type=str, default='2',
help="The amount of pooling of audio encoder, "
"either the same amount of pooling across all layers "
"indicated by a single number, or different amounts of "
"pooling per layer separated by comma.")
group.add('--enc_dropout', type=float, default=0.0,
help="Dropout probability for encoder.")
# Decoder
group = parser.add_argument_group('Model - Decoder')
group.add('--dec_rnn_type', type=str, default='LSTM', choices=['LSTM', 'GRU'],
help="Type of decoder RNN layer to use.")
group.add('--dec_layers', type=int, default=2,
help='Number of layers in the decoder')
group.add('--dec_rnn_size', type=int, default=256,
help="Size of decoder rnn hidden states.")
group.add('--dec_dropout', type=float, default=0.0,
help="Dropout probability for decoder.")
group.add('--init_sched_sampling_rate', type=float, default=0.0,
help="Initial rate for scheduled sampling")
# Attention
group = parser.add_argument_group('Model - Attention')
group.add('--attention_type', type=str, default='general',
choices=['dot', 'general', 'mlp'],
help="The attention type to use: "
"dotprod or general (Luong) or MLP (Bahdanau)")
# Bridge
group = parser.add_argument_group('Model - Bridge')
group.add('--bridge_type', type=str, default='zero',
choices=['copy', 'mlp', 'zero'],
help="The bridge type to use between encoder and decoder.")
def preprocess_opts(parser):
# Data
group = parser.add_argument_group('Data')
group.add('--src_train', required=True, nargs='+',
help="Path(s) to the training source data")
group.add('--tgt_train', required=True, nargs='+',
help="Path(s) to the training target data")
group.add('--src_valid', required=True, nargs='+',
help="Path(s) to the validation source data")
group.add('--tgt_valid', required=True, nargs='+',
help="Path(s) to the validation target data")
group.add('--src_test', required=True, nargs='+',
help="Path(s) to the test source data")
group.add('--tgt_test', required=True, nargs='+',
help="Path(s) to the test target data")
group.add('--src_dir', default="",
help="Source directory for audio files.")
group.add('--save_dir', required=True,
help="Directory for saving the prepared data")
group.add('--shard_size', type=int, default=6000,
help="Divide src_corpus and tgt_corpus into "
"smaller multiple src_copus and tgt corpus files, then "
"build shards, each shard will have "
"opt.shard_size samples except last shard. "
"shard_size=0 means no segmentation "
"shard_size>0 means segment dataset into multiple shards, "
"each shard has shard_size samples")
# Vocab
group = parser.add_argument_group('Vocab')
group.add('--vocab', type=str, required=True,
help="File to be used for building vocabulary.")
group.add('--max_vocab_size', type=int, default=50000,
help="Maximum size of the vocabulary")
# Audio processing
group = parser.add_argument_group('Audio')
group.add('--sample_rate', type=int, default=16000,
help="Sample rate.")
group.add('--window_size', type=float, default=.02,
help="Window size for spectrogram in seconds.")
group.add('--window_stride', type=float, default=.01,
help="Window stride for spectrogram in seconds.")
group.add('--window', default='hamming',
help="Window type for spectrogram generation. "
"Passed to librosa as argument.")
group.add('--feat_type', default='mfcc', choices=['fbank', 'stft', 'mfcc'],
help="Type of audio features to be extracted")
group.add('--normalize_audio', action='store_true',
help="Whether to perform mean-variance normalization on features.")
def general_opts(parser):
|
def train_opts(parser):
# Initialization
group = parser.add_argument_group('Initialization')
group.add('--param_init', type=float, default=0.1,
help="Init parameters with uniform distribution "
"with support (-param_init, param_init). "
"Use 0 to not use initialization")
group.add('--param_init_glorot', action='store_true',
help="Init parameters with xavier_uniform.")
# Optimization
group = parser.add_argument_group('Optimization')
group.add('--train_batch_size', type=int, default=32,
help='Batch size for training')
group.add('--bucket_size', type=int, default=256,
help="Shuffle this many examples to reduce padding.")
group.add('--bptt', type=int, default=0,
help="Number of timesteps for truncated BPTT. Set to 0 to disable.")
group.add('--train_steps', type=int, default=100000,
help='Number of training steps')
group.add('--eval_steps', type=int, default=10000,
help='Perfom validation every X steps')
group.add('--shard_size', type=int, default=0,
help="Maximum batches of words in a sequence to run "
"the generator on in parallel. Higher is faster, but "
"uses more memory. Set to 0 to disable.")
group.add('--single_pass', action='store_true',
help="Make a single pass over the training dataset.")
group.add('--optim', default='sgd',
choices=['sgd', 'adagrad', 'adadelta', 'adam'],
help="Optimization method.")
group.add('--adagrad_accumulator_init', type=float, default=0,
help="Initializes the accumulator values in adagrad. "
"Mirrors the initial_accumulator_value option "
"in the tensorflow adagrad (use 0.1 for their default).")
group.add('--max_grad_norm', type=float, default=10,
help="If the norm of the gradient vector exceeds this, "
"renormalize it to have the norm equal to "
"max_grad_norm")
group.add('--adam_beta1', type=float, default=0.9,
help="The beta1 parameter used by Adam. "
"Almost without exception a value of 0.9 is used in "
"the literature, seemingly giving good results, "
"so we would discourage changing this value from "
"the default without due consideration.")
group.add('--adam_beta2', type=float, default=0.999,
help='The beta2 parameter used by Adam. '
'Typically a value of 0.999 is recommended, as this is '
'the value suggested by the original paper describing '
'Adam, and is also the value adopted in other frameworks '
'such as Tensorflow and Kerras, i.e. see: '
'https://www.tensorflow.org/api_docs/python/tf/train/Adam'
'Optimizer or '
'https://keras.io/optimizers/ . '
'Whereas recently the paper "Attention is All You Need" '
'suggested a value of 0.98 for beta2, this parameter may '
'not work well for normal models / default '
'baselines.')
group.add('--learning_rate', type=float, default=1.0,
help="Starting learning rate. "
"Recommended settings: sgd = 1, adagrad = 0.1, "
"adadelta = 1, adam = 0.001")
group.add('--learning_rate_decay', type=float, default=0.5,
help="If update_learning_rate, decay learning rate by "
"this much if steps have gone past "
"start_decay_steps")
group.add('--start_decay_steps', type=int, default=50000,
help="Start decaying every decay_steps after start_decay_steps")
group.add('--decay_steps', type=int, default=10000,
help="Decay every decay_steps")
group.add('--decay_method', type=str, default="none",
choices=['noam', 'noamwd', 'rsqrt', 'none'],
help="Use a custom decay rate.")
group.add('--warmup_steps', type=int, default=4000,
help="Number of warmup steps for custom decay.")
group = parser.add_argument_group('Logging')
group.add('--log_every', type=int, default=50,
help="Print stats at this interval.")
group.add("--tensorboard_dir", type=str, default="",
help="Log directory for Tensorboard. "
"This is also the name of the run.")
group.add("--save_dir", type=str, default="saved",
help="Directory for saving checkpoints.")
def translate_opts(parser):
group = parser.add_argument_group('Translation')
group.add('--eval_batch_size', type=int, default=32,
help='Batch size for evaluation')
group.add('--eval_split', choices=['train', 'valid', 'test'], default='test',
help='Split to be used for evaluation')
group.add('--n_best', type=int, default=1,
help='Number of hypotheses to return for each sample')
group.add('--min_length', type=int, default=0,
help='Minimum length of generated transcription')
group.add('--max_length', type=int, default=100,
help='Maximum length of generated transcription')
group.add('--ratio', type=float, default=0.,
help='If greater than 0, used for estimating transcription '
'length from length of encoded sequence')
group.add('--beam_size', type=int, default=8,
help='Size of beam during search')
group.add('--block_ngram_repeat', type=int, default=0,
help='Block hypotheses containing as many consecutive '
'repetitions of ngrams/tokens')
group.add('--excluded_toks', type=str, default='',
help='Comma-separated list of tokens not to be '
'blocked during decoding')
group.add('--out', type=str, default='',
help='File for writing generated hypotheses')
group.add('--verbose', action='store_true',
help='Print the best transcription as it is generated')
group.add('--attn_debug', action='store_true',
help='Print the attention heatmap for each sample')
| group = parser.add_argument_group('General')
group.add('--data', type=str, required=True,
help='Path prefix to .pt files generated by preprocess.py')
group.add('--checkpoint', type=str, default='',
help='Path to checkpoint of pretrained model')
group.add('--seed', type=int, default=1234,
help="Random seed used for the experiments reproducibility.") |
replicated_state.rs | use super::{
canister_state::CanisterState,
metadata_state::{IngressHistoryState, Stream, Streams, SystemMetadata},
};
use crate::{
bitcoin_state::{BitcoinState, BitcoinStateError},
canister_state::{
system_state::{push_input, CanisterOutputQueuesIterator},
ENFORCE_MESSAGE_MEMORY_USAGE,
},
metadata_state::StreamMap,
CanisterQueues,
};
use ic_base_types::PrincipalId;
use ic_btc_types_internal::{BitcoinAdapterRequestWrapper, BitcoinAdapterResponse};
use ic_error_types::{ErrorCode, UserError};
use ic_interfaces::{
execution_environment::CanisterOutOfCyclesError, messages::CanisterInputMessage,
};
use ic_registry_routing_table::RoutingTable;
use ic_registry_subnet_features::BitcoinFeature;
use ic_registry_subnet_type::SubnetType;
use ic_types::{
ingress::IngressStatus,
messages::{
is_subnet_message, CallbackId, MessageId, RequestOrResponse, Response, SignedIngressContent,
},
xnet::QueueId,
CanisterId, MemoryAllocation, NumBytes, QueueIndex, SubnetId, Time,
};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaChaRng;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// Input queue type: local or remote subnet.
#[derive(Clone, Copy, Eq, Debug, PartialEq)]
pub enum InputQueueType {
/// Local subnet input messages.
LocalSubnet,
/// Remote subnet input messages.
RemoteSubnet,
}
/// Next input queue: round-robin across local subnet; ingress; or remote subnet.
#[derive(Clone, Copy, Eq, Debug, PartialEq)]
pub enum NextInputQueue {
/// Local subnet input messages.
LocalSubnet,
/// Ingress messages.
Ingress,
/// Remote subnet input messages.
RemoteSubnet,
}
impl Default for NextInputQueue {
fn default() -> Self {
NextInputQueue::LocalSubnet
}
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug, Hash)]
pub enum StateError {
/// Message enqueuing failed due to no matching canister ID.
CanisterNotFound(CanisterId),
/// Message enqueuing failed due to full in/out queue.
QueueFull { capacity: usize },
/// Canister is stopped, not accepting any messages.
CanisterStopped(CanisterId),
/// Canister is stopping, only accepting responses.
CanisterStopping(CanisterId),
/// Canister is out of cycles.
CanisterOutOfCycles(CanisterOutOfCyclesError),
/// Canister state is invalid because of broken invariant.
InvariantBroken(String),
/// Message enqueuing failed due to calling an unknown subnet method.
UnknownSubnetMethod(String),
/// Response enqueuing failed due to not matching the expected response.
NonMatchingResponse {
err_str: String,
originator: CanisterId,
callback_id: CallbackId,
respondent: CanisterId,
},
/// Message enqueuing failed due to calling a subnet method with
/// an invalid payload.
InvalidSubnetPayload,
/// Message enqueuing would have caused the canister or subnet to run over
/// their memory limit.
OutOfMemory { requested: NumBytes, available: i64 },
/// An error that can be returned when manipulating the `BitcoinState`.
/// See `BitcoinStateError` for more information.
BitcoinStateError(BitcoinStateError),
}
/// Circular iterator that consumes messages from all canisters' and the
/// subnet's output queues. All messages that have not been explicitly popped
/// will remain in the state.
///
/// The iterator loops over the canisters (plus subnet) consuming one output
/// message from each in a round robin fashion. For each canister and the subnet
/// a circular iterator again ensures that messages are consumed from output
/// queues in a round robin fashion.
///
/// Additional operations compared to a standard iterator:
/// * peeking (returning a reference to the next message without consuming it);
/// and
/// * excluding whole queues from iteration while retaining their messages
/// (e.g. in order to efficiently implement per destination limits).
#[derive(Debug)]
struct OutputIterator<'a> {
/// Priority queue of non-empty canister iterators. The next message will be
/// popped / peeked from the first iterator.
canister_iterators: VecDeque<CanisterOutputQueuesIterator<'a>>,
/// Number of messages left in the iterator.
size: usize,
}
impl<'a> OutputIterator<'a> {
fn new(
canisters: &'a mut BTreeMap<CanisterId, CanisterState>,
subnet_queues: &'a mut CanisterQueues,
own_subnet_id: SubnetId,
seed: u64,
) -> Self {
let mut canister_iterators: VecDeque<_> = canisters
.iter_mut()
.map(|(owner, canister)| canister.system_state.output_into_iter(*owner))
.filter(|handle| !handle.is_empty())
.collect();
let mut rng = ChaChaRng::seed_from_u64(seed);
let rotation = rng.gen_range(0, canister_iterators.len().max(1));
canister_iterators.rotate_left(rotation as usize);
// Push the subnet queues in front in order to make sure that at least one
// system message is always routed as long as there is space for it.
let subnet_queues_iter = subnet_queues.output_into_iter(CanisterId::from(own_subnet_id));
if !subnet_queues_iter.is_empty() {
canister_iterators.push_front(subnet_queues_iter)
}
let size = canister_iterators.iter().map(|q| q.size_hint().0).sum();
OutputIterator {
canister_iterators,
size,
}
}
/// Computes the number of messages left in `queue_handles`.
///
/// Time complexity: O(N).
fn compute_size(queue_handles: &VecDeque<CanisterOutputQueuesIterator<'a>>) -> usize {
queue_handles.iter().map(|q| q.size_hint().0).sum()
}
}
impl std::iter::Iterator for OutputIterator<'_> {
type Item = (QueueId, QueueIndex, RequestOrResponse);
/// Pops a message from the next canister. If this was not the last message
/// for that canister, the canister iterator is moved to the back of the
/// iteration order.
fn next(&mut self) -> Option<Self::Item> {
if let Some(mut canister_iterator) = self.canister_iterators.pop_front() {
if let Some((queue_id, queue_index, msg)) = canister_iterator.next() {
self.size -= 1;
if !canister_iterator.is_empty() {
self.canister_iterators.push_back(canister_iterator);
}
debug_assert_eq!(Self::compute_size(&self.canister_iterators), self.size);
return Some((queue_id, queue_index, msg));
}
}
None
}
/// Returns the exact number of messages left in the iterator.
fn size_hint(&self) -> (usize, Option<usize>) {
(self.size, Some(self.size))
}
}
pub trait PeekableOutputIterator:
std::iter::Iterator<Item = (QueueId, QueueIndex, RequestOrResponse)>
{
/// Peeks into the iterator and returns a reference to the item `next`
/// would return.
fn peek(&self) -> Option<(QueueId, QueueIndex, Arc<RequestOrResponse>)>;
/// Permanently filters out from iteration the next queue (i.e. all messages
/// with the same sender and receiver as the next). The mesages are retained
/// in the output queue.
fn exclude_queue(&mut self);
}
impl PeekableOutputIterator for OutputIterator<'_> {
fn peek(&self) -> Option<(QueueId, QueueIndex, Arc<RequestOrResponse>)> {
self.canister_iterators.front().and_then(|it| it.peek())
}
fn exclude_queue(&mut self) {
if let Some(mut canister_iterator) = self.canister_iterators.pop_front() {
self.size -= canister_iterator.exclude_queue();
if !canister_iterator.is_empty() {
self.canister_iterators.push_front(canister_iterator);
}
debug_assert_eq!(Self::compute_size(&self.canister_iterators), self.size);
}
}
}
pub const LABEL_VALUE_CANISTER_NOT_FOUND: &str = "CanisterNotFound";
pub const LABEL_VALUE_QUEUE_FULL: &str = "QueueFull";
pub const LABEL_VALUE_CANISTER_STOPPED: &str = "CanisterStopped";
pub const LABEL_VALUE_CANISTER_STOPPING: &str = "CanisterStopping";
pub const LABEL_VALUE_CANISTER_OUT_OF_CYCLES: &str = "CanisterOutOfCycles";
pub const LABEL_VALUE_INVARIANT_BROKEN: &str = "InvariantBroken";
pub const LABEL_VALUE_UNKNOWN_SUBNET_METHOD: &str = "UnknownSubnetMethod";
pub const LABEL_VALUE_INVALID_RESPONSE: &str = "InvalidResponse";
pub const LABEL_VALUE_INVALID_SUBNET_PAYLOAD: &str = "InvalidSubnetPayload";
pub const LABEL_VALUE_OUT_OF_MEMORY: &str = "OutOfMemory";
pub const LABEL_VALUE_BITCOIN_STATE_ERROR: &str = "BitcoinStateError";
impl StateError {
/// Returns a string representation of the `StateError` variant name to be
/// used as a metric label value (e.g. `"QueueFull"`).
pub fn to_label_value(&self) -> &'static str {
match self {
StateError::CanisterNotFound(_) => LABEL_VALUE_CANISTER_NOT_FOUND,
StateError::QueueFull { .. } => LABEL_VALUE_QUEUE_FULL,
StateError::CanisterStopped(_) => LABEL_VALUE_CANISTER_STOPPED,
StateError::CanisterStopping(_) => LABEL_VALUE_CANISTER_STOPPING,
StateError::CanisterOutOfCycles(_) => LABEL_VALUE_CANISTER_OUT_OF_CYCLES,
StateError::InvariantBroken(_) => LABEL_VALUE_INVARIANT_BROKEN,
StateError::UnknownSubnetMethod(_) => LABEL_VALUE_UNKNOWN_SUBNET_METHOD,
StateError::NonMatchingResponse { .. } => LABEL_VALUE_INVALID_RESPONSE,
StateError::InvalidSubnetPayload => LABEL_VALUE_INVALID_SUBNET_PAYLOAD,
StateError::OutOfMemory { .. } => LABEL_VALUE_OUT_OF_MEMORY,
StateError::BitcoinStateError(_) => LABEL_VALUE_BITCOIN_STATE_ERROR,
}
}
}
impl std::error::Error for StateError {}
impl std::fmt::Display for StateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
StateError::CanisterNotFound(canister_id) => {
write!(f, "Canister {} not found", canister_id)
}
StateError::QueueFull { capacity } => {
write!(f, "Maximum queue capacity {} reached", capacity)
}
StateError::CanisterStopped(canister_id) => {
write!(f, "Canister {} is stopped", canister_id)
}
StateError::CanisterStopping(canister_id) => {
write!(f, "Canister {} is stopping", canister_id)
}
StateError::CanisterOutOfCycles(err) => write!(f, "{}", err),
StateError::InvariantBroken(err) => {
write!(f, "Invariant broken: {}", err)
}
StateError::UnknownSubnetMethod(method) => write!(
f,
"Cannot enqueue management message. Method {} is unknown.",
method
),
StateError::NonMatchingResponse {err_str, originator, callback_id, respondent} => write!(
f,
"Cannot enqueue response with callback id {} due to {} : originator => {}, respondent => {}",
callback_id, err_str, originator, respondent
),
StateError::InvalidSubnetPayload => write!(
f,
"Cannot enqueue management message. Candid payload is invalid."
),
StateError::OutOfMemory {
requested,
available,
} => write!(
f,
"Cannot enqueue message. Out of memory: requested {}, available {}",
requested, available
),
StateError::BitcoinStateError(error) => write!(f, "Bitcoin state error: {}", error),
}
}
}
/// ReplicatedState is the deterministic replicated state of the system.
/// Broadly speaking it consists of two parts: CanisterState used for canister
/// execution and SystemMetadata used for message routing and history queries.
//
// * We don't derive `Serialize` and `Deserialize` because these are handled by
// our OP layer.
// * We don't derive `Hash` because `ingress_history` is a Hashmap that doesn't
// derive `Hash`.
#[derive(Clone, Debug)]
pub struct ReplicatedState {
/// States of all canisters, indexed by canister ids.
pub canister_states: BTreeMap<CanisterId, CanisterState>,
/// Deterministic processing metadata.
pub metadata: SystemMetadata,
/// Queues for holding messages sent/received by the subnet.
// Must remain private.
subnet_queues: CanisterQueues,
/// Queue for holding responses arriving from Consensus.
///
/// Responses from consensus are to be processed each round.
/// The queue is, therefore, emptied at the end of every round.
// TODO(EXE-109): Move this queue into `subnet_queues`
pub consensus_queue: Vec<Response>,
pub root: PathBuf,
bitcoin: BitcoinState,
}
// We use custom impl of PartialEq because state root is not part of identity.
impl PartialEq for ReplicatedState {
fn eq(&self, rhs: &Self) -> bool {
(
&self.bitcoin,
&self.canister_states,
&self.metadata,
&self.subnet_queues,
&self.consensus_queue,
) == (
&rhs.bitcoin,
&rhs.canister_states,
&rhs.metadata,
&rhs.subnet_queues,
&rhs.consensus_queue,
)
}
}
impl ReplicatedState {
/// Creates a new empty node state.
pub fn new_rooted_at(
own_subnet_id: SubnetId,
own_subnet_type: SubnetType,
root: PathBuf,
) -> ReplicatedState {
ReplicatedState {
root,
canister_states: BTreeMap::new(),
metadata: SystemMetadata::new(own_subnet_id, own_subnet_type),
subnet_queues: CanisterQueues::default(),
consensus_queue: Vec::new(),
bitcoin: BitcoinState::default(),
}
}
pub fn new_from_checkpoint(
canister_states: BTreeMap<CanisterId, CanisterState>,
metadata: SystemMetadata,
subnet_queues: CanisterQueues,
consensus_queue: Vec<Response>,
bitcoin: BitcoinState,
root: PathBuf,
) -> Self {
let mut res = Self {
canister_states,
metadata,
subnet_queues,
consensus_queue,
root,
bitcoin,
};
res.update_stream_responses_size_bytes();
res
}
pub fn path(&self) -> &Path {
&self.root
}
pub fn canister_state(&self, canister_id: &CanisterId) -> Option<&CanisterState> {
self.canister_states.get(canister_id)
}
pub fn canister_state_mut(&mut self, canister_id: &CanisterId) -> Option<&mut CanisterState> {
self.canister_states.get_mut(canister_id)
}
pub fn take_canister_state(&mut self, canister_id: &CanisterId) -> Option<CanisterState> {
self.canister_states.remove(canister_id)
}
pub fn take_canister_states(&mut self) -> BTreeMap<CanisterId, CanisterState> {
std::mem::take(&mut self.canister_states)
}
pub fn routing_table(&self) -> Arc<RoutingTable> {
Arc::clone(&self.metadata.network_topology.routing_table)
}
/// Insert the canister state into the replicated state. If a canister
/// already exists for the given canister id, it will be replaced. It is the
/// responsibility of the caller of this function to ensure that any
/// relevant state associated with the older canister state are properly
/// cleaned up.
pub fn put_canister_state(&mut self, canister_state: CanisterState) {
self.canister_states
.insert(canister_state.canister_id(), canister_state);
}
/// Replaces the content of `self.canister_states` with the provided `canisters`.
///
/// Panics if `self.canister_states` was not empty. The intended use is to
/// call `put_canister_states()` after `take_canister_states()`, with no
/// other canister-related calls in-between, in order to prevent concurrent
/// mutations from replacing each other.
pub fn put_canister_states(&mut self, canisters: BTreeMap<CanisterId, CanisterState>) {
assert!(self.canister_states.is_empty()); |
/// Returns an iterator over canister states, ordered by canister ID.
pub fn canisters_iter(
&self,
) -> std::collections::btree_map::Values<'_, CanisterId, CanisterState> {
self.canister_states.values()
}
/// Returns a mutable iterator over canister states, ordered by canister ID.
pub fn canisters_iter_mut(
&mut self,
) -> std::collections::btree_map::ValuesMut<'_, CanisterId, CanisterState> {
self.canister_states.values_mut()
}
// Loads a fresh version of the canister from the state and ensures that it
// has a call context manager i.e. it is not stopped.
pub fn get_active_canister(
&self,
canister_id: &CanisterId,
) -> Result<CanisterState, UserError> {
let canister = self.canister_state(canister_id).ok_or_else(|| {
UserError::new(
ErrorCode::CanisterNotFound,
format!("Canister {} not found", canister_id),
)
})?;
if canister.system_state.call_context_manager().is_none() {
Err(UserError::new(
ErrorCode::CanisterStopped,
format!(
"Canister {} is stopped and therefore does not have a CallContextManager",
canister.canister_id()
),
))
} else {
Ok(canister.clone())
}
}
pub fn system_metadata(&self) -> &SystemMetadata {
&self.metadata
}
pub fn set_system_metadata(&mut self, metadata: SystemMetadata) {
self.metadata = metadata;
}
pub fn get_ingress_status(&self, message_id: &MessageId) -> IngressStatus {
self.metadata
.ingress_history
.get(message_id)
.cloned()
.unwrap_or(IngressStatus::Unknown)
}
pub fn get_ingress_history(&self) -> IngressHistoryState {
self.metadata.ingress_history.clone()
}
/// Sets the `status` for `message_id` in the ingress history. It will
/// be ensured that the cumulative payload size of statuses in the
/// ingress history will be below or equal to `ingress_memory_capacity`
/// by transitioning `Completed` and `Failed` statuses to `Done` from
/// oldest to newest in case inserting `status` pushes the memory
/// consumption over the bound.
pub fn set_ingress_status(
&mut self,
message_id: MessageId,
status: IngressStatus,
ingress_memory_capacity: NumBytes,
) {
self.metadata.ingress_history.insert(
message_id,
status,
self.time(),
ingress_memory_capacity,
);
}
/// Prunes ingress history statuses with a pruning time older than
/// `self.time()`.
pub fn prune_ingress_history(&mut self) {
self.metadata.ingress_history.prune(self.time());
}
/// Returns all subnets for which a stream is available.
pub fn subnets_with_available_streams(&self) -> Vec<SubnetId> {
self.metadata.streams.keys().cloned().collect()
}
/// Retrieves a reference to the stream from this subnet to the destination
/// subnet, if such a stream exists.
pub fn get_stream(&self, destination_subnet_id: &SubnetId) -> Option<&Stream> {
self.metadata.streams.get(destination_subnet_id)
}
/// Returns the sum of reserved compute allocations of all currently
/// available canisters.
pub fn total_compute_allocation(&self) -> u64 {
self.canisters_iter()
.map(|canister| canister.scheduler_state.compute_allocation.as_percent())
.sum()
}
/// Returns the total memory taken by canisters in bytes.
///
/// This accounts for the canister memory reservation, where specified; and
/// the actual canister memory usage, where no explicit memory reservation
/// has been made. Canister message memory usage is included for application
/// subnets only.
pub fn total_memory_taken(&self) -> NumBytes {
self.total_memory_taken_impl(self.metadata.own_subnet_type != SubnetType::System)
}
/// Returns the total memory taken by canisters in bytes, always including
/// canister messages (regardless of subnet type).
///
/// This accounts for the canister memory reservation, where specified; and
/// the actual canister memory usage, where no explicit memory reservation
/// has been made.
pub fn total_memory_taken_with_messages(&self) -> NumBytes {
self.total_memory_taken_impl(true)
}
/// Common implementation for `total_memory_taken()` and
/// `total_memory_taken_with_messages()`.
fn total_memory_taken_impl(&self, with_messages: bool) -> NumBytes {
let mut memory_taken = self
.canisters_iter()
.map(|canister| match canister.memory_allocation() {
MemoryAllocation::Reserved(bytes) => bytes,
MemoryAllocation::BestEffort => canister.memory_usage_impl(with_messages),
})
.sum();
if ENFORCE_MESSAGE_MEMORY_USAGE && with_messages {
memory_taken += (self.subnet_queues.memory_usage() as u64).into();
}
memory_taken
}
/// Returns the total memory taken by canister messages in bytes.
pub fn message_memory_taken(&self) -> NumBytes {
if ENFORCE_MESSAGE_MEMORY_USAGE {
NumBytes::new(self.subnet_queues.memory_usage() as u64)
+ self
.canisters_iter()
.map(|canister| canister.system_state.memory_usage())
.sum()
} else {
0.into()
}
}
/// Returns the total memory taken by the ingress history in bytes.
pub fn total_ingress_memory_taken(&self) -> NumBytes {
self.metadata.ingress_history.memory_usage()
}
/// Returns the `SubnetId` hosting the given `principal_id` (canister or
/// subnet).
pub fn find_subnet_id(&self, principal_id: PrincipalId) -> Result<SubnetId, UserError> {
let subnet_id = self
.metadata
.network_topology
.routing_table
.route(principal_id);
match subnet_id {
None => Err(UserError::new(
ErrorCode::SubnetNotFound,
format!("Could not find subnetId given principalId {}", principal_id),
)),
Some(subnet_id) => Ok(subnet_id),
}
}
/// Pushes a `RequestOrResponse` into the induction pool (canister or subnet
/// input queue).
///
/// The messages from the same subnet get pushed into the local subnet
/// queue, while the messages form the other subnets get pushed to the inter
/// subnet queues.
///
/// On failure (queue full, canister not found, out of memory), returns the
/// corresponding error and the original message.
///
/// Updates `subnet_available_memory` to reflect any change in memory usage.
pub fn push_input(
&mut self,
index: QueueIndex,
msg: RequestOrResponse,
max_canister_memory_size: NumBytes,
subnet_available_memory: &mut i64,
) -> Result<(), (StateError, RequestOrResponse)> {
let own_subnet_type = self.metadata.own_subnet_type;
let input_queue_type = if msg.sender().get_ref() == self.metadata.own_subnet_id.get_ref()
|| self.canister_states.contains_key(&msg.sender())
{
InputQueueType::LocalSubnet
} else {
InputQueueType::RemoteSubnet
};
match self.canister_state_mut(&msg.receiver()) {
Some(receiver_canister) => receiver_canister.push_input(
index,
msg,
max_canister_memory_size,
subnet_available_memory,
own_subnet_type,
input_queue_type,
),
None => {
let subnet_id = self.metadata.own_subnet_id.get_ref();
if msg.receiver().get_ref() == subnet_id {
push_input(
&mut self.subnet_queues,
index,
msg,
// No canister limit, so pass the subnet limit twice.
*subnet_available_memory,
subnet_available_memory,
own_subnet_type,
input_queue_type,
)
} else {
Err((StateError::CanisterNotFound(msg.receiver()), msg))
}
}
}
}
/// Pushes an ingress message into the induction pool (canister or subnet
/// ingress queue).
pub fn push_ingress(&mut self, msg: SignedIngressContent) -> Result<(), StateError> {
if is_subnet_message(&msg, self.metadata.own_subnet_id) {
self.subnet_queues.push_ingress(msg.into());
} else {
let canister_id = msg.canister_id();
let canister = match self.canister_states.get_mut(&canister_id) {
Some(canister) => canister,
None => return Err(StateError::CanisterNotFound(canister_id)),
};
canister.push_ingress(msg.into());
}
Ok(())
}
/// Extracts the next inter-canister or ingress message (round-robin) from
/// `self.subnet_queues`.
pub fn pop_subnet_input(&mut self) -> Option<CanisterInputMessage> {
self.subnet_queues.pop_input()
}
/// Pushes a `Response` type message into the relevant subnet output queue.
/// The protocol should have already reserved a slot, so this cannot fail.
///
/// # Panics
///
/// Panics if the queue does not already exist or there is no reserved slot
/// to push the `Response` into.
pub fn push_subnet_output_response(&mut self, msg: Response) {
self.subnet_queues.push_output_response(msg)
}
/// Returns a circular iterator that consumes messages from all canisters'
/// and the subnet's output queues.
///
/// The iterator loops over the canisters (plus subnet) consuming one output
/// message from each in a round robin fashion. For each canister and the
/// subnet a circular iterator again ensures that messages are consumed
/// from output queues in a round robin fashion.
///
/// The iterator is peekable so that one can obtain a reference to the next
/// message. Calling `next` will consume the message and remove it from the
/// state. All messages that have not been explicitly consumed will remain
/// in the state.
pub fn output_into_iter(&mut self) -> impl PeekableOutputIterator + '_ {
let own_subnet_id = self.metadata.own_subnet_id;
let time = self.metadata.time();
OutputIterator::new(
&mut self.canister_states,
&mut self.subnet_queues,
own_subnet_id,
// We seed the output iterator with the time. We can do this because
// we don't need unpredictability of the rotation, and we accept that
// in case the same time is passed in two consecutive batches we
// rotate by the same amount for now.
time.as_nanos_since_unix_epoch(),
)
}
pub fn time(&self) -> Time {
self.metadata.time()
}
/// Returns an immutable reference to `self.subnet_queues`.
pub fn subnet_queues(&self) -> &CanisterQueues {
&self.subnet_queues
}
/// Updates the byte size of responses in streams for each canister.
fn update_stream_responses_size_bytes(&mut self) {
let stream_responses_size_bytes = self.metadata.streams.responses_size_bytes();
for (canister_id, canister_state) in self.canister_states.iter_mut() {
canister_state.set_stream_responses_size_bytes(
stream_responses_size_bytes
.get(canister_id)
.cloned()
.unwrap_or_default(),
)
}
}
/// Returns the number of canisters in this `ReplicatedState`.
pub fn num_canisters(&self) -> usize {
self.canister_states.len()
}
/// Returns a reference to the `BitcoinState`.
pub fn bitcoin(&self) -> &BitcoinState {
&self.bitcoin
}
/// Returns a mutable reference to the `BitcoinState`.
pub fn bitcoin_mut(&mut self) -> &mut BitcoinState {
&mut self.bitcoin
}
/// Pushes a request onto the testnet `BitcoinState` iff the bitcoin testnet
/// feature is enabled and returns a `StateError` otherwise.
///
/// See documentation of `BitcoinState::push_request` for more information.
// TODO(EXC-1097): Remove this method as it isn't being used in production.
pub fn push_request_bitcoin(
&mut self,
request: BitcoinAdapterRequestWrapper,
) -> Result<(), StateError> {
match self.metadata.own_subnet_features.bitcoin_testnet() {
BitcoinFeature::Enabled => self
.bitcoin
.adapter_queues
.push_request(request)
.map_err(StateError::BitcoinStateError),
BitcoinFeature::Paused => Err(StateError::BitcoinStateError(
BitcoinStateError::TestnetFeatureNotEnabled,
)),
BitcoinFeature::Disabled => Err(StateError::BitcoinStateError(
BitcoinStateError::TestnetFeatureNotEnabled,
)),
}
}
/// Pushes a response from the Bitcoin Adapter to the testnet `BitcoinState`
/// iff the bitcoin testnet feature is not disabled and returns a `StateError`
/// otherwise.
///
/// See documentation of `BitcoinState::push_response` for more information.
pub fn push_response_bitcoin(
&mut self,
response: BitcoinAdapterResponse,
) -> Result<(), StateError> {
match self.metadata.own_subnet_features.bitcoin_testnet() {
BitcoinFeature::Enabled => self
.bitcoin
.push_response(response)
.map_err(StateError::BitcoinStateError),
BitcoinFeature::Paused => self
.bitcoin
.push_response(response)
.map_err(StateError::BitcoinStateError),
BitcoinFeature::Disabled => Err(StateError::BitcoinStateError(
BitcoinStateError::TestnetFeatureNotEnabled,
)),
}
}
pub fn take_bitcoin_state(&mut self) -> BitcoinState {
std::mem::take(&mut self.bitcoin)
}
pub fn put_bitcoin_state(&mut self, bitcoin: BitcoinState) {
self.bitcoin = bitcoin;
}
}
/// A trait exposing `ReplicatedState` functionality for the exclusive use of
/// Message Routing.
pub trait ReplicatedStateMessageRouting {
/// Returns a reference to the streams.
fn streams(&self) -> &StreamMap;
/// Removes the streams from this `ReplicatedState`.
fn take_streams(&mut self) -> Streams;
/// Atomically replaces the streams.
fn put_streams(&mut self, streams: Streams);
}
impl ReplicatedStateMessageRouting for ReplicatedState {
fn streams(&self) -> &StreamMap {
self.metadata.streams.streams()
}
fn take_streams(&mut self) -> Streams {
std::mem::take(Arc::make_mut(&mut self.metadata.streams))
}
fn put_streams(&mut self, streams: Streams) {
// Should never replace a non-empty Streams via `put_streams()`.
assert!(self.metadata.streams.streams().is_empty());
*Arc::make_mut(&mut self.metadata.streams) = streams;
self.update_stream_responses_size_bytes();
}
}
pub mod testing {
use super::*;
use crate::{metadata_state::testing::StreamsTesting, testing::CanisterQueuesTesting};
/// Exposes `ReplicatedState` internals for use in other crates' unit tests.
pub trait ReplicatedStateTesting {
/// Testing only: Returns a reference to `self.subnet_queues`
fn subnet_queues(&self) -> &CanisterQueues;
/// Testing only: Returns a mutable reference to `self.subnet_queues`.
fn subnet_queues_mut(&mut self) -> &mut CanisterQueues;
/// Testing only: Replaces `self.subnet_queues` with `subnet_queues`
fn put_subnet_queues(&mut self, subnet_queues: CanisterQueues);
/// Testing only: Replaces `SystemMetadata::streams` with the provided
/// ones.
fn with_streams(&mut self, streams: StreamMap);
/// Testing only: Modifies `SystemMetadata::streams` by applying the
/// provided function.
fn modify_streams<F: FnOnce(&mut StreamMap)>(&mut self, f: F);
/// Testing only: Returns the number of messages across all canister and
/// subnet output queues.
fn output_message_count(&self) -> usize;
}
impl ReplicatedStateTesting for ReplicatedState {
fn subnet_queues(&self) -> &CanisterQueues {
&self.subnet_queues
}
fn subnet_queues_mut(&mut self) -> &mut CanisterQueues {
&mut self.subnet_queues
}
fn put_subnet_queues(&mut self, subnet_queues: CanisterQueues) {
self.subnet_queues = subnet_queues;
}
fn with_streams(&mut self, streams: StreamMap) {
self.modify_streams(|streamz| *streamz = streams);
}
fn modify_streams<F: FnOnce(&mut StreamMap)>(&mut self, f: F) {
let mut streams = self.take_streams();
streams.modify_streams(f);
self.put_streams(streams);
}
fn output_message_count(&self) -> usize {
self.canister_states
.values()
.map(|canister| canister.system_state.queues().output_message_count())
.sum::<usize>()
+ self.subnet_queues.output_message_count()
}
}
} | self.canister_states = canisters;
} |
anova.py | import numpy as np
from scipy.stats import f
# Does analysis of variance for a number of sets x.
# Each set in x is an array containing mean, variance
# and number [mean, var, n].
def anova(x):
| mean = np.mean(x[:, 0]) # overall mean
n = np.sum(x[:, 2]) # total N
r = len(x) # number of sets
ssb = 0.
for i in range(r): # sum of squares between sets
ssb += x[i, 2] * (x[i, 0] - mean)**2
ssw = 0.
for i in range(r): # sum of squares within sets
ssw += (x[i, 2] - 1) * x[i, 1]
fs = (ssb / (r - 1)) / (ssw / (n - r))
dfn, dfd = r - 1, n - r # degrees of freedom
p = f.cdf(fs, dfn, dfd) # P-value from F-distribution
return fs, p |
|
route.py | # -*- coding: UTF8
'''
Created on 13.07.2015
@author: mEDI
'''
from elite.system import system as elitesystem
#from elite.rares import rares as eliterares
# from elite.route import route as eliteroute
class route(object):
'''
classdocs
'''
#__slots__ = ["bla"]
#bla =1
maxHops = None
maxJumpDistance = None
maxDeep = None
# die kürzeste route is nicht die beste wegen den optimalen preisen bei > 150ly
systemID = None
_before = None
# _initSystem = None # startsystem
initSystem = None # startsystem
possibleSystems = []
_raresInSystem = None
_availableSystemList = None
_sellDone = None
starDist = None
deep = 1
_hopsFromBefore = None
_dist = None # distance to before system
mydb = None
rares = None
system = None
def __init__(self, mydb, before=None, maxDeep=None, maxJumpDistance=None, maxHops=None):
# super(route, self).__init__()
self.mydb = mydb
self.possibleSystems = []
self._before = before
if before:
self.initSystem = before.initSystem
self.system = self.initSystem.system
self.maxHops = self.initSystem.maxHops
self.maxDeep = self.initSystem.maxDeep
self.maxJumpDistance = self.initSystem.maxJumpDistance
# self.rares = before.rares
else:
self.system = elitesystem(self.mydb)
self.maxDeep = maxDeep
self.maxHops = maxHops
self.maxJumpDistance = maxJumpDistance
# self.rares = eliterares(con)
def addPossibleSystems(self, systemID, dist, startdist, systemList):
# def addPossibleSystems(self, system, dist, rarelist):
newroute = route(self.mydb, self)
newroute._availableSystemList = systemList
newroute._dist = dist
newroute.systemID = systemID
newroute.starDist = startdist
newroute.deep = self.deep + 1
newroute._hopsFromBefore = int(round((dist / self.maxJumpDistance) + 0.5))
# new = {"System":system, "dist":dist, "rareslist":rarelist, "nextroute":route(self.con)}
self.possibleSystems.append(newroute)
def setMaxHops(self, hops):
self.maxHops = hops
def setmaxJumpDistance(self, dist):
self.maxJumpDistance = dist
def calcRoutingDeep(self):
MaxDeep = self.deep
for nextsystem in self.possibleSystems:
nMaxDeep = nextsystem.calcRoutingDeep()
if nMaxDeep > MaxDeep:
MaxDeep = nMaxDeep
return MaxDeep
def getLongRouting(self, maxdeep, dist, totalStartDist, totalHops, systems=[]):
systems.append(self.systemID)
for nextsystem in self.possibleSystems:
if nextsystem.deep >= maxdeep:
print("system:%s -> %s deep: %d dist:%d totalStarDist:%d hops:%d" % (systems, self.systemID, nextsystem.deep, nextsystem._dist + dist, nextsystem.starDist + totalStartDist, nextsystem._hopsFromBefore + totalHops))
nextsystem.getLongRouting(maxdeep, nextsystem._dist + dist, nextsystem.starDist + totalStartDist, nextsystem._hopsFromBefore + totalHops, systems)
systems.pop()
def getMinHops(self, maxdeep, totalHops=0):
minHops = None
for nextsystem in self.possibleSystems:
if nextsystem.deep >= maxdeep:
if minHops is None or minHops > nextsystem._hopsFromBefore + totalHops:
minHops = nextsystem._hopsFromBefore + totalHops
ret = nextsystem.getMinHops(maxdeep, nextsystem._hopsFromBefore + totalHops)
if ret and (minHops is None or minHops > ret):
minHops = ret
return minHops
def calcRouteSum(self):
totalSum = 1
for nextsystem in self.possibleSystems:
totalSum += nextsystem.calcRouteSum()
return totalSum
def getMinStarDist(self, maxdeep, starDist=0):
minStartDist = None
for nextsystem in self.possibleSystems:
if nextsystem.deep >= maxdeep:
if minStartDist is None or minStartDist > nextsystem.starDist + starDist:
minStartDist = nextsystem.starDist + starDist
ret = nextsystem.getMinStarDist(maxdeep, nextsystem.starDist + starDist)
if ret and (minStartDist is None or minStartDist > ret):
minStartDist = ret
return minStartDist
def getMinDistFromBest(self, maxdeep, dist=0, totalStartDist=0, totalHops=0, minHops=None, minStardist=None):
# first loop calculate optimal data
if minHops is None:
minHops = self.getMinHops(maxdeep)
if minStardist is None:
minStardist = self.getMinStarDist(maxdeep)
minDist = None
for nextsystem in self.possibleSystems:
if nextsystem.deep == maxdeep and nextsystem._hopsFromBefore + totalHops == minHops and nextsystem.starDist + totalStartDist == minStardist:
if minDist is None or minDist > nextsystem._dist + dist:
minDist = nextsystem._dist + dist
ret = nextsystem.getMinDistFromBest(maxdeep, nextsystem._dist + dist, nextsystem.starDist + totalStartDist, nextsystem._hopsFromBefore + totalHops, minHops, minStardist)
if ret and (minDist is None or minDist > ret):
minDist = ret
return minDist
def getBestRoute(self, maxdeep, dist=0, totalStartDist=0, totalHops=0, minHops=None, minStardist=None, minDist=None):
# first loop calculate optimal data
if minHops is None:
minHops = self.getMinHops(maxdeep)
if minStardist is None:
minStardist = self.getMinStarDist(maxdeep)
if minDist is None:
minDist = self.getMinDistFromBest(maxdeep, 0, 0, 0, minHops, minStardist)
# systems.append(self)
for nextsystem in self.possibleSystems:
if nextsystem and nextsystem.deep == maxdeep and nextsystem._hopsFromBefore + totalHops == minHops and nextsystem.starDist + totalStartDist == minStardist and minDist == nextsystem._dist + dist:
| before = nextsystem
systems = []
while before:
systems.append(before)
before = before._before
systems.reverse()
return systems
break
res = nextsystem.getBestRoute(maxdeep, nextsystem._dist + dist, nextsystem.starDist + totalStartDist, nextsystem._hopsFromBefore + totalHops, minHops, minStardist, minDist)
if res :
#print(res)
return res
def getAllRoutes(self, maxdeep):
routesList = []
def listWorker(curSystem):
if curSystem.deep == maxdeep:
routesList.append(curSystem)
return
for nextsys in curSystem.possibleSystems:
listWorker(nextsys)
listWorker(self.initSystem)
return routesList
def getSystemsFromRoute(self):
before = self
systems = []
while before:
systems.append(before)
before = before._before
systems.reverse()
return systems
def getStardistanceFromRoute(self):
before = self
distance = 0
while before:
if before.starDist:
distance += before.starDist
before = before._before
return distance
def calcRoutenRecrusion(self, slowMode):
# self.queueLock.acquire()
if self.deep+1 >= self.maxDeep:
return
for nextsystem in self.possibleSystems:
nextsystem.calcAllRoutesFromSystem( slowMode)
def testExistRoute(self, system, currentRoute):
# testen ob alle systeme der route schon einmal in einer anderen kombination verwendet wurden
# recursive rareroute
count = len(currentRoute)+1
#if count == 1: return
def listWorker(curSystem, count):
if curSystem.systemID in currentRoute:
count -= 1
elif curSystem.systemID == system:
count -= 1
#print(count)
if count == 0:
# print(system, curSystem.systemID ,currentRoute)
# allow other routes to me drop only extaxt ends to me
if curSystem.systemID == system:
return True
return
for nextsys in curSystem.possibleSystems:
if listWorker(nextsys, count) == True:
return True
# print(self.initSystem)
return listWorker(self.initSystem, count)
def calcAllRoutesFromSystem(self, slowMode=False):
if len(self._availableSystemList) == 0: return
maxDistance = self.maxHops * self.maxJumpDistance
#print(len(self._availableSystemList), self._availableSystemList)
systems = self.system.getSystemsInDistance(self.systemID, maxDistance, self._availableSystemList)
#=======================================================================
# reverse=True long routes first sell more items
# reverse=False short routes first sell not all items
# only in slow mod no difference
#=====================================================================
currentRoute = []
if slowMode != True:
systems = sorted(systems, key=lambda system: system["dist"], reverse=True)
# build current routelist
currentRoute.append(self.systemID)
before = self._before
while before:
currentRoute.append(before.systemID)
before = before._before
for system in systems:
# print(system)
nextSystemlist = self._availableSystemList[:]
#nextSystemlist = []
for listitem in nextSystemlist:
if listitem[0] == system["System"]:
stardist = listitem[1]
nextSystemlist.remove(listitem)
break
if stardist == None:
stardist = 0
if slowMode == True:
self.addPossibleSystems(system["System"], system["dist"], stardist, nextSystemlist)
else:
if self.testExistRoute(system["System"], currentRoute) != True:
#if True:
self.addPossibleSystems(system["System"], system["dist"], stardist, nextSystemlist)
# self.addPossibleSystems(system["System"], system["dist"], newrareslist)
currentRoute = []
self._availableSystemList = []
nextSystemlist = []
systems = []
self.calcRoutenRecrusion(slowMode)
# return myRaresRoute |
#print("best system: %s deep: %d dist:%d totalStarDist:%d hops:%d" % ( self.systemID, nextsystem.deep, nextsystem._dist + dist, nextsystem.starDist + totalStartDist, nextsystem._hopsFromBefore + totalHops))
|
grids.py | import logging
import math
from json import dumps, loads
from typing import Dict, List, Optional
from markupsafe import escape
from sqlalchemy.sql.expression import and_, false, func, null, or_, true
from galaxy.model.item_attrs import get_foreign_key, UsesAnnotations, UsesItemRatings
from galaxy.util import restore_text, sanitize_text, unicodify
from galaxy.web.framework import decorators, url_for
log = logging.getLogger(__name__)
class GridColumn:
def __init__(self, label, key=None, model_class=None, method=None, format=None,
link=None, attach_popup=False, visible=True, nowrap=False,
# Valid values for filterable are ['standard', 'advanced', None]
filterable=None, sortable=True, label_id_prefix=None, target=None,
delayed=False):
"""Create a grid column."""
self.label = label
self.key = key
self.model_class = model_class
self.method = method
self.format = format
self.link = link
self.target = target
self.nowrap = nowrap
self.attach_popup = attach_popup
self.visible = visible
self.filterable = filterable
self.delayed = delayed
# Column must have a key to be sortable.
self.sortable = (self.key is not None and sortable)
self.label_id_prefix = label_id_prefix or ''
def get_value(self, trans, grid, item):
if self.method:
value = getattr(grid, self.method)(trans, item)
elif self.key and hasattr(item, self.key):
value = getattr(item, self.key)
else:
value = None
if self.format:
value = self.format(value)
return escape(unicodify(value))
def get_link(self, trans, grid, item):
if self.link and self.link(item):
return self.link(item)
return None
def filter(self, trans, user, query, column_filter):
""" Modify query to reflect the column filter. """
if column_filter == "All":
pass
if column_filter == "True":
query = query.filter_by(**{self.key: True})
elif column_filter == "False":
query = query.filter_by(**{self.key: False})
return query
def get_accepted_filters(self):
""" Returns a list of accepted filters for this column. """
accepted_filters_vals = ["False", "True", "All"]
accepted_filters = []
for val in accepted_filters_vals:
args = {self.key: val}
accepted_filters.append(GridColumnFilter(val, args))
return accepted_filters
def sort(self, trans, query, ascending, column_name=None):
"""Sort query using this column."""
if column_name is None:
column_name = self.key
column = self.model_class.table.c.get(column_name)
if column is None:
column = getattr(self.model_class, column_name)
if ascending:
query = query.order_by(column.asc())
else:
query = query.order_by(column.desc())
return query
class ReverseSortColumn(GridColumn):
""" Column that reverses sorting; this is useful when the natural sort is descending. """
def sort(self, trans, query, ascending, column_name=None):
return GridColumn.sort(self, trans, query, (not ascending), column_name=column_name)
class TextColumn(GridColumn):
""" Generic column that employs freetext and, hence, supports freetext, case-independent filtering. """
def filter(self, trans, user, query, column_filter):
""" Modify query to filter using free text, case independence. """
if column_filter == "All":
pass
elif column_filter:
query = query.filter(self.get_filter(trans, user, column_filter))
return query
def get_filter(self, trans, user, column_filter):
""" Returns a SQLAlchemy criterion derived from column_filter. """
if isinstance(column_filter, str):
return self.get_single_filter(user, column_filter)
elif isinstance(column_filter, list):
clause_list = []
for filter in column_filter:
clause_list.append(self.get_single_filter(user, filter))
return and_(*clause_list)
def get_single_filter(self, user, a_filter):
"""
Returns a SQLAlchemy criterion derived for a single filter. Single filter
is the most basic filter--usually a string--and cannot be a list.
"""
# Queries that include table joins cannot guarantee that table column names will be
# unique, so check to see if a_filter is of type <TableName>.<ColumnName>.
if self.key.find('.') > -1:
a_key = self.key.split('.')[1]
else:
a_key = self.key
model_class_key_field = getattr(self.model_class, a_key)
return func.lower(model_class_key_field).like("%" + a_filter.lower() + "%")
def sort(self, trans, query, ascending, column_name=None):
"""Sort column using case-insensitive alphabetical sorting."""
if column_name is None:
column_name = self.key
if ascending:
query = query.order_by(func.lower(self.model_class.table.c.get(column_name)).asc())
else:
query = query.order_by(func.lower(self.model_class.table.c.get(column_name)).desc())
return query
class DateTimeColumn(TextColumn):
def sort(self, trans, query, ascending, column_name=None):
"""Sort query using this column."""
return GridColumn.sort(self, trans, query, ascending, column_name=column_name)
class BooleanColumn(TextColumn):
def sort(self, trans, query, ascending, column_name=None):
"""Sort query using this column."""
return GridColumn.sort(self, trans, query, ascending, column_name=column_name)
def get_single_filter(self, user, a_filter):
if self.key.find('.') > -1:
a_key = self.key.split('.')[1]
else:
a_key = self.key
model_class_key_field = getattr(self.model_class, a_key)
return model_class_key_field == a_filter
class IntegerColumn(TextColumn):
"""
Integer column that employs freetext, but checks that the text is an integer,
so support filtering on integer values.
IMPORTANT NOTE: grids that use this column type should not include the column
in the cols_to_filter list of MulticolFilterColumn ( i.e., searching on this
column type should not be performed in the grid's standard search - it won't
throw exceptions, but it also will not find what you're looking for ). Grids
that search on this column should use 'filterable="advanced"' so that searching
is only performed in the advanced search component, restricting the search to
the specific column.
This is useful for searching on object ids or other integer columns. See the
JobIdColumn column in the SpecifiedDateListGrid class in the jobs controller of
the reports webapp for an example.
"""
def get_single_filter(self, user, a_filter):
model_class_key_field = getattr(self.model_class, self.key)
assert int(a_filter), "The search entry must be an integer"
return model_class_key_field == int(a_filter)
def sort(self, trans, query, ascending, column_name=None):
"""Sort query using this column."""
return GridColumn.sort(self, trans, query, ascending, column_name=column_name)
class CommunityRatingColumn(GridColumn, UsesItemRatings):
""" Column that displays community ratings for an item. """
def get_value(self, trans, grid, item):
if not hasattr(item, "average_rating"):
# No prefetched column property, generate it on the fly.
ave_item_rating, num_ratings = self.get_ave_item_rating_data(trans.sa_session, item, webapp_model=trans.model)
else:
ave_item_rating = item.average_rating
num_ratings = 2 # just used for pluralization
if not ave_item_rating:
ave_item_rating = 0
return trans.fill_template("tool_shed_rating.mako",
ave_item_rating=ave_item_rating,
num_ratings=num_ratings,
item_id=trans.security.encode_id(item.id))
def sort(self, trans, query, ascending, column_name=None):
# Get the columns that connect item's table and item's rating association table.
item_rating_assoc_class = getattr(trans.model, '%sRatingAssociation' % self.model_class.__name__)
foreign_key = get_foreign_key(item_rating_assoc_class, self.model_class)
fk_col = foreign_key.parent
referent_col = foreign_key.get_referent(self.model_class.table)
# Do sorting using a subquery.
# Subquery to get average rating for each item.
ave_rating_subquery = trans.sa_session.query(fk_col,
func.avg(item_rating_assoc_class.table.c.rating).label('avg_rating')) \
.group_by(fk_col).subquery()
# Integrate subquery into main query.
query = query.outerjoin((ave_rating_subquery, referent_col == ave_rating_subquery.columns[fk_col.name]))
# Sort using subquery results; use coalesce to avoid null values.
if not ascending: # TODO: for now, reverse sorting b/c first sort is ascending, and that should be the natural sort.
query = query.order_by(func.coalesce(ave_rating_subquery.c.avg_rating, 0).asc())
else:
query = query.order_by(func.coalesce(ave_rating_subquery.c.avg_rating, 0).desc())
return query
class OwnerAnnotationColumn(TextColumn, UsesAnnotations):
""" Column that displays and filters item owner's annotations. """
def __init__(self, col_name, key, model_class=None, model_annotation_association_class=None, filterable=None):
GridColumn.__init__(self, col_name, key=key, model_class=model_class, filterable=filterable)
self.sortable = False
self.model_annotation_association_class = model_annotation_association_class
def get_value(self, trans, grid, item):
""" Returns first 150 characters of annotation. """
annotation = self.get_item_annotation_str(trans.sa_session, item.user, item)
if annotation:
ann_snippet = annotation[:155]
if len(annotation) > 155:
ann_snippet = ann_snippet[:ann_snippet.rfind(' ')]
ann_snippet += "..."
else:
ann_snippet = ""
return escape(ann_snippet)
def get_single_filter(self, user, a_filter):
""" Filter by annotation and annotation owner. """
return self.model_class.annotations.any(
and_(func.lower(self.model_annotation_association_class.annotation).like("%" + a_filter.lower() + "%"),
# TODO: not sure why, to filter by owner's annotations, we have to do this rather than
# 'self.model_class.user==self.model_annotation_association_class.user'
self.model_annotation_association_class.table.c.user_id == self.model_class.table.c.user_id))
class CommunityTagsColumn(TextColumn):
""" Column that supports community tags. """
def __init__(self, col_name, key, model_class=None, model_tag_association_class=None, filterable=None, grid_name=None):
GridColumn.__init__(self, col_name, key=key, model_class=model_class, nowrap=True, filterable=filterable, sortable=False)
self.model_tag_association_class = model_tag_association_class
# Column-specific attributes.
self.grid_name = grid_name
def get_value(self, trans, grid, item):
return trans.fill_template("/tagging_common.mako", tag_type="community", trans=trans, user=trans.get_user(), tagged_item=item, elt_context=self.grid_name,
tag_click_fn="add_tag_to_grid_filter", use_toggle_link=True)
def filter(self, trans, user, query, column_filter):
""" Modify query to filter model_class by tag. Multiple filters are ANDed. """
if column_filter == "All":
pass
elif column_filter:
query = query.filter(self.get_filter(trans, user, column_filter))
return query
def get_filter(self, trans, user, column_filter):
# Parse filter to extract multiple tags.
if isinstance(column_filter, list):
# Collapse list of tags into a single string; this is redundant but effective. TODO: fix this by iterating over tags.
column_filter = ",".join(column_filter)
raw_tags = trans.app.tag_handler.parse_tags(column_filter)
clause_list = []
for name, value in raw_tags:
if name:
# Filter by all tags.
clause_list.append(self.model_class.tags.any(func.lower(self.model_tag_association_class.user_tname).like("%" + name.lower() + "%")))
if value:
# Filter by all values.
clause_list.append(self.model_class.tags.any(func.lower(self.model_tag_association_class.user_value).like("%" + value.lower() + "%")))
return and_(*clause_list)
class IndividualTagsColumn(CommunityTagsColumn):
""" Column that supports individual tags. """
def get_value(self, trans, grid, item):
return trans.fill_template("/tagging_common.mako",
tag_type="individual",
user=trans.user,
tagged_item=item,
elt_context=self.grid_name,
tag_click_fn="add_tag_to_grid_filter",
use_toggle_link=True)
def get_filter(self, trans, user, column_filter):
# Parse filter to extract multiple tags.
if isinstance(column_filter, list):
# Collapse list of tags into a single string; this is redundant but effective. TODO: fix this by iterating over tags.
column_filter = ",".join(column_filter)
raw_tags = trans.app.tag_handler.parse_tags(column_filter)
clause_list = []
for name, value in raw_tags:
if name:
# Filter by individual's tag names.
clause_list.append(self.model_class.tags.any(and_(func.lower(self.model_tag_association_class.user_tname).like("%" + name.lower() + "%"), self.model_tag_association_class.user == user)))
if value:
# Filter by individual's tag values.
clause_list.append(self.model_class.tags.any(and_(func.lower(self.model_tag_association_class.user_value).like("%" + value.lower() + "%"), self.model_tag_association_class.user == user)))
return and_(*clause_list)
class MulticolFilterColumn(TextColumn):
""" Column that performs multicolumn filtering. """
def __init__(self, col_name, cols_to_filter, key, visible, filterable="default"):
GridColumn.__init__(self, col_name, key=key, visible=visible, filterable=filterable)
self.cols_to_filter = cols_to_filter
def filter(self, trans, user, query, column_filter):
""" Modify query to filter model_class by tag. Multiple filters are ANDed. """
if column_filter == "All":
return query
if isinstance(column_filter, list):
clause_list = []
for filter in column_filter:
part_clause_list = []
for column in self.cols_to_filter:
part_clause_list.append(column.get_filter(trans, user, filter))
clause_list.append(or_(*part_clause_list))
complete_filter = and_(*clause_list)
else:
clause_list = []
for column in self.cols_to_filter:
clause_list.append(column.get_filter(trans, user, column_filter))
complete_filter = or_(*clause_list)
return query.filter(complete_filter)
class OwnerColumn(TextColumn):
""" Column that lists item's owner. """
def get_value(self, trans, grid, item):
return item.user.username
def sort(self, trans, query, ascending, column_name=None):
""" Sort column using case-insensitive alphabetical sorting on item's username. """
if ascending:
query = query.order_by(func.lower(self.model_class.username).asc())
else:
query = query.order_by(func.lower(self.model_class.username).desc())
return query
class PublicURLColumn(TextColumn):
""" Column displays item's public URL based on username and slug. """
def get_link(self, trans, grid, item):
if item.user.username and item.slug:
return dict(action='display_by_username_and_slug', username=item.user.username, slug=item.slug)
elif not item.user.username:
# TODO: provide link to set username.
return None
elif not item.user.slug:
# TODO: provide link to set slug.
return None
class DeletedColumn(GridColumn):
""" Column that tracks and filters for items with deleted attribute. """
def get_accepted_filters(self):
""" Returns a list of accepted filters for this column. """
accepted_filter_labels_and_vals = {"active": "False", "deleted": "True", "all": "All"}
accepted_filters = []
for label, val in accepted_filter_labels_and_vals.items():
args = {self.key: val}
accepted_filters.append(GridColumnFilter(label, args))
return accepted_filters
def filter(self, trans, user, query, column_filter):
"""Modify query to filter self.model_class by state."""
if column_filter == "All":
pass
elif column_filter in ["True", "False"]:
query = query.filter(self.model_class.deleted == (column_filter == "True"))
return query
class PurgedColumn(GridColumn):
""" Column that tracks and filters for items with purged attribute. """
def get_accepted_filters(self):
""" Returns a list of accepted filters for this column. """
accepted_filter_labels_and_vals = {"nonpurged": "False", "purged": "True", "all": "All"}
accepted_filters = []
for label, val in accepted_filter_labels_and_vals.items():
args = {self.key: val}
accepted_filters.append(GridColumnFilter(label, args))
return accepted_filters
def filter(self, trans, user, query, column_filter):
"""Modify query to filter self.model_class by state."""
if column_filter == "All":
pass
elif column_filter in ["True", "False"]:
query = query.filter(self.model_class.purged == (column_filter == "True"))
return query
class StateColumn(GridColumn):
"""
Column that tracks and filters for items with state attribute.
IMPORTANT NOTE: self.model_class must have a states Bunch or dict if
this column type is used in the grid.
"""
def get_value(self, trans, grid, item):
return item.state
def filter(self, trans, user, query, column_filter):
"""Modify query to filter self.model_class by state."""
if column_filter == "All":
pass
elif column_filter in [v for k, v in self.model_class.states.items()]:
query = query.filter(self.model_class.state == column_filter)
return query
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
all = GridColumnFilter('all', {self.key: 'All'})
accepted_filters = [all]
for v in self.model_class.states.values():
args = {self.key: v}
accepted_filters.append(GridColumnFilter(v, args))
return accepted_filters
class SharingStatusColumn(GridColumn):
""" Grid column to indicate sharing status. """
def __init__(self, *args, **kwargs):
self.use_shared_with_count = kwargs.pop("use_shared_with_count", False)
super().__init__(*args, **kwargs)
def get_value(self, trans, grid, item):
# Delete items cannot be shared.
if item.deleted:
return ""
# Build a list of sharing for this item.
sharing_statuses = []
if self._is_shared(item):
sharing_statuses.append("Shared")
if item.importable:
sharing_statuses.append("Accessible")
if item.published:
sharing_statuses.append("Published")
return ", ".join(sharing_statuses)
def _is_shared(self, item):
if self.use_shared_with_count:
# optimization to skip join for users_shared_with and loading in that data.
return item.users_shared_with_count > 0
return item.users_shared_with
def filter(self, trans, user, query, column_filter):
""" Modify query to filter histories by sharing status. """
if column_filter == "All":
pass
elif column_filter:
if column_filter == "private":
query = query.filter(self.model_class.users_shared_with == null())
query = query.filter(self.model_class.importable == false())
elif column_filter == "shared":
query = query.filter(self.model_class.users_shared_with != null())
elif column_filter == "accessible":
query = query.filter(self.model_class.importable == true())
elif column_filter == "published":
query = query.filter(self.model_class.published == true())
return query
def get_accepted_filters(self):
""" Returns a list of accepted filters for this column. """
accepted_filter_labels_and_vals = {}
accepted_filter_labels_and_vals["private"] = "private"
accepted_filter_labels_and_vals["shared"] = "shared"
accepted_filter_labels_and_vals["accessible"] = "accessible"
accepted_filter_labels_and_vals["published"] = "published"
accepted_filter_labels_and_vals["all"] = "All"
accepted_filters = []
for label, val in accepted_filter_labels_and_vals.items():
args = {self.key: val}
accepted_filters.append(GridColumnFilter(label, args))
return accepted_filters
class GridOperation:
def __init__(self, label, key=None, condition=None, allow_multiple=True, allow_popup=True,
target=None, url_args=None, async_compatible=False, confirm=None,
global_operation=None):
self.label = label
self.key = key
self.allow_multiple = allow_multiple
self.allow_popup = allow_popup
self.condition = condition
self.target = target
self.url_args = url_args
self.async_compatible = async_compatible
# if 'confirm' is set, then ask before completing the operation
self.confirm = confirm
# specify a general operation that acts on the full grid
# this should be a function returning a dictionary with parameters
# to pass to the URL, similar to GridColumn links:
# global_operation=(lambda: dict(operation="download")
self.global_operation = global_operation
def get_url_args(self, item):
if self.url_args:
if callable(self.url_args):
url_args = self.url_args(item)
else:
url_args = dict(self.url_args)
url_args['id'] = item.id
return url_args
else:
return dict(operation=self.label, id=item.id)
def allowed(self, item):
if self.condition:
return bool(self.condition(item))
else:
return True
class DisplayByUsernameAndSlugGridOperation(GridOperation):
""" Operation to display an item by username and slug. """
def get_url_args(self, item):
return {'action': 'display_by_username_and_slug', 'username': item.user.username, 'slug': item.slug}
class GridAction:
def __init__(self, label=None, url_args=None, target=None):
self.label = label
self.url_args = url_args
self.target = target
class GridColumnFilter:
def __init__(self, label, args=None):
self.label = label
self.args = args
def get_url_args(self):
rval = {}
for k, v in self.args.items():
rval["f-" + k] = v
return rval
class Grid:
"""
Specifies the content and format of a grid (data table).
"""
title = ""
model_class: Optional[type] = None
show_item_checkboxes = False
use_hide_message = True
global_actions: List[GridAction] = []
columns: List[GridColumn] = []
operations: List[GridOperation] = []
standard_filters: List[GridColumnFilter] = []
# Any columns that are filterable (either standard or advanced) should have a default value set in the default filter.
default_filter: Dict[str, str] = {}
default_sort_key: Optional[str] = None
use_paging = False
num_rows_per_page = 25
num_page_links = 10
# Set preference names.
cur_filter_pref_name = ".filter"
cur_sort_key_pref_name = ".sort_key"
legend = None
info_text: Optional[str] = None
def __init__(self):
# Determine if any multiple row operations are defined
self.has_multiple_item_operations = False
for operation in self.operations:
if operation.allow_multiple:
self.has_multiple_item_operations = True
break
# If a column does not have a model class, set the column's model class
# to be the grid's model class.
for column in self.columns:
if not column.model_class:
column.model_class = self.model_class
def __call__(self, trans, **kwargs):
# Get basics.
# FIXME: pretty sure this is only here to pass along, can likely be eliminated
status = kwargs.get('status', None)
message = kwargs.get('message', None)
# Build a base filter and sort key that is the combination of the saved state and defaults.
# Saved state takes preference over defaults.
base_filter = {}
if self.default_filter:
# default_filter is a dictionary that provides a default set of filters based on the grid's columns.
base_filter = self.default_filter.copy()
base_sort_key = self.default_sort_key
# Build initial query
query = self.build_initial_query(trans, **kwargs)
query = self.apply_query_filter(trans, query, **kwargs)
# Maintain sort state in generated urls
extra_url_args = {}
# Determine whether use_default_filter flag is set.
use_default_filter_str = kwargs.get('use_default_filter')
use_default_filter = False
if use_default_filter_str:
use_default_filter = (use_default_filter_str.lower() == 'true')
# Process filtering arguments to (a) build a query that represents the filter and (b) build a
# dictionary that denotes the current filter.
cur_filter_dict = {}
for column in self.columns:
if column.key:
# Get the filter criterion for the column. Precedence is (a) if using default filter, only look there; otherwise,
# (b) look in kwargs; and (c) look in base filter.
column_filter = None
if use_default_filter:
if self.default_filter:
column_filter = self.default_filter.get(column.key)
elif "f-" + column.model_class.__name__ + ".%s" % column.key in kwargs:
# Queries that include table joins cannot guarantee unique column names. This problem is
# handled by setting the column_filter value to <TableName>.<ColumnName>.
column_filter = kwargs.get("f-" + column.model_class.__name__ + ".%s" % column.key)
elif "f-" + column.key in kwargs:
column_filter = kwargs.get("f-" + column.key)
elif column.key in base_filter:
column_filter = base_filter.get(column.key)
# Method (1) combines a mix of strings and lists of strings into a single string and (2) attempts to de-jsonify all strings.
def loads_recurse(item):
decoded_list = []
if isinstance(item, str):
try:
# Not clear what we're decoding, so recurse to ensure that we catch everything.
decoded_item = loads(item)
if isinstance(decoded_item, list):
decoded_list = loads_recurse(decoded_item)
else:
decoded_list = [str(decoded_item)]
except ValueError:
decoded_list = [str(item)]
elif isinstance(item, list):
for element in item:
a_list = loads_recurse(element)
decoded_list = decoded_list + a_list
return decoded_list
# If column filter found, apply it.
if column_filter is not None:
# TextColumns may have a mix of json and strings.
if isinstance(column, TextColumn):
column_filter = loads_recurse(column_filter)
if len(column_filter) == 1:
column_filter = column_filter[0]
# Interpret ',' as a separator for multiple terms.
if isinstance(column_filter, str) and column_filter.find(',') != -1:
column_filter = column_filter.split(',')
# Check if filter is empty
if isinstance(column_filter, list):
# Remove empty strings from filter list
column_filter = [x for x in column_filter if x != '']
if len(column_filter) == 0:
continue
elif isinstance(column_filter, str):
# If filter criterion is empty, do nothing.
if column_filter == '':
continue
# Update query.
query = column.filter(trans, trans.user, query, column_filter)
# Upate current filter dict.
# Column filters are rendered in various places, sanitize them all here.
cur_filter_dict[column.key] = sanitize_text(column_filter)
# Carry filter along to newly generated urls; make sure filter is a string so
# that we can encode to UTF-8 and thus handle user input to filters.
if isinstance(column_filter, list):
# Filter is a list; process each item.
extra_url_args["f-" + column.key] = dumps(column_filter)
else:
# Process singleton filter.
extra_url_args["f-" + column.key] = column_filter
# Process sort arguments.
sort_key = None
if 'sort' in kwargs:
sort_key = kwargs['sort']
elif base_sort_key:
sort_key = base_sort_key
if sort_key:
ascending = not(sort_key.startswith("-"))
# Queries that include table joins cannot guarantee unique column names. This problem is
# handled by setting the column_filter value to <TableName>.<ColumnName>.
table_name = None
if sort_key.find('.') > -1:
a_list = sort_key.split('.')
if ascending:
table_name = a_list[0]
else:
table_name = a_list[0][1:]
column_name = a_list[1]
elif ascending:
column_name = sort_key
else:
column_name = sort_key[1:]
# Sort key is a column key.
for column in self.columns:
if column.key and column.key.find('.') > -1:
column_key = column.key.split('.')[1]
else:
column_key = column.key
if (table_name is None or table_name == column.model_class.__name__) and column_key == column_name:
query = column.sort(trans, query, ascending, column_name=column_name)
break
extra_url_args['sort'] = sort_key
# There might be a current row
current_item = self.get_current_item(trans, **kwargs)
# Process page number.
num_pages = None
total_row_count_query = query # query without limit applied to get total number of rows.
if self.use_paging:
if 'page' in kwargs:
if kwargs['page'] == 'all':
page_num = 0
else:
page_num = int(kwargs['page'])
else:
page_num = 1
if page_num == 0:
num_pages = 1
page_num = 1
else:
query = query.limit(self.num_rows_per_page).offset((page_num - 1) * self.num_rows_per_page)
else:
# Defaults.
page_num = 1
# There are some places in grid templates where it's useful for a grid
# to have its current filter.
self.cur_filter_dict = cur_filter_dict
# Log grid view.
context = str(self.__class__.__name__)
params = cur_filter_dict.copy()
params['sort'] = sort_key
# Render grid.
def url(*args, **kwargs):
route_name = kwargs.pop('__route_name__', None)
# Only include sort/filter arguments if not linking to another
# page. This is a bit of a hack.
if 'action' in kwargs:
new_kwargs = dict()
else:
new_kwargs = dict(extra_url_args)
# Extend new_kwargs with first argument if found
if len(args) > 0:
new_kwargs.update(args[0])
new_kwargs.update(kwargs)
# We need to encode item ids
if 'id' in new_kwargs:
id = new_kwargs['id']
if isinstance(id, list):
new_kwargs['id'] = [trans.security.encode_id(i) for i in id]
else:
new_kwargs['id'] = trans.security.encode_id(id)
# The url_for invocation *must* include a controller and action.
if 'controller' not in new_kwargs:
new_kwargs['controller'] = trans.controller
if 'action' not in new_kwargs:
new_kwargs['action'] = trans.action
if route_name:
return url_for(route_name, **new_kwargs)
return url_for(**new_kwargs)
self.use_panels = (kwargs.get('use_panels', False) in [True, 'True', 'true'])
self.advanced_search = (kwargs.get('advanced_search', False) in [True, 'True', 'true'])
# Currently, filling the template returns a str object; this requires decoding the string into a
# unicode object within mako templates. What probably should be done is to return the template as
# utf-8 unicode; however, this would require encoding the object as utf-8 before returning the grid
# results via a controller method, which is require substantial changes. Hence, for now, return grid
# as str.
grid_config = {
'title': self.title,
'title_id': getattr(self, "title_id", None),
'url_base': trans.request.path_url,
'async_ops': [],
'categorical_filters': {},
'filters': cur_filter_dict,
'sort_key': sort_key,
'show_item_checkboxes': self.show_item_checkboxes or kwargs.get('show_item_checkboxes', '') in ['True', 'true'],
'cur_page_num': page_num,
'num_page_links': self.num_page_links,
'status': status,
'message': restore_text(message),
'global_actions': [],
'operations': [],
'items': [],
'columns': [],
'model_class': str(self.model_class),
'use_paging': self.use_paging,
'legend': self.legend,
'current_item_id': False,
'use_hide_message': self.use_hide_message,
'default_filter_dict': self.default_filter,
'advanced_search': self.advanced_search,
'info_text': self.info_text,
'url': url(dict()),
'refresh_frames': kwargs.get('refresh_frames', [])
}
if current_item:
grid_config['current_item_id'] = current_item.id
for column in self.columns:
extra = ''
if column.sortable:
if sort_key.endswith(column.key):
if not sort_key.startswith("-"):
extra = "↓"
else:
extra = "↑"
grid_config['columns'].append({
'key': column.key,
'visible': column.visible,
'nowrap': column.nowrap,
'attach_popup': column.attach_popup,
'label_id_prefix': column.label_id_prefix,
'sortable': column.sortable,
'label': column.label,
'filterable': column.filterable,
'delayed': column.delayed,
'is_text': isinstance(column, TextColumn),
'extra': extra
})
for operation in self.operations:
grid_config['operations'].append({
'allow_multiple': operation.allow_multiple,
'allow_popup': operation.allow_popup,
'target': operation.target,
'label': operation.label,
'confirm': operation.confirm,
'href': url(**operation.url_args) if isinstance(operation.url_args, dict) else None,
'global_operation': False
})
if operation.allow_multiple:
grid_config['show_item_checkboxes'] = True
if operation.global_operation:
grid_config['global_operation'] = url(** (operation.global_operation()))
for action in self.global_actions:
grid_config['global_actions'].append({
'url_args': url(**action.url_args),
'label': action.label,
'target': action.target
})
for operation in [op for op in self.operations if op.async_compatible]:
grid_config['async_ops'].append(operation.label.lower())
for column in self.columns:
if column.filterable is not None and not isinstance(column, TextColumn):
grid_config['categorical_filters'][column.key] = {filter.label: filter.args for filter in column.get_accepted_filters()}
for item in query:
item_dict = {
'id': item.id,
'encode_id': trans.security.encode_id(item.id),
'link': [],
'operation_config': {},
'column_config': {}
}
for column in self.columns:
if column.visible:
link = column.get_link(trans, self, item)
if link:
link = url(**link)
else:
link = None
target = column.target
value = unicodify(column.get_value(trans, self, item))
if value:
value = value.replace('/', '//')
item_dict['column_config'][column.label] = {
'link': link,
'value': value,
'target': target
}
for operation in self.operations:
item_dict['operation_config'][operation.label] = {
'allowed': operation.allowed(item),
'url_args': url(**operation.get_url_args(item)),
'target': operation.target
}
grid_config['items'].append(item_dict)
if self.use_paging and num_pages is None:
# TODO: it would be better to just return this as None, render, and fire
# off a second request for this count I think.
total_num_rows = total_row_count_query.count()
num_pages = int(math.ceil(float(total_num_rows) / self.num_rows_per_page))
grid_config["num_pages"] = num_pages
trans.log_action(trans.get_user(), "grid.view", context, params)
return grid_config
def get_ids(self, **kwargs):
id = []
if 'id' in kwargs:
id = kwargs['id']
# Coerce ids to list
if not isinstance(id, list):
id = id.split(",")
# Ensure ids are integers
try:
id = list(map(int, id))
except Exception:
decorators.error("Invalid id")
return id
# ---- Override these ----------------------------------------------------
def handle_operation(self, trans, operation, ids, **kwargs):
pass
def get_current_item(self, trans, **kwargs):
return None
def | (self, trans, **kwargs):
return trans.sa_session.query(self.model_class)
def apply_query_filter(self, trans, query, **kwargs):
# Applies a database filter that holds for all items in the grid.
# (gvk) Is this method necessary? Why not simply build the entire query,
# including applying filters in the build_initial_query() method?
return query
| build_initial_query |
router.go | import (
"github.com/simman/Image_Beego_Qiniu/controllers"
"github.com/astaxie/beego"
)
func init() {
beego.Router("/", &controllers.HomeController{})
beego.Router("/my", &controllers.HomeController{}, "*:My")
beego.Router("/hot", &controllers.HomeController{}, "*:Hot")
beego.Router("/Upload", &controllers.HomeController{}, "post:Upload")
} | package routers
|
|
data_loader.py | # -*- coding: utf-8 -*-
# @Author : William
# @Project : TextGAN-william
# @FileName : data_loader.py
# @Time : Created at 2019-05-31
# @Blog : http://zhiweil.ml/
# @Description :
# Copyrights (C) 2018. All Rights Reserved.
import random
from torch.utils.data import Dataset, DataLoader
from utils.text_process import *
class GANDataset(Dataset):
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
class GenDataIter:
def __init__(self, samples, if_test_data=False, shuffle=None):
self.batch_size = cfg.batch_size
self.max_seq_len = cfg.max_seq_len
self.start_letter = cfg.start_letter
self.shuffle = cfg.data_shuffle if not shuffle else shuffle
if cfg.if_real_data:
self.word2idx_dict, self.idx2word_dict = load_dict(cfg.dataset)
if if_test_data: # used for the classifier
self.word2idx_dict, self.idx2word_dict = load_test_dict(cfg.dataset)
self.loader = DataLoader(
dataset=GANDataset(self.__read_data__(samples)),
batch_size=self.batch_size,
shuffle=self.shuffle,
drop_last=True)
self.input = self._all_data_('input')
self.target = self._all_data_('target')
def __read_data__(self, samples):
"""
input: same as target, but start with start_letter.
"""
# global all_data
if isinstance(samples, torch.Tensor): # Tensor
inp, target = self.prepare(samples)
all_data = [{'input': i, 'target': t} for (i, t) in zip(inp, target)]
elif isinstance(samples, str): # filename
inp, target = self.load_data(samples)
all_data = [{'input': i, 'target': t} for (i, t) in zip(inp, target)]
else:
all_data = None
return all_data
def random_batch(self):
"""Randomly choose a batch from loader, please note that the data should not be shuffled."""
idx = random.randint(0, len(self.loader) - 1)
return list(self.loader)[idx]
def _all_data_(self, col):
return torch.cat([data[col].unsqueeze(0) for data in self.loader.dataset.data], 0)
@staticmethod
def prepare(samples, gpu=False):
"""Add start_letter to samples as inp, target same as samples"""
inp = torch.zeros(samples.size()).long()
target = samples
inp[:, 0] = cfg.start_letter
inp[:, 1:] = target[:, :cfg.max_seq_len - 1]
#print(f"dataloader inp: {inp[0][:]}")
#print(f"dataloader target: {target[0][:]}")
if gpu:
return inp.cuda(), target.cuda()
return inp, target
def load_data(self, filename):
"""Load real data from local file"""
self.tokens = get_tokenlized(filename)
samples_index = tokens_to_tensor(self.tokens, self.word2idx_dict)
return self.prepare(samples_index)
class DisDataIter:
def __init__(self, pos_samples, neg_samples, shuffle=None):
self.batch_size = cfg.batch_size
self.max_seq_len = cfg.max_seq_len
self.start_letter = cfg.start_letter
self.shuffle = cfg.data_shuffle if not shuffle else shuffle
self.loader = DataLoader(
dataset=GANDataset(self.__read_data__(pos_samples, neg_samples)),
batch_size=self.batch_size,
shuffle=self.shuffle,
drop_last=True)
def __read_data__(self, pos_samples, neg_samples):
"""
input: same as target, but start with start_letter.
"""
inp, target = self.prepare(pos_samples, neg_samples)
all_data = [{'input': i, 'target': t} for (i, t) in zip(inp, target)]
return all_data
def random_batch(self):
idx = random.randint(0, len(self.loader) - 1)
return list(self.loader)[idx]
def prepare(self, pos_samples, neg_samples, gpu=False):
| """Build inp and target"""
inp = torch.cat((pos_samples, neg_samples), dim=0).long().detach() # !!!need .detach()
target = torch.ones(inp.size(0)).long()
target[pos_samples.size(0):] = 0
# shuffle
perm = torch.randperm(inp.size(0))
inp = inp[perm]
target = target[perm]
if gpu:
return inp.cuda(), target.cuda()
return inp, target |
|
unit_characteristic_plot.py | import numpy as np
import datajoint as dj
from PIL import ImageColor
from collections import Counter
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import itertools
import pandas as pd
from pipeline import experiment, ephys, psth, lab, histology, ccf, psth_foraging
from pipeline.plot.util import (_plot_with_sem, _extract_one_stim_dur,
_plot_stacked_psth_diff, _plot_avg_psth, _jointplot_w_hue)
from pipeline.plot import unit_psth
from pipeline.util import (_get_units_hemisphere, _get_trial_event_times,
_get_stim_onset_time, _get_clustering_method)
from . import PhotostimError
_plt_xmin = -3
_plt_xmax = 2
def plot_clustering_quality(probe_insertion, clustering_method=None, axs=None):
probe_insertion = probe_insertion.proj()
if clustering_method is None:
try:
clustering_method = _get_clustering_method(probe_insertion)
except ValueError as e:
raise ValueError(str(e) + '\nPlease specify one with the kwarg "clustering_method"')
amp, snr, spk_rate, isi_violation = (ephys.Unit * ephys.UnitStat * ephys.ProbeInsertion.InsertionLocation
& probe_insertion & {'clustering_method': clustering_method}).fetch(
'unit_amp', 'unit_snr', 'avg_firing_rate', 'isi_violation')
metrics = {'amp': amp,
'snr': snr,
'isi': np.array(isi_violation) * 100, # to percentage
'rate': np.array(spk_rate)}
label_mapper = {'amp': 'Amplitude',
'snr': 'Signal to noise ratio (SNR)',
'isi': 'ISI violation (%)',
'rate': 'Firing rate (spike/s)'}
fig = None
if axs is None:
fig, axs = plt.subplots(2, 3, figsize = (12, 8))
fig.subplots_adjust(wspace=0.4)
assert axs.size == 6
for (m1, m2), ax in zip(itertools.combinations(list(metrics.keys()), 2), axs.flatten()):
ax.plot(metrics[m1], metrics[m2], '.k')
ax.set_xlabel(label_mapper[m1])
ax.set_ylabel(label_mapper[m2])
# cosmetic
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
return fig
def plot_unit_characteristic(probe_insertion, clustering_method=None, axs=None):
probe_insertion = probe_insertion.proj()
if clustering_method is None:
try:
clustering_method = _get_clustering_method(probe_insertion)
except ValueError as e:
raise ValueError(str(e) + '\nPlease specify one with the kwarg "clustering_method"')
if clustering_method in ('kilosort2'):
q_unit = (ephys.Unit * ephys.ProbeInsertion.InsertionLocation.proj('depth') * ephys.UnitStat
* lab.ElectrodeConfig.Electrode.proj() * lab.ProbeType.Electrode.proj('x_coord', 'y_coord')
& probe_insertion & {'clustering_method': clustering_method} & 'unit_quality != "all"').proj(
..., x='x_coord', y='y_coord')
else:
q_unit = (ephys.Unit * ephys.ProbeInsertion.InsertionLocation.proj('depth') * ephys.UnitStat
& probe_insertion & {'clustering_method': clustering_method} & 'unit_quality != "all"').proj(
..., x='unit_posx', y='unit_posy')
amp, snr, spk_rate, x, y, insertion_depth = q_unit.fetch(
'unit_amp', 'unit_snr', 'avg_firing_rate', 'x', 'y', 'depth')
metrics = pd.DataFrame(list(zip(*(amp/amp.max(), snr/snr.max(), spk_rate/spk_rate.max(),
x, insertion_depth.astype(float) + y))))
metrics.columns = ['amp', 'snr', 'rate', 'x', 'y']
# --- prepare for plotting
shank_count = (ephys.ProbeInsertion & probe_insertion).aggr(lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode,
shank_count='count(distinct shank)').fetch1('shank_count')
m_scale = get_m_scale(shank_count)
ymin = metrics.y.min() - 100
ymax = metrics.y.max() + 200
xmax = 1.3 * metrics.x.max()
xmin = -1/6*xmax
cosmetic = {'legend': None,
'linewidth': 1.75,
'alpha': 0.9,
'facecolor': 'none', 'edgecolor': 'k'}
# --- plot
fig = None
if axs is None:
fig, axs = plt.subplots(1, 3, figsize=(10, 8))
fig.subplots_adjust(wspace=0.6)
assert axs.size == 3
sns.scatterplot(data=metrics, x='x', y='y', s=metrics.amp*m_scale, ax=axs[0], **cosmetic)
sns.scatterplot(data=metrics, x='x', y='y', s=metrics.snr*m_scale, ax=axs[1], **cosmetic)
sns.scatterplot(data=metrics, x='x', y='y', s=metrics.rate*m_scale, ax=axs[2], **cosmetic)
# manually draw the legend
lg_ypos = ymax
data = pd.DataFrame({'x': [0.1*xmax, 0.4*xmax, 0.75*xmax], 'y': [lg_ypos, lg_ypos, lg_ypos],
'size_ratio': np.array([0.2, 0.5, 0.8])})
for ax, ax_maxval in zip(axs.flatten(), (amp.max(), snr.max(), spk_rate.max())):
sns.scatterplot(data=data, x='x', y='y', s=data.size_ratio*m_scale, ax=ax, **dict(cosmetic, facecolor='k'))
for _, r in data.iterrows():
ax.text(r['x']-4, r['y']+70, (r['size_ratio']*ax_maxval).astype(int))
# cosmetic
for title, ax in zip(('Amplitude', 'SNR', 'Firing rate'), axs.flatten()):
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_title(title)
ax.set_xlim((xmin, xmax))
ax.plot([0.5*xmin, xmax], [lg_ypos-80, lg_ypos-80], '-k')
ax.set_ylim((ymin, ymax + 150))
return fig
def plot_unit_selectivity(probe_insertion, clustering_method=None, axs=None):
probe_insertion = probe_insertion.proj()
if clustering_method is None:
try:
clustering_method = _get_clustering_method(probe_insertion)
except ValueError as e:
raise ValueError(str(e) + '\nPlease specify one with the kwarg "clustering_method"')
if clustering_method in ('kilosort2'):
q_unit = (psth.PeriodSelectivity * ephys.Unit * ephys.ProbeInsertion.InsertionLocation
* lab.ElectrodeConfig.Electrode.proj() * lab.ProbeType.Electrode.proj('x_coord', 'y_coord')
* experiment.Period & probe_insertion & {'clustering_method': clustering_method}
& 'period_selectivity != "non-selective"').proj(..., x='unit_posx', y='unit_posy').proj(
..., x='x_coord', y='y_coord')
else:
q_unit = (psth.PeriodSelectivity * ephys.Unit * ephys.ProbeInsertion.InsertionLocation
* experiment.Period & probe_insertion & {'clustering_method': clustering_method}
& 'period_selectivity != "non-selective"').proj(..., x='unit_posx', y='unit_posy')
attr_names = ['unit', 'period', 'period_selectivity', 'contra_firing_rate',
'ipsi_firing_rate', 'x', 'y', 'depth']
selective_units = q_unit.fetch(*attr_names)
selective_units = pd.DataFrame(selective_units).T
selective_units.columns = attr_names
selective_units.period_selectivity.astype('category')
# --- account for insertion depth (manipulator depth)
selective_units.y = selective_units.depth.values.astype(float) + selective_units.y
# --- get ipsi vs. contra firing rate difference
f_rate_diff = np.abs(selective_units.ipsi_firing_rate - selective_units.contra_firing_rate)
selective_units['f_rate_diff'] = f_rate_diff / f_rate_diff.max()
# --- prepare for plotting
shank_count = (ephys.ProbeInsertion & probe_insertion).aggr(lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode,
shank_count='count(distinct shank)').fetch1('shank_count')
m_scale = get_m_scale(shank_count)
cosmetic = {'legend': None,
'linewidth': 0.0001}
ymin = selective_units.y.min() - 100
ymax = selective_units.y.max() + 100
xmax = 1.3 * selective_units.x.max()
xmin = -1/6*xmax
# a bit of hack to get the 'open circle'
pts = np.linspace(0, np.pi * 2, 24)
circ = np.c_[np.sin(pts) / 2, -np.cos(pts) / 2]
vert = np.r_[circ, circ[::-1] * .7]
open_circle = mpl.path.Path(vert)
# --- plot
fig = None
if axs is None:
fig, axs = plt.subplots(1, 3, figsize=(10, 8))
fig.subplots_adjust(wspace=0.6)
assert axs.size == 3
for (title, df), ax in zip(((p, selective_units[selective_units.period == p])
for p in ('sample', 'delay', 'response')), axs):
sns.scatterplot(data=df, x='x', y='y',
s=df.f_rate_diff.values.astype(float)*m_scale,
hue='period_selectivity', marker=open_circle,
palette={'contra-selective': 'b', 'ipsi-selective': 'r'},
ax=ax, **cosmetic)
contra_p = (df.period_selectivity == 'contra-selective').sum() / len(df) * 100
# cosmetic
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_title(f'{title}\n% contra: {contra_p:.2f}\n% ipsi: {100-contra_p:.2f}')
ax.set_xlim((xmin, xmax))
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_ylim((ymin, ymax))
return fig
def plot_unit_bilateral_photostim_effect(probe_insertion, clustering_method=None, axs=None):
probe_insertion = probe_insertion.proj()
if not (psth.TrialCondition().get_trials('all_noearlylick_both_alm_stim') & probe_insertion):
raise PhotostimError('No Bilateral ALM Photo-stimulation present')
if clustering_method is None:
try:
clustering_method = _get_clustering_method(probe_insertion)
except ValueError as e:
raise ValueError(str(e) + '\nPlease specify one with the kwarg "clustering_method"')
dv_loc = (ephys.ProbeInsertion.InsertionLocation & probe_insertion).fetch1('depth')
no_stim_cond = (psth.TrialCondition
& {'trial_condition_name':
'all_noearlylick_nostim'}).fetch1('KEY')
bi_stim_cond = (psth.TrialCondition
& {'trial_condition_name':
'all_noearlylick_both_alm_stim'}).fetch1('KEY')
units = ephys.Unit & probe_insertion & {'clustering_method': clustering_method} & 'unit_quality != "all"'
metrics = pd.DataFrame(columns=['unit', 'x', 'y', 'frate_change'])
# get photostim onset and duration
stim_durs = np.unique((experiment.Photostim & experiment.PhotostimEvent
* psth.TrialCondition().get_trials('all_noearlylick_both_alm_stim')
& probe_insertion).fetch('duration'))
stim_dur = _extract_one_stim_dur(stim_durs)
stim_time = _get_stim_onset_time(units, 'all_noearlylick_both_alm_stim')
# XXX: could be done with 1x fetch+join
for u_idx, unit in enumerate(units.fetch('KEY', order_by='unit')):
if clustering_method in ('kilosort2'):
x, y = (ephys.Unit * lab.ElectrodeConfig.Electrode.proj()
* lab.ProbeType.Electrode.proj('x_coord', 'y_coord') & unit).fetch1('x_coord', 'y_coord')
else:
x, y = (ephys.Unit & unit).fetch1('unit_posx', 'unit_posy')
# obtain unit psth per trial, for all nostim and bistim trials
nostim_trials = ephys.Unit.TrialSpikes & unit & psth.TrialCondition.get_trials(no_stim_cond['trial_condition_name'])
bistim_trials = ephys.Unit.TrialSpikes & unit & psth.TrialCondition.get_trials(bi_stim_cond['trial_condition_name'])
nostim_psths, nostim_edge = psth.compute_unit_psth(unit, nostim_trials.fetch('KEY'), per_trial=True)
bistim_psths, bistim_edge = psth.compute_unit_psth(unit, bistim_trials.fetch('KEY'), per_trial=True)
# compute the firing rate difference between contra vs. ipsi within the stimulation time window
ctrl_frate = np.array([nostim_psth[np.logical_and(nostim_edge >= stim_time,
nostim_edge <= stim_time + stim_dur)].mean()
for nostim_psth in nostim_psths])
stim_frate = np.array([bistim_psth[np.logical_and(bistim_edge >= stim_time,
bistim_edge <= stim_time + stim_dur)].mean()
for bistim_psth in bistim_psths])
frate_change = (stim_frate.mean() - ctrl_frate.mean()) / ctrl_frate.mean()
frate_change = abs(frate_change) if frate_change < 0 else 0.0001
metrics.loc[u_idx] = (int(unit['unit']), x, float(dv_loc) + y, frate_change)
metrics.frate_change = metrics.frate_change / metrics.frate_change.max()
# --- prepare for plotting
shank_count = (ephys.ProbeInsertion & probe_insertion).aggr(lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode,
shank_count='count(distinct shank)').fetch1('shank_count')
m_scale = get_m_scale(shank_count)
fig = None
if axs is None:
fig, axs = plt.subplots(1, 1, figsize=(4, 8))
xmax = 1.3 * metrics.x.max()
xmin = -1/6*xmax
cosmetic = {'legend': None,
'linewidth': 1.75,
'alpha': 0.9,
'facecolor': 'none', 'edgecolor': 'k'}
sns.scatterplot(data=metrics, x='x', y='y', s=metrics.frate_change*m_scale,
ax=axs, **cosmetic)
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.set_title('% change')
axs.set_xlim((xmin, xmax))
return fig
def plot_pseudocoronal_slice(probe_insertion, shank_no=1):
# ---- Electrode sites ----
annotated_electrodes = (lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode
* ephys.ProbeInsertion
* histology.ElectrodeCCFPosition.ElectrodePosition
& probe_insertion & {'shank': shank_no})
electrode_coords = np.array(list(zip(*annotated_electrodes.fetch(
'ccf_z', 'ccf_y', 'ccf_x', order_by='ccf_y')))) # (AP, DV, ML)
probe_track_coords = np.array(list(zip(*(histology.LabeledProbeTrack.Point
& probe_insertion & {'shank': shank_no}).fetch(
'ccf_z', 'ccf_y', 'ccf_x', order_by='ccf_y'))))
voxel_res = ccf.CCFLabel.CCF_R3_20UM_RESOLUTION
lr_max, dv_max, _ = ccf.get_ccf_xyz_max()
pseudocoronal_points, shank_ccfs = histology.retrieve_pseudocoronal_slice(probe_insertion, shank_no)
dv_pts, lr_pts, ap_pts, color_codes = pseudocoronal_points.T
dv_pts = dv_pts.astype(int)
lr_pts = lr_pts.astype(int)
color_codes = color_codes.astype(str)
# ---- paint annotation color code ----
coronal_slice = np.full((dv_max + 1, lr_max + 1, 3), np.nan)
for color in set(color_codes):
matched_ind = np.where(color_codes == color)[0]
dv_ind = dv_pts[matched_ind] # rows
lr_ind = lr_pts[matched_ind] # cols
try:
c_rgb = ImageColor.getcolor("#" + color, "RGB")
except ValueError as e:
print(str(e))
continue
coronal_slice[dv_ind, lr_ind, :] = np.full((len(matched_ind), 3), c_rgb)
# ---- paint the interpolated track of this probe/shank in gray ----
in_probe_range = np.logical_and(shank_ccfs[:, 1] >= probe_track_coords[:, 1].min(),
shank_ccfs[:, 1] <= probe_track_coords[:, 1].max())
in_electrode_range = np.logical_and(shank_ccfs[:, 1] >= electrode_coords[:, 1].min(),
shank_ccfs[:, 1] <= electrode_coords[:, 1].max())
tracks_coords = shank_ccfs[np.logical_and(in_probe_range, ~in_electrode_range), :]
coronal_slice[tracks_coords[:, 1], tracks_coords[:, 0], :] = np.full(
(tracks_coords.shape[0], 3), ImageColor.getcolor("#FFFFFF", "RGB"))
# ---- paint electrode sites on this probe/shank in black ----
coronal_slice[electrode_coords[:, 1], electrode_coords[:, 2], :] = np.full(
(electrode_coords.shape[0], 3), ImageColor.getcolor("#080808", "RGB"))
# ---- downsample the 2D slice to the voxel resolution ----
coronal_slice = coronal_slice[::voxel_res, ::voxel_res, :]
# paint outside region white
nan_r, nan_c = np.where(np.nansum(coronal_slice, axis=2) == 0)
coronal_slice[nan_r, nan_c, :] = np.full((len(nan_r), 3), ImageColor.getcolor("#FFFFFF", "RGB"))
# ---- plot ----
fig, ax = plt.subplots(1, 1)
ax.imshow(coronal_slice.astype(np.uint8), extent=[0, lr_max, dv_max, 0])
ax.invert_xaxis()
ax.set_xticks([])
ax.set_yticks([])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
return fig
def plot_driftmap(probe_insertion, clustering_method=None, shank_no=1):
probe_insertion = probe_insertion.proj()
assert histology.InterpolatedShankTrack & probe_insertion
if clustering_method is None:
try:
clustering_method = _get_clustering_method(probe_insertion)
except ValueError as e:
raise ValueError(str(e) + '\nPlease specify one with the kwarg "clustering_method"')
units = (ephys.Unit * lab.ElectrodeConfig.Electrode
& probe_insertion & {'clustering_method': clustering_method}
& 'unit_quality != "all"')
units = (units.proj('spike_times', 'spike_depths', 'unit_posy')
* ephys.ProbeInsertion.proj()
* lab.ProbeType.Electrode.proj('shank') & {'shank': shank_no})
# ---- ccf region ----
annotated_electrodes = (lab.ElectrodeConfig.Electrode * lab.ProbeType.Electrode
* ephys.ProbeInsertion
* histology.ElectrodeCCFPosition.ElectrodePosition
* ccf.CCFAnnotation * ccf.CCFBrainRegion.proj(..., annotation='region_name')
& probe_insertion & {'shank': shank_no})
pos_y, ccf_y, color_code = annotated_electrodes.fetch(
'y_coord', 'ccf_y', 'color_code', order_by='y_coord DESC')
# CCF position of most ventral recording site
last_electrode_site = np.array((histology.InterpolatedShankTrack.DeepestElectrodePoint
& probe_insertion & {'shank': shank_no}).fetch1(
'ccf_x', 'ccf_y', 'ccf_z'))
# CCF position of the brain surface where this shank crosses
brain_surface_site = np.array((histology.InterpolatedShankTrack.BrainSurfacePoint
& probe_insertion & {'shank': shank_no}).fetch1(
'ccf_x', 'ccf_y', 'ccf_z'))
# CCF position of most ventral recording site, with respect to the brain surface
y_ref = -np.linalg.norm(last_electrode_site - brain_surface_site)
# ---- spikes ----brain_surface_site
spike_times, spike_depths = units.fetch('spike_times', 'spike_depths', order_by='unit')
spike_times = np.hstack(spike_times)
spike_depths = np.hstack(spike_depths)
# histogram
# time_res = 10 # time resolution: 1sec
# depth_res = 10 # depth resolution: 10um
#
# spike_bins = np.arange(0, spike_times.max() + time_res, time_res)
# depth_bins = np.arange(spike_depths.min() - depth_res, spike_depths.max() + depth_res, depth_res)
# time-depth 2D histogram
time_bin_count = 1000
depth_bin_count = 200
spike_bins = np.linspace(0, spike_times.max(), time_bin_count)
depth_bins = np.linspace(0, np.nanmax(spike_depths), depth_bin_count)
spk_count, spk_edges, depth_edges = np.histogram2d(spike_times, spike_depths, bins=[spike_bins, depth_bins])
spk_rates = spk_count / np.mean(np.diff(spike_bins))
spk_edges = spk_edges[:-1]
depth_edges = depth_edges[:-1]
# region colorcode, by depths
binned_hexcodes = []
y_spacing = np.abs(np.nanmedian(np.where(np.diff(pos_y)==0, np.nan, np.diff(pos_y))))
anno_depth_bins = np.arange(0, depth_bins[-1], y_spacing)
for s, e in zip(anno_depth_bins[:-1], anno_depth_bins[1:]):
hexcodes = color_code[np.logical_and(pos_y > s, pos_y <= e)]
if len(hexcodes):
binned_hexcodes.append(Counter(hexcodes).most_common()[0][0])
else:
binned_hexcodes.append('FFFFFF')
region_rgba = np.array([list(ImageColor.getcolor("#" + chex, "RGBA")) for chex in binned_hexcodes])
region_rgba = np.repeat(region_rgba[:, np.newaxis, :], 10, axis=1)
# canvas setup
fig = plt.figure(figsize=(16, 8))
grid = plt.GridSpec(12, 12)
ax_main = plt.subplot(grid[1:, 0:9])
ax_cbar = plt.subplot(grid[0, 0:9])
ax_spkcount = plt.subplot(grid[1:, 9:11])
ax_anno = plt.subplot(grid[1:, 11:])
# -- plot main --
im = ax_main.imshow(spk_rates.T, aspect='auto', cmap='gray_r',
extent=[spike_bins[0], spike_bins[-1], depth_bins[-1], depth_bins[0]])
# cosmetic
ax_main.invert_yaxis()
ax_main.set_xlabel('Time (sec)')
ax_main.set_ylabel('Distance from tip sites (um)')
ax_main.set_ylim(depth_edges[0], depth_edges[-1])
ax_main.spines['right'].set_visible(False)
ax_main.spines['top'].set_visible(False)
cb = fig.colorbar(im, cax=ax_cbar, orientation='horizontal')
cb.outline.set_visible(False)
cb.ax.xaxis.tick_top()
cb.set_label('Firing rate (Hz)')
cb.ax.xaxis.set_label_position('top')
# -- plot spikecount --
ax_spkcount.plot(spk_count.sum(axis=0) / 10e3, depth_edges, 'k')
ax_spkcount.set_xlabel('Spike count (x$10^3$)')
ax_spkcount.set_yticks([])
ax_spkcount.set_ylim(depth_edges[0], depth_edges[-1])
ax_spkcount.spines['right'].set_visible(False)
ax_spkcount.spines['top'].set_visible(False)
ax_spkcount.spines['bottom'].set_visible(False)
ax_spkcount.spines['left'].set_visible(False)
# -- plot colored region annotation
ax_anno.imshow(region_rgba, aspect='auto',
extent=[0, 10, (anno_depth_bins[-1] + y_ref) / 1000, (anno_depth_bins[0] + y_ref) / 1000])
ax_anno.invert_yaxis()
ax_anno.spines['right'].set_visible(False)
ax_anno.spines['top'].set_visible(False)
ax_anno.spines['bottom'].set_visible(False)
ax_anno.spines['left'].set_visible(False)
ax_anno.set_xticks([])
ax_anno.yaxis.tick_right()
ax_anno.set_ylabel('Depth in the brain (mm)')
ax_anno.yaxis.set_label_position('right')
return fig
def plot_stacked_contra_ipsi_psth(units, axs=None):
units = units.proj()
# get event start times: sample, delay, response
period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit')
hemi = _get_units_hemisphere(units)
conds_i = (psth.TrialCondition
& {'trial_condition_name':
'good_noearlylick_left_hit' if hemi == 'left' else 'good_noearlylick_right_hit'}).fetch1('KEY')
conds_c = (psth.TrialCondition
& {'trial_condition_name':
'good_noearlylick_right_hit' if hemi == 'left' else 'good_noearlylick_left_hit'}).fetch1('KEY')
sel_i = (ephys.Unit * psth.UnitSelectivity
& 'unit_selectivity = "ipsi-selective"' & units)
sel_c = (ephys.Unit * psth.UnitSelectivity
& 'unit_selectivity = "contra-selective"' & units)
# ipsi selective ipsi trials
psth_is_it = (psth.UnitPsth * sel_i.proj('unit_posy') & conds_i).fetch(order_by='unit_posy desc')
# ipsi selective contra trials
psth_is_ct = (psth.UnitPsth * sel_i.proj('unit_posy') & conds_c).fetch(order_by='unit_posy desc')
# contra selective contra trials
psth_cs_ct = (psth.UnitPsth * sel_c.proj('unit_posy') & conds_c).fetch(order_by='unit_posy desc')
# contra selective ipsi trials
psth_cs_it = (psth.UnitPsth * sel_c.proj('unit_posy') & conds_i).fetch(order_by='unit_posy desc')
fig = None
if axs is None:
fig, axs = plt.subplots(1, 2, figsize=(20, 20))
assert axs.size == 2
_plot_stacked_psth_diff(psth_cs_ct, psth_cs_it, ax=axs[0], vlines=period_starts, flip=True)
axs[0].set_title('Contra-selective Units')
axs[0].set_ylabel('Unit (by depth)')
axs[0].set_xlabel('Time to go (s)')
_plot_stacked_psth_diff(psth_is_it, psth_is_ct, ax=axs[1], vlines=period_starts)
axs[1].set_title('Ipsi-selective Units')
axs[1].set_ylabel('Unit (by depth)')
axs[1].set_xlabel('Time to go (s)')
return fig
def plot_avg_contra_ipsi_psth(units, axs=None):
units = units.proj()
# get event start times: sample, delay, response
period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit')
hemi = _get_units_hemisphere(units)
good_unit = ephys.Unit & 'unit_quality != "all"'
conds_i = (psth.TrialCondition
& {'trial_condition_name':
'good_noearlylick_left_hit' if hemi == 'left' else 'good_noearlylick_right_hit'}).fetch('KEY')
conds_c = (psth.TrialCondition
& {'trial_condition_name':
'good_noearlylick_right_hit' if hemi == 'left' else 'good_noearlylick_left_hit'}).fetch('KEY')
sel_i = (ephys.Unit * psth.UnitSelectivity
& 'unit_selectivity = "ipsi-selective"' & units)
sel_c = (ephys.Unit * psth.UnitSelectivity
& 'unit_selectivity = "contra-selective"' & units)
psth_is_it = (((psth.UnitPsth & conds_i)
* ephys.Unit.proj('unit_posy'))
& good_unit.proj() & sel_i.proj()).fetch(
'unit_psth', order_by='unit_posy desc')
psth_is_ct = (((psth.UnitPsth & conds_c)
* ephys.Unit.proj('unit_posy'))
& good_unit.proj() & sel_i.proj()).fetch(
'unit_psth', order_by='unit_posy desc')
psth_cs_ct = (((psth.UnitPsth & conds_c)
* ephys.Unit.proj('unit_posy'))
& good_unit.proj() & sel_c.proj()).fetch(
'unit_psth', order_by='unit_posy desc')
psth_cs_it = (((psth.UnitPsth & conds_i)
* ephys.Unit.proj('unit_posy'))
& good_unit.proj() & sel_c.proj()).fetch(
'unit_psth', order_by='unit_posy desc')
fig = None
if axs is None:
fig, axs = plt.subplots(1, 2, figsize=(16, 6))
assert axs.size == 2
_plot_avg_psth(psth_cs_it, psth_cs_ct, period_starts, axs[0],
'Contra-selective')
_plot_avg_psth(psth_is_it, psth_is_ct, period_starts, axs[1],
'Ipsi-selective')
ymax = max([ax.get_ylim()[1] for ax in axs])
for ax in axs:
ax.set_ylim((0, ymax))
return fig
def plot_psth_photostim_effect(units, condition_name_kw=['both_alm'], axs=None):
"""
For the specified `units`, plot PSTH comparison between stim vs. no-stim with left/right trial instruction
The stim location (or other appropriate search keywords) can be specified in `condition_name_kw` (default: both ALM)
"""
units = units.proj()
fig = None
if axs is None:
fig, axs = plt.subplots(1, 2, figsize=(16, 6))
assert axs.size == 2
hemi = _get_units_hemisphere(units)
# no photostim:
psth_n_l = psth.TrialCondition.get_cond_name_from_keywords(['_nostim', '_left'])[0]
psth_n_r = psth.TrialCondition.get_cond_name_from_keywords(['_nostim', '_right'])[0]
psth_n_l = (psth.UnitPsth * psth.TrialCondition & units
& {'trial_condition_name': psth_n_l} & 'unit_psth is not NULL').fetch('unit_psth')
psth_n_r = (psth.UnitPsth * psth.TrialCondition & units
& {'trial_condition_name': psth_n_r} & 'unit_psth is not NULL').fetch('unit_psth')
# with photostim
psth_s_l = psth.TrialCondition.get_cond_name_from_keywords(condition_name_kw + ['_stim_left'])[0]
psth_s_r = psth.TrialCondition.get_cond_name_from_keywords(condition_name_kw + ['_stim_right'])[0]
psth_s_l = (psth.UnitPsth * psth.TrialCondition & units
& {'trial_condition_name': psth_s_l} & 'unit_psth is not NULL').fetch('unit_psth')
psth_s_r = (psth.UnitPsth * psth.TrialCondition & units
& {'trial_condition_name': psth_s_r} & 'unit_psth is not NULL').fetch('unit_psth')
# get event start times: sample, delay, response
period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit') | # get photostim onset and duration
stim_trial_cond_name = psth.TrialCondition.get_cond_name_from_keywords(condition_name_kw + ['_stim'])[0]
stim_durs = np.unique((experiment.Photostim & experiment.PhotostimEvent
* psth.TrialCondition().get_trials(stim_trial_cond_name)
& units).fetch('duration'))
stim_dur = _extract_one_stim_dur(stim_durs)
stim_time = _get_stim_onset_time(units, stim_trial_cond_name)
if hemi == 'left':
psth_s_i = psth_s_l
psth_n_i = psth_n_l
psth_s_c = psth_s_r
psth_n_c = psth_n_r
else:
psth_s_i = psth_s_r
psth_n_i = psth_n_r
psth_s_c = psth_s_l
psth_n_c = psth_n_l
_plot_avg_psth(psth_n_i, psth_n_c, period_starts, axs[0],
'Control')
_plot_avg_psth(psth_s_i, psth_s_c, period_starts, axs[1],
'Photostim')
# cosmetic
ymax = max([ax.get_ylim()[1] for ax in axs])
for ax in axs:
ax.set_ylim((0, ymax))
ax.set_xlim([_plt_xmin, _plt_xmax])
# add shaded bar for photostim
axs[1].axvspan(stim_time, stim_time + stim_dur, alpha=0.3, color='royalblue')
return fig
def plot_coding_direction(units, time_period=None, label=None, axs=None):
# get event start times: sample, delay, response
period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], units, 'good_noearlylick_hit')
_, proj_contra_trial, proj_ipsi_trial, time_stamps, _ = psth.compute_CD_projected_psth(
units.fetch('KEY'), time_period=time_period)
fig = None
if axs is None:
fig, axs = plt.subplots(1, 1, figsize=(8, 6))
# plot
_plot_with_sem(proj_contra_trial, time_stamps, ax=axs, c='b')
_plot_with_sem(proj_ipsi_trial, time_stamps, ax=axs, c='r')
for x in period_starts:
axs.axvline(x=x, linestyle = '--', color = 'k')
# cosmetic
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.set_ylabel('CD projection (a.u.)')
axs.set_xlabel('Time (s)')
if label:
axs.set_title(label)
return fig
def plot_paired_coding_direction(unit_g1, unit_g2, labels=None, time_period=None):
"""
Plot trial-to-trial CD-endpoint correlation between CD-projected trial-psth from two unit-groups (e.g. two brain regions)
Note: coding direction is calculated on selective units, contra vs. ipsi, within the specified time_period
"""
_, proj_contra_trial_g1, proj_ipsi_trial_g1, time_stamps, unit_g1_hemi = psth.compute_CD_projected_psth(
unit_g1.fetch('KEY'), time_period=time_period)
_, proj_contra_trial_g2, proj_ipsi_trial_g2, time_stamps, unit_g2_hemi = psth.compute_CD_projected_psth(
unit_g2.fetch('KEY'), time_period=time_period)
# get event start times: sample, delay, response
period_names, period_starts = _get_trial_event_times(['sample', 'delay', 'go'], unit_g1, 'good_noearlylick_hit')
if labels:
assert len(labels) == 2
else:
labels = ('unit group 1', 'unit group 2')
# plot projected trial-psth
fig, axs = plt.subplots(1, 2, figsize=(16, 6))
_plot_with_sem(proj_contra_trial_g1, time_stamps, ax=axs[0], c='b')
_plot_with_sem(proj_ipsi_trial_g1, time_stamps, ax=axs[0], c='r')
_plot_with_sem(proj_contra_trial_g2, time_stamps, ax=axs[1], c='b')
_plot_with_sem(proj_ipsi_trial_g2, time_stamps, ax=axs[1], c='r')
# cosmetic
for ax, label in zip(axs, labels):
for x in period_starts:
ax.axvline(x=x, linestyle = '--', color = 'k')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_ylabel('CD projection (a.u.)')
ax.set_xlabel('Time (s)')
ax.set_title(label)
# plot trial CD-endpoint correlation - if 2 unit-groups are from 2 hemispheres,
# then contra-ipsi definition is based on the first group
p_start, p_end = time_period
contra_cdend_1 = proj_contra_trial_g1[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
ipsi_cdend_1 = proj_ipsi_trial_g1[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
if unit_g1_hemi == unit_g1_hemi:
contra_cdend_2 = proj_contra_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
ipsi_cdend_2 = proj_ipsi_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
else:
contra_cdend_2 = proj_ipsi_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
ipsi_cdend_2 = proj_contra_trial_g2[:, np.logical_and(time_stamps >= p_start, time_stamps < p_end)].mean(axis=1)
c_df = pd.DataFrame([contra_cdend_1, contra_cdend_2]).T
c_df.columns = labels
c_df['trial-type'] = 'contra'
i_df = pd.DataFrame([ipsi_cdend_1, ipsi_cdend_2]).T
i_df.columns = labels
i_df['trial-type'] = 'ipsi'
df = c_df.append(i_df)
jplot = _jointplot_w_hue(data=df, x=labels[0], y=labels[1], hue= 'trial-type', colormap=['b', 'r'],
figsize=(8, 6), fig=None, scatter_kws=None)
jplot['fig'].show()
return fig
# ========== Foraging task ==========
def plot_unit_period_fit(linear_model='Q_rel + Q_tot + rpe'):
#%%
# linear_model='Q_c + Q_i + rpe'
q_unit = ((ephys.Unit * ephys.ClusterMetric * ephys.UnitStat * ephys.MAPClusterMetric.DriftMetric)
& 'presence_ratio > 0.95'
& 'amplitude_cutoff < 0.1'
& 'isi_violation < 0.5'
& 'unit_amp > 70'
# & 'drift_metric < 0.1'
)
q_hist = (q_unit * histology.ElectrodeCCFPosition.ElectrodePosition) * ccf.CCFAnnotation
q_unit_n = dj.U('annotation').aggr(q_hist, area_num_units='count(*)')
q_hist *= q_unit_n
lvs = (psth_foraging.LinearModel.X & {'multi_linear_model': linear_model}).fetch('var_name')
q_all = ((psth_foraging.UnitPeriodLinearFit
* psth_foraging.UnitPeriodLinearFit.Param
* q_hist)
& {'multi_linear_model': linear_model})
#%%
# -- Heatmap ---
# for lv in zip(lvs):
# fig, ax = plt.subplots(1, 1, figsize=(13, 15))
# df = pd.DataFrame((q_all & {'var_name': lv}).proj('beta', 'p', 't', 'area_num_units').fetch())
# df = df.pivot(index=['subject_id', 'session', 'insertion_number',
# 'clustering_method', 'unit', 'annotation', 'area_num_units'],
# columns='period', values='t')
# df.sort_values(by=['area_num_units', 'iti_all'], ascending=False , inplace=True)
# df = df.reset_index().drop(['subject_id', 'session', 'insertion_number',
# 'clustering_method', 'unit', 'area_num_units'], axis=1)
# df = df.set_index('annotation')
# sns.heatmap(df, ax=ax, cmap='coolwarm')
# ax.set_position([0.5, 0.1, 0.2, 0.8])
#%%
# -- t distribution --
epochs = ['delay', 'go_to_end', 'iti_first_2', 'iti_last_2']
fig, axs = plt.subplots(len(lvs), len(epochs), figsize=(4*len(epochs), 4*len(lvs)))
areas = q_unit_n.fetch(order_by='area_num_units desc', format='frame')
# Areas that have most number of neurons
areas = list(areas.index[:10])
for i, lv in enumerate(lvs):
for j, ep in enumerate(epochs):
ax = axs[i, j]
ax.axhline(y=0.95, color='k', linestyle=':')
ax.axvline(x=1.96, color='k', linestyle=':')
for area in areas:
this_ts = (q_all & {'var_name': lv, 'period': ep, 'annotation': area}).fetch('t')
values, bin = np.histogram(np.abs(this_ts), 100)
ax.plot(bin[:-1], np.cumsum(values)/len(this_ts), label=f'{area}, n = {len(this_ts)}')
ax.set(xlim=(0, 10))
ax.label_outer()
if i == 0:
ax.set_title(ep)
if j == 0:
ax.set_ylabel(lv)
if i == len(lvs) - 1 and j == 0:
ax.set_xlabel('|t value|')
ax.legend(bbox_to_anchor=(-1,3), loc='upper left')
#%%
# -- ipsi and contra action value weights --
fig, axs = plt.subplots(1,2, figsize=(8,4))
if linear_model == 'Q_c + Q_i + rpe':
lvs = ['ipsi_action_value', 'contra_action_value']
elif linear_model == 'Q_l + Q_r + rpe':
lvs = ['left_action_value', 'right_action_value']
else:
lvs = ['relative_action_value_ic', 'total_action_value']
for j, ep in enumerate(['go_to_end', 'iti_all']):
ax = axs[j]
for area in areas:
# if not 'thalamus' in area:
# continue
ax.axhline(y=-2, color='k', ls='--', lw=.5)
ax.axhline(y=2, color='k', ls='--', lw=.5)
ax.axvline(x=-2, color='k', ls='--', lw=.5)
ax.axvline(x=2, color='k', ls='--', lw=.5)
df = pd.DataFrame((q_all
& {'annotation': area}
& {'period': ep}).proj('beta', 'p', 'area_num_units', 't').fetch())
betas = df.pivot(index=['subject_id', 'session', 'insertion_number',
'clustering_method', 'unit', 'annotation', 'area_num_units'],
columns='var_name', values='t')
ps = df.pivot(index=['subject_id', 'session', 'insertion_number',
'clustering_method', 'unit', 'annotation', 'area_num_units'],
columns='var_name', values='p')
sizes = 2 + 2 * np.sum(ps.values < 0.05, axis=1)
ax.scatter(x=betas[lvs[0]], y=betas[lvs[1]], s=sizes)
ax.set_xlim([-20, 20])
ax.set_ylim([-20, 20])
ax.set_xlabel(lvs[0])
ax.set_ylabel(lvs[1])
ax.set_title(ep)
ax.label_outer()
# sns.scatterplot(data=betas, x='ipsi_action_value', y='contra_action_value',
# hue='annotation', sizes=sizes, legend=False)
#%%
def plot_example_cells(sort_lv = 'relative_action_value_ic',
sort_ep = 'iti_all',
best_n = 10, linear_model='Q_rel + Q_tot + rpe'):
#%%
q_unit = ((ephys.Unit * ephys.ClusterMetric * ephys.UnitStat * ephys.MAPClusterMetric.DriftMetric)
& 'presence_ratio > 0.95'
& 'amplitude_cutoff < 0.1'
& 'isi_violation < 0.5'
& 'unit_amp > 100'
# & 'drift_metric < 0.1'
)
q_hist = (q_unit * histology.ElectrodeCCFPosition.ElectrodePosition) * ccf.CCFAnnotation
q_unit_n = dj.U('annotation').aggr(q_hist, area_num_units='count(*)')
q_hist *= q_unit_n
lvs = (psth_foraging.LinearModel.X & {'multi_linear_model': linear_model}).fetch('var_name')
q_all = ((psth_foraging.UnitPeriodLinearFit
* psth_foraging.UnitPeriodLinearFit.Param
* q_hist)
& {'multi_linear_model': linear_model})
# Best n (absolute value)
best_models = (q_all & f'var_name = "{sort_lv}"' & f'period = "{sort_ep}"').proj(
'actual_behavior_model', abs_t='abs(t)').fetch(order_by='abs_t desc', limit=best_n, format='frame')
for unit_key in best_models.reset_index().to_dict('records'):
unit_psth.plot_unit_psth_choice_outcome(unit_key)
unit_psth.plot_unit_psth_latent_variable_quantile(unit_key,
model_id=unit_key['actual_behavior_model'])
unit_psth.plot_unit_period_tuning(unit_key)
#%%
# =========== HELPER ==============
def get_m_scale(shank_count):
return 1350 - 150*shank_count | |
process_snapshot.rs | //! process-snapshot
use crate::{
read_snapshot::{self},
recover::{accounts_into_recovery, LegacyRecovery},
};
use anyhow::{bail, Error, Result};
use backup_cli::backup_types::state_snapshot::manifest::StateSnapshotBackup;
use diem_types::{
access_path::AccessPath,
account_config::AccountResource,
account_state::AccountState,
account_state_blob::AccountStateBlob,
write_set::{WriteOp, WriteSetMut},
};
use move_core_types::move_resource::MoveResource;
use ol_keys::wallet::get_account_from_mnem;
use ol_types::fixtures;
use std::convert::TryFrom;
use std::path::PathBuf;
/// take an archive file path and parse into a writeset
pub async fn archive_into_swarm_writeset(archive_path: PathBuf) -> Result<WriteSetMut, Error> {
let backup = read_snapshot::read_from_json(&archive_path)?;
let account_blobs = accounts_from_snapshot_backup(backup, &archive_path).await?;
accounts_into_writeset_swarm(&account_blobs)
}
/// take an archive file path and parse into a writeset
pub async fn archive_into_recovery(
archive_path: &PathBuf,
is_legacy: bool,
) -> Result<Vec<LegacyRecovery>, Error> {
let manifest_json = archive_path.join("state.manifest");
let backup = read_snapshot::read_from_json(&manifest_json)?;
let account_blobs = accounts_from_snapshot_backup(backup, archive_path).await?;
let r = if is_legacy {
println!("Parsing account state from legacy, Libra structs");
todo!();
} else {
println!("Parsing account state from Diem structs");
accounts_into_recovery(&account_blobs)?
};
Ok(r)
}
/// Tokio async parsing of state snapshot into blob
async fn accounts_from_snapshot_backup(
manifest: StateSnapshotBackup,
archive_path: &PathBuf,
) -> Result<Vec<AccountStateBlob>, Error> {
// parse AccountStateBlob from chunks of the archive
let mut account_state_blobs: Vec<AccountStateBlob> = Vec::new();
for chunk in manifest.chunks {
// dbg!(&archive_path);
let blobs = read_snapshot::read_account_state_chunk(chunk.blobs, archive_path).await?;
// println!("{:?}", blobs);
for (_key, blob) in blobs {
account_state_blobs.push(blob)
}
}
Ok(account_state_blobs)
}
fn get_alice_authkey_for_swarm() -> Vec<u8> {
let mnemonic_string = fixtures::get_persona_mnem("alice");
let account_details = get_account_from_mnem(mnemonic_string).unwrap();
account_details.0.to_vec()
}
/// make the writeset for the genesis case. Starts with an unmodified account state and make into a writeset.
fn accounts_into_writeset_swarm(
account_state_blobs: &Vec<AccountStateBlob>,
) -> Result<WriteSetMut, Error> {
let mut write_set_mut = WriteSetMut::new(vec![]);
for blob in account_state_blobs {
let account_state = AccountState::try_from(blob)?;
// TODO: borrow
let clean = get_unmodified_writeset(&account_state)?;
let auth = authkey_rotate_change_item(&account_state, get_alice_authkey_for_swarm())?;
let merge_clean = merge_writeset(write_set_mut, clean)?;
write_set_mut = merge_writeset(merge_clean, auth)?;
}
println!("Total accounts read: {}", &account_state_blobs.len());
Ok(write_set_mut)
}
/// Without modifying the data convert an AccountState struct, into a WriteSet Item which can be included in a genesis transaction. This should take all of the resources in the account.
fn get_unmodified_writeset(account_state: &AccountState) -> Result<WriteSetMut, Error> {
let mut ws = WriteSetMut::new(vec![]);
if let Some(address) = account_state.get_account_address()? {
// iterate over all the account's resources\
for (k, v) in account_state.iter() {
let item_tuple = (
AccessPath::new(address, k.clone()),
WriteOp::Value(v.clone()),
);
// push into the writeset
ws.push(item_tuple);
}
println!("processed account: {:?}", address);
return Ok(ws);
}
bail!("ERROR: No address for AccountState: {:?}", account_state);
}
/// Returns the writeset item for replaceing an authkey on an account. This is only to be used in testing and simulation.
fn authkey_rotate_change_item(
account_state: &AccountState,
authentication_key: Vec<u8>,
) -> Result<WriteSetMut, Error> {
let mut ws = WriteSetMut::new(vec![]);
if let Some(address) = account_state.get_account_address()? {
// iterate over all the account's resources
for (k, _v) in account_state.iter() {
// if we find an AccountResource struc, which is where authkeys are kept
if k.clone() == AccountResource::resource_path() {
// let account_resource_option = account_state.get_account_resource()?;
if let Some(account_resource) = account_state.get_account_resource()? {
let ar = account_resource.rotate_auth_key(authentication_key.clone());
ws.push((
AccessPath::new(address, k.clone()),
WriteOp::Value(bcs::to_bytes(&ar).unwrap()),
));
}
}
}
println!("rotate authkey for account: {:?}", address);
}
bail!(
"ERROR: No address found at AccountState: {:?}",
account_state
);
}
/// helper to merge writesets
pub fn | (left: WriteSetMut, right: WriteSetMut) -> Result<WriteSetMut, Error> {
let mut merge = left.get();
merge.extend(right.get());
Ok(WriteSetMut::new(merge))
}
#[test]
pub fn test_accounts_into_recovery() {
use diem_types::{account_config::BalanceResource, validator_config::ValidatorConfigResource};
use move_core_types::move_resource::MoveResource;
use ol_types::miner_state::TowerStateResource;
use std::path::Path;
let path = env!("CARGO_MANIFEST_DIR");
let buf = Path::new(path)
.parent()
.unwrap()
.join("fixtures/state-snapshot/194/state_ver_74694920.0889/");
let path_man = buf.clone().join("state.manifest");
println!("Running.....");
let backup = crate::read_snapshot::read_from_json(&path_man).unwrap();
let account_blobs_futures = accounts_from_snapshot_backup(backup, &path_man);
let account_blobs = tokio_test::block_on(account_blobs_futures).unwrap();
let genesis_recovery_list = accounts_into_recovery(&account_blobs).unwrap();
println!(
"Total GenesisRecovery objects: {}",
&genesis_recovery_list.len()
);
for blob in account_blobs {
let account_state = AccountState::try_from(&blob).unwrap();
if let Some(address) = account_state.get_account_address().unwrap() {
let mut address_processed = false;
for gr in &genesis_recovery_list {
if gr.account != Some(address) {
continue;
}
// iterate over all the account's resources\
for (k, v) in account_state.iter() {
// extract the validator config resource
if k.clone() == BalanceResource::resource_path() {
match &gr.balance {
Some(balance) => {
if bcs::to_bytes(&balance).unwrap() != v.clone() {
panic!("Balance resource not found in GenesisRecovery object: {:?}", gr.account);
}
}
None => {
panic!("Balance not found");
}
}
}
if k.clone() == ValidatorConfigResource::resource_path() {
match &gr.val_cfg {
Some(val_cfg) => {
if bcs::to_bytes(&val_cfg).unwrap() != v.clone() {
panic!("ValidatorConfigResource not found in GenesisRecovery object: {:?}", gr.account);
}
}
None => {
panic!("ValidatorConfigResource not found");
}
}
}
if k.clone() == TowerStateResource::resource_path() {
match &gr.miner_state {
Some(miner_state) => {
if bcs::to_bytes(&miner_state).unwrap() != v.clone() {
panic!("TowerStateResource not found in GenesisRecovery object: {:?}", gr.account);
}
}
None => {
panic!("TowerStateResource not found");
}
}
}
}
println!("processed account: {:?}", address);
address_processed = true;
break;
}
if !address_processed {
panic!("Address not found for {} in recovery list", &address);
}
};
}
}
| merge_writeset |
issue50516.go | // Copyright 2022 The 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 p
func _[P struct{ f int }](x P) |
func _[P struct{ f int } | struct{ g int }](x P) {
_ = x.g // ERROR type P has no field or method g
}
| {
_ = x.g // ERROR type P has no field or method g
} |
anycluster.js | "use strict";
var gridColorValues = {
5: "pink",
10: "lightcoral",
50: "coral",
100: "orange",
1000: "orangered",
10000: "red"
};
//set marker sizes according to your images for correct display
var markerImageSizes = {
1: [24,39],
5 : [30,30],
10: [30,30],
50: [40,40],
100: [40,40],
1000: [50,50],
10000: [60,60]
};
var Anycluster = function(mapdiv_id, settings_, mapInitCallback){
this.mapdiv_id = mapdiv_id;
if (typeof mapInitCallback === "function") {
google.maps.event.addDomListener(window, 'load', mapInitCallback);
}
this.loadSettings(settings_);
this.viewportMarkerCount = 0;
this.markerList = [];
this.clearMarkers = false;
for (let key in this.api[this.mapType]){
this[key] = this.api[this.mapType][key];
}
this.initialize();
};
Anycluster.prototype = {
loadSettings : function(settings_) {
this.baseURL = settings_.baseURL || "/anycluster/";
this.autostart = typeof(settings_.autostart) == "boolean" ? settings_.autostart : true;
this.filters = settings_.filters || [];
this.center = settings_.center || [0,0];
this.clusterMethod = settings_.clusterMethod || "grid";
this.iconType = settings_.iconType || "exact";
this.gridSize = settings_.gridSize || 64;
this.mapType = settings_.mapType; // "google" or "leaflet"
this.zoom = settings_.zoom || 3;
this.singlePinImages = settings_.singlePinImages ? settings_.singlePinImages : {};
this.onFinalClick = settings_.onFinalClick || this.onFinalClick;
this.loadEnd = settings_.loadEnd || this.loadEnd;
this.loadStart = settings_.loadStart || this.loadStart;
this.clusterArea = settings_.clusterArea || false;
this.returnFormat = settings_.returnFormat || "html"; // return format for final clicks, html or json
this.mobile = settings_.mobile || false;
this.markerFolder = settings_.markerFolder || "/static/anycluster/images/";
if (this.mapType == "kmeans"){
this.gridSize = 256;
}
// api specific settings
if (this.mapType == "google"){
this.api_settings = settings_.google || {};
}
else if (this.mapType == "leaflet"){
this.api_settings = settings_.leaflet || {};
}
for (let key in this.api[this.mapType]["default_settings"]){
if (!(this.api_settings.hasOwnProperty(key)) ){
this.api_settings[key] = this.api[this.mapType]["default_settings"][key];
}
}
},
prepare_xhr : function(xhr){
if (this.mobile == true){
xhr.withCredentials = true;
}
else {
var csrftoken = getCookieValue("csrftoken");
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
return xhr;
},
// on small markers or on final zoom, this function is launched
markerFinalClickFunction : function(mapmarker) {
var clusterer = this;
if (clusterer.clusterMethod == "kmeans") {
clusterer.getClusterContent(mapmarker, function(data){
clusterer.onFinalClick(mapmarker, data);
});
}
else if (clusterer.clusterMethod = "grid"){
var geojson = mapmarker["geojson"];
clusterer.getAreaContent(geojson, function(data){
clusterer.onFinalClick(mapmarker, data);
});
}
},
// hook for you to implement what happens if a user clicks on the final marker
// data cen be html or json, depending on this.returnFormat
onFinalClick: function(mapmarker, data){
alert(data);
},
markerClickFunction : function(marker) {
this.removeAllMarkers();
this.setMap(marker.longitude, marker.latitude);
},
filter: function(filterObj){
this.filters = filterObj;
this.clearMarkers = true;
this.cluster();
},
addFilters: function(newfilters){
for (var f=0; f<newfilters.length; f++){
this.filters.push(newfilters[f]);
}
this.clearMarkers = true;
},
removeFilters: function(activefilters){
for (i=0; i<= activefilters.length; i++){
delete this.filters[ activefilters[i] ];
}
this.clearMarkers = true;
},
cluster : function(cache, clusteredCB){
if (this.clusterArea == false){
var viewport_json = this.getViewport();
var geoJson = this.viewportToGeoJson(viewport_json);
var geometry_type = "viewport";
}
else {
var geoJson = clusterer.clusterArea;
var geometry_type = "strict";
}
this.getClusters(geoJson, geometry_type, clusteredCB, cache);
},
getClusters : function(geoJson, geometry_type, gotClusters, cache){
this.zoom = this.getZoom();
var clusterer = this;
this.loadStart();
var url = this.baseURL + this.clusterMethod + '/' + this.zoom + '/' + this.gridSize + '/';
var postParams = {
'geojson' : geoJson,
'filters': this.filters,
'geometry_type': geometry_type
};
if (cache === true){
postParams['cache'] = 'load';
}
//send the ajax request
url = encodeURI(url);
var xhr = new XMLHttpRequest();
xhr.onload = function(){
console.log("[xhr] finished with status " + xhr.status);
if (clusterer.clearMarkers == true){
clusterer.removeAllMarkers();
}
var clusters = JSON.parse(xhr.responseText);
//route the clusters
if (clusterer.clusterMethod == "grid"){
var clusterFunction = clusterer.drawCell;
}
else if (clusterer.clusterMethod == "kmeans"){
if (clusterer.iconType == "simple"){
var clusterFunction = clusterer.drawMarker;
}
else {
var clusterFunction = clusterer.drawMarkerExactCount;
}
}
if (clusters.length > 0 && geometry_type == "strict"){
clusterer.removeAllMarkers();
}
for (let i=0; i<clusters.length; i++) {
var cluster = clusters[i];
if ( cluster.count == 1) {
clusterer.drawMarker(clusterer, cluster);
}
else {
clusterFunction(clusterer, cluster);
}
}
clusterer.post_clustering();
//update totalcount
clusterer.viewportMarkerCount = clusterer.getViewportMarkerCount();
clusterer.loadEnd();
if (typeof clusteredCB === "function") {
gotClusters();
}
}
xhr.open("POST", url, true);
xhr = this.prepare_xhr(xhr);
xhr.send(JSON.stringify(postParams));
},
getClusterContent : function(cluster, gotClusterContent){
var clusterer = this;
var postParams = {
"x": cluster.longitude,
"y": cluster.latitude,
"ids": cluster.ids,
"filters": this.filters
}
var url = this.baseURL + "getClusterContent/" + this.zoom + "/" + this.gridSize + "/";
if (this.returnFormat == "json"){
url += '?format=json';
}
url = encodeURI(url);
var xhr = new XMLHttpRequest();
xhr.onload = function(){
var data = xhr.responseText;
if (clusterer.returnFormat == "json"){
data = JSON.parse(data);
}
gotClusterContent(data);
}
xhr.open("POST",url,true);
xhr = this.prepare_xhr(xhr);
xhr.send(JSON.stringify(postParams));
},
getViewportContent : function(gotViewportContent){
var viewport_json = this.getViewport();
var geoJson = this.viewportToGeoJson(viewport_json);
this.getAreaContent(geoJson, gotViewportContent);
},
getAreaContent : function(geoJson, gotAreaContent){
var clusterer = this;
this.zoom = this.getZoom();
var postParams = {
"geojson":geoJson,
"filters":this.filters
}
var url = this.baseURL + "getAreaContent/" + this.zoom + "/" + this.gridSize + "/"
if (this.returnFormat == 'json'){
url += '?format=json';
}
url = encodeURI(url);
var xhr = new XMLHttpRequest();
xhr.onload = function(){
var data = xhr.responseText;
if (clusterer.returnFormat == "json"){
data = JSON.parse(data);
}
gotAreaContent(data);
}
xhr.open("POST",url,true);
xhr = this.prepare_xhr(xhr);
xhr.send(JSON.stringify(postParams));
},
_max_bounds : {
"left" : -179,
"top" : 89,
"right" : 179,
"bottom" : -89
},
viewportToGeoJson : function(viewport){
if (viewport["left"] < this._max_bounds["left"]){
viewport["left"] = this._max_bounds["left"];
}
if (viewport["bottom"] < this._max_bounds["bottom"]){
viewport["bottom"] = this._max_bounds["bottom"];
}
if (viewport["top"] > this._max_bounds["top"]){
viewport["top"] = this._max_bounds["top"];
}
if (viewport["right"] > this._max_bounds["right"]){
viewport["right"] = this._max_bounds["right"];
}
// check if the viewport spans the edges of coordinate system
if (viewport["left"] > viewport["right"]) {
var geomtype = "MultiPolygon";
var coordinates = [ [
[ viewport["left"], viewport["top"] ],
[ 179, viewport["top"] ],
[ 179, viewport["bottom"] ],
[ viewport["left"], viewport["bottom"] ],
[ viewport["left"], viewport["top"] ]
],
[
[ -179, viewport["top"] ],
[ viewport["right"], viewport["top"] ],
[ viewport["right"], viewport["bottom"] ],
[ -179, viewport["bottom"] ],
[ -179, viewport["top"] ]
]];
}
else {
var geomtype = "Polygon";
var coordinates = [ [
[ viewport["left"], viewport["top"] ],
[ viewport["right"], viewport["top"] ],
[ viewport["right"], viewport["bottom"] ],
[ viewport["left"], viewport["bottom"] ],
[ viewport["left"], viewport["top"] ]
]];
}
var geoJson = {
"type": "Feature",
"properties" : {},
"geometry": {
"type": geomtype,
"coordinates": coordinates
}
}
return geoJson;
},
selectPinIcon : function(cluster) {
var count = cluster["count"];
var pinimg = cluster["pinimg"];
if (count == 1) {
var singlePinURL = "" + this.markerFolder + "pin_unknown.png";
if( typeof(this.singlePinImages) == "function"){
singlePinURL = this.singlePinImages(cluster);
}
else {
if (this.singlePinImages.hasOwnProperty(pinimg)){
singlePinURL = this.singlePinImages[pinimg];
}
}
}
else if (count > 10000){
var pinicon = "10000";
}
else if (count > 1000) {
var pinicon = "1000";
}
else if (count > 100) {
var pinicon = "100";
}
else if (count > 50) {
var pinicon = "50";
}
else if (count > 10) {
var pinicon = "10";
}
else {
var pinicon = "5";
}
if (count == 1){
var imgurl = singlePinURL;
var pinicon = "1";
}
else {
if (this.iconType == "exact"){
var imgurl = "" + this.markerFolder + pinicon + "_empty.png";
}
else {
var imgurl = "" + this.markerFolder + pinicon + ".png";
}
}
var size = markerImageSizes[pinicon];
if (count == 1){
var anchor = [parseInt(size[0]/2), size[1]-1];
}
else {
var anchor = [parseInt(size[0]/2), parseInt(size[1]/2)];
}
var imgObj = {
url : imgurl,
size : size,
anchor: anchor,
popupAnchor: [0, -parseInt(size[1]) + 8]
}
return imgObj;
},
urlizeObject: function(obj){
var urlParams = "?";
var first = true;
for (var key in obj){
if (first == true){
first = false;
urlParams = urlParams + key + "=" + obj[key];
}
else {
urlParams = urlParams + "&" + key + "=" + obj[key];
}
}
return urlParams;
},
markerIsInRectangle: function(marker, rectangle){
if (rectangle["right"] > marker.longitude && rectangle["left"] < marker.longitude && rectangle["top"] > marker.latitude && rectangle["bottom"] < marker.latitude) {
return true; | },
getViewportMarkerCount: function(){
var viewport = this.getViewport();
var totalCount = 0;
for (var i=0; i<this.markerList.length; i++){
var marker = this.markerList[i];
if (viewport["left"] > viewport["right"]) {
var viewport_part1 = {"left": viewport["left"], "top": viewport["top"], "right": 180, "bottom": viewport["bottom"]},
viewport_part2 = {"left": -180, "top": viewport["top"], "right": viewport["right"], "bottom": viewport["bottom"]};
if ( this.markerIsInRectangle(marker, viewport_part1) || this.markerIsInRectangle(marker, viewport_part2) ){
totalCount += marker.count;
}
}
else {
if ( this.markerIsInRectangle(marker, viewport) ){
totalCount += marker.count;
}
}
}
return totalCount;
},
loadStart : function(){},
loadEnd : function(){},
api : {
"google" : {
default_settings : {
"mapTypeId" : "HYBRID"
},
initialize : function(){
var googleOptions = {
zoom: this.zoom,
scrollwheel: false,
center: new google.maps.LatLng(this.center[0], this.center[1]),
mapTypeId: google.maps.MapTypeId[this.MapTypeId]
}
this.map = new google.maps.Map(document.getElementById(this.mapdiv_id), googleOptions);
if (this.autostart == true){
this.startClustering();
}
},
startClustering : function(){
var clusterer = this;
var firstLoad = true;
google.maps.event.addListener(this.map, "idle", function() {
if (firstLoad === true){
firstLoad = false;
clusterer.cluster(true);
}
else {
clusterer.cluster(false);
}
});
google.maps.event.addListener(this.map, "zoom_changed", function() {
clusterer.removeAllMarkers();
});
},
setMap : function(lng, lat){
var zoom = this.map.getZoom();
zoom = zoom + 3;
this.zoom = zoom;
var center = new google.maps.LatLng(lat,lng);
this.map.setCenter(center, zoom);
this.map.setZoom(zoom);
},
add_marker_click_listener : function(marker, count){
var clusterer = this;
if (clusterer.zoom >= 13 || count <= 3) {
google.maps.event.addListener(marker, "click", function() {
clusterer.markerFinalClickFunction(this);
});
}
else {
google.maps.event.addListener(marker, "click", function() {
clusterer.markerClickFunction(this);
});
}
},
drawMarker : function(clusterer, cluster){
var center = new google.maps.LatLng(cluster["center"]["y"], cluster["center"]["x"]);
var count = cluster["count"];
var pinimg = cluster["pinimg"];
var ids = cluster["ids"];
var piniconObj = clusterer.selectPinIcon(cluster);
var pinicon = piniconObj.url;
var marker = new google.maps.Marker({
position: center,
latitude: center.lat(),
longitude: center.lng(),
map: clusterer.map,
count: count,
icon: pinicon,
geojson: cluster.geojson,
ids: ids
});
clusterer.markerList.push(marker);
clusterer.add_marker_click_listener(marker, count);
},
drawMarkerExactCount : function(clusterer, cluster){
var center = new google.maps.LatLng(cluster["center"]["y"], cluster["center"]["x"]);
var count = cluster["count"];
var pinimg = cluster["pinimg"];
var ids = cluster["ids"];
var marker = new clusterMarker(center, count, clusterer.map, ids);
clusterer.markerList.push(marker);
clusterer.add_marker_click_listener(marker, count);
},
drawCell : function(clusterer, cluster){
var geojson = {
"type": "Feature",
"count": cluster.count,
"geometry": JSON.parse(cluster.geojson),
"properties": {"count": cluster.count}
}
clusterer.map.data.addGeoJson(geojson);
},
post_clustering : function(){
this.paintGridColors();
},
paintGridColors : function(){
var clusterer = this;
var setColorStyleFn = function(feature) {
var count = feature.getProperty("count");
var rounded_count = roundMarkerCount(count);
return {
fillColor: gridColorValues[rounded_count],
strokeWeight: 0
};
}
this.map.data.setStyle(setColorStyleFn);
},
getZoom : function(){
return this.map.getZoom();
},
getViewport : function(){
var viewport = this.map.getBounds();
var viewport_json = {
"left" : viewport.getSouthWest().lng(),
"top" : viewport.getNorthEast().lat(),
"right" : viewport.getNorthEast().lng(),
"bottom" : viewport.getSouthWest().lat()
};
return viewport_json;
},
removeAllMarkers : function(){
var clusterer = this;
for (var i=0; i<this.markerList.length; i+=1){
this.markerList[i].setMap(null);
}
if (typeof(this.map.data) == "object"){
this.map.data.forEach(function(feature){
clusterer.map.data.remove(feature);
});
}
this.clearMarkers = false;
this.markerList.length = 0;
}
},
"leaflet" : {
default_settings : {
"layers": {
"streets" : L.tileLayer("https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png",
{
attribution: "© OpenStreetMap, Tiles courtesy of Humanitarian OpenStreetMap Team",
subdomains: "ab"
}
),
"satellite" : L.layerGroup([
L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
{
attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
maxZoom: 20,
maxNativeZoom: 18
}
),
L.tileLayer('http://{s}.tile.stamen.com/toner-labels/{z}/{x}/{y}.{ext}',
{
attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap',
subdomains: 'abcd',
minZoom: 0,
maxNativeZoom: 18,
maxZoom: 20,
ext: 'png'
}
)
])
}
},
initialize : function(){
var map = L.map(this.mapdiv_id, {
center: this.center,
zoom: this.zoom,
scrollWheelZoom: false,
layers: this.api_settings["layers"]["streets"]
});
L.control.layers(this.api_settings["layers"], {}, {"position":"topright"}).addTo(map);
var markerLayers = L.layerGroup().addTo(map);
map.markerLayers = markerLayers;
// support geojson for grid cluster
var geoJsonLayers = L.layerGroup().addTo(map);
map.geoJsonLayers = geoJsonLayers;
this.map = map;
if (this.autostart == true){
this.startClustering();
}
},
startClustering : function(){
var firstLoad = true;
var clusterer = this;
clusterer.cluster(true);
this.map.addEventListener("moveend", function(event){
clusterer.cluster(false);
});
this.map.addEventListener("zoomend", function(event) {
clusterer.removeAllMarkers();
});
},
getViewport : function(){
var viewport = this.map.getBounds();
var viewport_json = {
"left" : viewport.getSouthWest().lng,
"top" : viewport.getNorthEast().lat,
"right" : viewport.getNorthEast().lng,
"bottom" : viewport.getSouthWest().lat
};
return viewport_json;
},
getZoom : function(){
return this.map.getZoom();
},
add_marker_click_listener : function(marker, count){
var clusterer = this;
if (clusterer.zoom >= 13 || count <= 3) {
marker.on("click", function(event) {
clusterer.markerFinalClickFunction(this);
});
}
else {
marker.on("click", function(event) {
clusterer.markerClickFunction(this);
});
}
},
drawMarkerOnMap : function(cluster, clusterIcon){
var clusterer = this;
var latLng = L.latLng(cluster["center"]["y"], cluster["center"]["x"]);
var count = cluster["count"];
var pinimg = cluster["pinimg"];
var marker_options = {
icon : clusterIcon
};
var marker = L.marker(latLng, marker_options);
// add properties required by anycluster to marker
marker.latitude = latLng.lat;
marker.longitude = latLng.lng;
marker.count = count;
if (cluster.hasOwnProperty("ids")){
marker.ids = cluster["ids"];
}
if (cluster.hasOwnProperty("geojson")){
var geojson = {
"type": "Feature",
"count": count,
"geometry": JSON.parse(cluster.geojson),
"properties": {"count": count}
};
marker.geojson = geojson;
}
clusterer.add_marker_click_listener(marker, count);
marker.addTo(clusterer.map.markerLayers);
clusterer.markerList.push(marker);
},
drawMarker : function(clusterer, cluster){
var count = cluster["count"];
var pinimg = cluster["pinimg"];
// get the correct icon
var piniconObj = clusterer.selectPinIcon(cluster);
// create a leaflet icon
var clusterIcon = L.icon({
iconUrl: piniconObj.url,
iconSize: piniconObj.size,
iconAnchor: piniconObj.anchor,
popupAnchor: piniconObj.popupAnchor
});
clusterer.drawMarkerOnMap(cluster, clusterIcon);
},
drawMarkerExactCount : function(clusterer, cluster){
var count = cluster['count'];
var pinimg = cluster['pinimg'];
var piniconObj = clusterer.selectPinIcon(cluster);
// exact count needs "marker with text"
var clusterIcon = L.divIcon({
html : '<div class="clusterMarkerText exactCountCluster" style="background-image:url(' + piniconObj.url + ');"><div>' + count + '</div></div>',
iconSize: piniconObj.size,
iconAnchor: piniconObj.anchor
});
clusterer.drawMarkerOnMap(cluster, clusterIcon);
},
setMap : function(lng, lat){
var center = L.latLng(lat, lng);
var zoom = this.map.getZoom();
zoom = zoom + 3;
this.zoom = zoom;
// setView(<LatLng> center, <Number> zoom, <Zoom/pan options> options?)
this.map.setView(center, zoom);
},
removeAllMarkers : function(){
// remove all the markers in one go
this.map.markerLayers.clearLayers();
if (this.map.hasOwnProperty("geoJsonLayers")){
this.map.geoJsonLayers.clearLayers();
}
this.clearMarkers = false;
this.markerList.length = 0;
},
drawCell : function(clusterer, cluster){
var count = cluster.count;
var latLng = L.latLng(cluster["center"]["y"], cluster["center"]["x"]);
var geojson = {
"type": "Feature",
"count": count,
"geometry": JSON.parse(cluster.geojson),
"properties": {"count": cluster.count}
};
var rounded_count = roundMarkerCount(count);
var fillColor = gridColorValues[rounded_count];
var strokeWeight = 0;
var cell = L.geoJSON(geojson, {
style: function (feature) {
return {
color: fillColor,
stroke: false
};
}
});
// add properties required by anycluster to marker
cell.latitude = latLng.lat;
cell.longitude = latLng.lng;
cell.count = count;
cell.geojson = geojson;
clusterer.add_marker_click_listener(cell, count);
cell.addTo(clusterer.map.geoJsonLayers);
},
post_clustering : function(){
}
}
}
}
// also used by anycluster_marker.js
var roundMarkerCount = function(count){
if (count == 1){
count = 1;
}
else if (count <= 5) {
count = 5;
}
else if (count <= 10) {
count = 10;
}
else if (count <= 50) {
count = 50;
}
else if (count <= 100) {
count = 100;
}
else if (count <= 1000) {
count = 1000;
}
else {
count = 10000;
}
return count;
}; | }
else {
return false;
} |
prnn_cb12_train_predict.py | from keras.layers import Input, Dense, concatenate
from keras.layers.recurrent import GRU
from keras.utils import plot_model
from keras.models import Model, load_model
from keras.callbacks import ModelCheckpoint
import keras
import pandas as pd
import numpy as np
import keras.backend as K
from keras.utils import to_categorical
from keras.losses import categorical_crossentropy
from multiprocessing import Pool, cpu_count
import pickle
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
dataset = "cb12/"
path = "../../data/"
interim_path = path + dataset + "interim/"
processed_path = path + dataset + "processed/"
model_path = "models/"
model_path_valid = "models/valid/"
def TOP1(y_true, y_pred):
y1 = y_pred * y_true
y2 = K.sum(y1, axis=1)[:, np.newaxis]
y3 = y_true - y1
return (K.sum(K.sigmoid(y_pred - y2)) + y3 * y3) / tf.cast(tf.shape(y_true)[0], tf.float32)
loss = TOP1
def create_prnn_model(left_input_size, right_input_size, batch_size = 512, hidden_units = 100, o_activation='softmax', lr = 0.001):
emb_size = 50
size = emb_size
# left input - item vector
input_left = Input(batch_shape=(batch_size, 1, left_input_size), name='input_left')
gru_left, gru_left_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_left')(input_left)
# right input - feature vector
input_right = Input(batch_shape=(batch_size, 1, right_input_size), name='input_right')
gru_right, gru_right_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_right')(input_right)
# merging both layers and creating the model
merged = concatenate([gru_left, gru_right])
#change softmax per another activation funciton?
output = Dense(left_input_size, activation=o_activation, name='output')(merged)
model = Model(inputs=[input_left, input_right], outputs=output, name='gru4rec')
encoder = Model(inputs=[input_left, input_right], outputs=merged)
# define model's optimizer
#optimizer = optim.Optimizer(optimizer=self.optimizer, lr=self.lr)
#opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
opt = keras.optimizers.Adagrad(lr=lr)
# define model's loss function --> implement here the top1 loss function
# loss_function = loss.LossFunction(loss_type=self.loss_function)
#model.compile(loss=loss_function, optimizer=opt, metrics=['accuracy'])
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
filepath = model_path_valid + 'prnn_cb12_checkpoint.h5'
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=2, save_best_only=True, mode='min')
callbacks_list = []
model.summary()
#plot_model(model, show_shapes=True, to_file='rnn-structure.png')
return model, encoder
def get_states(model):
#return the actual states of the layers
return [K.get_value(s) for s,_ in model.state_updates]
def freeze_layer(model, layer_name, lr):
|
class SessionDataset:
"""Credit to yhs-968/pyGRU4REC."""
def __init__(self, data, sep='\t', session_key='session_id', item_key='item_id', time_key='created_at', n_samples=-1, itemmap=None, time_sort=False):
"""
Args:
path: path of the csv file
sep: separator for the csv
session_key, item_key, time_key: name of the fields corresponding to the sessions, items, time
n_samples: the number of samples to use. If -1, use the whole dataset.
itemmap: mapping between item IDs and item indices
time_sort: whether to sort the sessions by time or not
"""
self.df = data
self.session_key = session_key
self.item_key = item_key
self.time_key = time_key
self.time_sort = time_sort
self.add_item_indices(itemmap=itemmap)
self.df.sort_values([session_key, time_key], inplace=True)
# Sort the df by time, and then by session ID. That is, df is sorted by session ID and
# clicks within a session are next to each other, where the clicks within a session are time-ordered.
self.click_offsets = self.get_click_offsets()
#array of the positions where there is a change of session.
#len = len(session_idx_arr) + 1
self.session_idx_arr = self.order_session_idx()
#array of sessions [0 1 2 3 4 .... n-1]
def get_click_offsets(self):
"""
Return the offsets of the beginning clicks of each session IDs,
where the offset is calculated against the first click of the first session ID.
"""
offsets = np.zeros(self.df[self.session_key].nunique() + 1, dtype=np.int32)
# group & sort the df by session_key and get the offset values
offsets[1:] = self.df.groupby(self.session_key).size().cumsum()
return offsets
def order_session_idx(self):
""" Order the session indices """
if self.time_sort:
# starting time for each sessions, sorted by session IDs
sessions_start_time = self.df.groupby(self.session_key)[self.time_key].min().values
# order the session indices by session starting times
session_idx_arr = np.argsort(sessions_start_time)
else:
session_idx_arr = np.arange(self.df[self.session_key].nunique())
return session_idx_arr
def add_item_indices(self, itemmap=None):
"""
Add item index column named "item_idx" to the df
Args:
itemmap (pd.DataFrame): mapping between the item Ids and indices
"""
if itemmap is None:
item_ids = self.df[self.item_key].unique() # unique item ids
item2idx = pd.Series(data=np.arange(len(item_ids)),
index=item_ids)
itemmap = pd.DataFrame({self.item_key:item_ids,
'item_idx':item2idx[item_ids].values})
self.itemmap = itemmap
self.df = pd.merge(self.df, self.itemmap, on=self.item_key, how='inner')
@property
def items(self):
return self.itemmap.item_id.unique()
class SessionDataLoader:
"""Credit to yhs-968/pyGRU4REC."""
def __init__(self, dataset, batch_size):
"""
A class for creating session-parallel mini-batches.
Args:
dataset (SessionDataset): the session dataset to generate the batches from
batch_size (int): size of the batch
"""
self.dataset = dataset
self.batch_size = batch_size
self.done_sessions_counter = 0
def __iter__(self):
""" Returns the iterator for producing session-parallel training mini-batches.
Yields:
input (B,): Item indices that will be encoded as one-hot vectors later.
target (B,): a Variable that stores the target item indices
masks: Numpy array indicating the positions of the sessions to be terminated
"""
df = self.dataset.df
session_key='session_id'
item_key='item_id'
time_key='created_at'
self.n_items = df[item_key].nunique()
click_offsets = self.dataset.click_offsets
#print(click_offsets)
session_idx_arr = self.dataset.session_idx_arr
#print(session_idx_arr)
iters = np.arange(self.batch_size)
#iters = np.arange(1)
maxiter = iters.max()
start = click_offsets[session_idx_arr[iters]]
end = click_offsets[session_idx_arr[iters] + 1]
#print(start)
#print(end)
mask = [] # indicator for the sessions to be terminated
finished = False
while not finished:
#minimum lenght of all the sessions
minlen = (end - start).min()
# Item indices (for embedding) for clicks where the first sessions start
idx_target = df.item_idx.values[start]
for i in range(minlen - 1):
# Build inputs & targets
idx_input = idx_target
idx_target = df.item_idx.values[start + i + 1]
inp = idx_input
target = idx_target
yield inp, target, mask
# click indices where a particular session meets second-to-last element
start = start + (minlen - 1)
# see if how many sessions should terminate
mask = np.arange(len(iters))[(end - start) <= 1]
self.done_sessions_counter = len(mask)
for idx in mask:
maxiter += 1
if maxiter >= len(click_offsets) - 1:
finished = True
break
# update the next starting/ending point
iters[idx] = maxiter
start[idx] = click_offsets[session_idx_arr[maxiter]]
end[idx] = click_offsets[session_idx_arr[maxiter] + 1]
def train_prnn(model, lr, loader, layer_freezing_enabled = False, num_epochs = 10):
for epoch in range(0, num_epochs):
print("Epoch: " + str(epoch+1))
epoch_loss = 0
i = 0
for feat, target, mask in loader:
#feat = np array size BATCH_SIZE with the item indexes of the first items of the first BATCH_SIZE sessions
#comvert feat to an array size (BATCH_SIZE, 26723) of one hot encoding the indes with loader.n_items
input_oh = to_categorical(feat, num_classes=loader.n_items)
#convert from shape (BATCH_SIZE, 26723) to (BATCH_SIZE, 1, 26723)
input_oh = np.expand_dims(input_oh, axis=1)
# with the argmax function you get back again the feat/target np array (arg_input = feat)
### arg_input = np.argmax(to_categorical(feat, num_classes=loader.n_items), axis=1)
### arg_output = np.argmax(to_categorical(target, num_classes=loader.n_items), axis=1)
input_feature = np.array([])
for line in feat:
#result = int(mapitem[(mapitem.item_idx == line)].item_id.values)
result = str(mapitem[(mapitem.item_idx == line)].item_id.values[0])
#print(result)
# use empty feature vec if missing
feature_vector = empty_feature_vec
if result in item_encodings.keys():
feature_vector = item_encodings[result]
input_feature = np.append(input_feature, feature_vector)
input_feature = input_feature.reshape(batch_size, 1, feature_size)
#target = np array size BATCH_SIZE with the item indexes of the TARGET items of the feat array items
target_oh = to_categorical(target, num_classes=loader.n_items)
#calculate the loss between the input and the expected output
if layer_freezing_enabled:
if i % 2 is 0:
model = freeze_layer(model, 'gru_left', lr = lr)
else:
model = freeze_layer(model, 'gru_right', lr = lr)
tr_loss = model.train_on_batch([input_oh, input_feature], target_oh)
epoch_loss += tr_loss[0]
i = i + 1
print("Epoch loss: " + str(epoch_loss))
return model
# # Set data for final training
# set data
train_path = '../../data/' + dataset + 'processed/train_14d.csv'
train = pd.read_csv(train_path, sep='\t')[['session_id', 'item_id', 'created_at']]
interactions = pd.read_csv('../../data/' + dataset + 'interim/interactions.csv', header=0, sep='\t')
items = pd.read_csv('../../data/' + dataset + 'interim/items.csv', header=0, sep='\t')
view_fields = ["item_id", "state", "ReqTopic", "DescTopic", "TitTopic"]
common_items = items.merge(interactions, on=['item_id'])[view_fields].drop_duplicates()
item_count = len(train['item_id'].unique())
print(item_count)
session_count = len(train['created_at'].unique())
print(len(common_items))
# CB12 items need to be converted to dummies
common = common_items
common["item_id"] = common["item_id"].astype('str')
common["DescTopic"] = common["DescTopic"].astype('str')
common["TitTopic"] = common["TitTopic"].astype('str')
common["ReqTopic"] = common["ReqTopic"].astype('str')
df2 = pd.DataFrame(index=common.index)
s1 = pd.get_dummies(common["state"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="state").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["ReqTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="ReqTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["state_", "ReqTopic_"], axis=1, errors="ignore")
s1 = pd.get_dummies(common["DescTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="DescTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["TitTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="TitTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["DescTopic_", "TitTopic_"], axis=1, errors="ignore")
common = common.drop(["state", "ReqTopic", "DescTopic", "TitTopic"], axis=1)
df2 = pd.concat([common, df2], axis=1)
one_hot = df2
print(one_hot.shape)
# number of content features per item
feature_size = one_hot.shape[1] - 1
item_encodings = {}
for index, row in one_hot.iterrows():
item_id = row["item_id"]
item_encodings[item_id] = row.values[1:]
print(len(item_encodings))
empty_feature_vec = np.zeros(feature_size, dtype=int)
# load data
batch_size = 512
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
mapitem = loader.dataset.itemmap
# # Train final model
# In[ ]:
# use best params
ls = 1000
act = "softmax"
lr = 0.001
# define model
model, encoder = create_prnn_model(item_count, feature_size, batch_size=batch_size, hidden_units = ls, o_activation = act, lr = lr)
# train model
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
print("Starting to train: " + model_name)
model = train_prnn(model, lr, loader)
pickle.dump(model, open(model_path + model_name, 'wb'), protocol=4)
print("Stored model in: " + model_path + model_name)
# # Generate predictions
def predict_function(sid, test_session, pr, item_idx_map, idx_item_map, cut_off=20,
session_key='session_id', item_key='item_id', time_key='created_at'):
test_session.sort_values([time_key], inplace=True)
# get first and only session_id (as we grouped it before calling this method)
session_id = test_session[session_key].unique()[0]
log_columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"]
log_df = pd.DataFrame(columns = log_columns)
session_length = len(test_session)
il = a = np.zeros((batch_size, 1, len(item_idx_map)))
ir = a = np.zeros((batch_size, 1, 115))
for i in range(session_length -1):
# use current item as reference point (rest is for testing)
current_item_id = test_session[item_key].values[i]
item_vec = np.zeros(len(item_idx_map), dtype=int)
item_idx = item_idx_map[current_item_id]
item_vec[item_idx] = 1
# set vector in batch input
il[i, 0] = item_vec
#item_features = item_encodings[current_item_id]
# use empty feature vec if missing
item_features = empty_feature_vec
if current_item_id in item_encodings.keys():
item_features = item_encodings[result]
#item_features = item_features.reshape(1,1, len(item_features))
ir[i, 0] = item_features
# do batch prediction
pred = model.predict([il, ir], batch_size=batch_size)
# for every subsession prediction
for i in range(session_length-1):
preds = pred[i]
topn_idx_preds = preds.argsort()[-cut_off:][::-1]
predictions = []
# for every recommended item index
for item_idx in topn_idx_preds:
pred_item = idx_item_map[item_idx]
predictions.append(pred_item)
current_input_set = test_session[item_key].values[:i+1]
remaining_test_set = test_session[item_key].values[i+1:]
position = "MID"
if i == 0:
position = "FIRST"
if len(remaining_test_set) == 1:
position = "LAST"
log_df = log_df.append({
"session_id": sid,
"input_items": ','.join(map(str, current_input_set)),
"input_count": len(current_input_set),
"position": position,
"remaining_items": ','.join(map(str, remaining_test_set)),
"remaining_count": len(remaining_test_set),
"predictions": ','.join(map(str, predictions))
}, ignore_index=True)
log_df['input_count'] = log_df['input_count'].astype(int)
log_df['remaining_count'] = log_df['remaining_count'].astype(int)
return log_df
# In[ ]:
import keras.losses
keras.losses.TOP1 = TOP1
print("Preparing train data...")
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
test_path = '../../data/' + dataset + 'processed/test_14d.csv'
test = pd.read_csv(test_path, sep='\t')[['session_id', 'item_id', 'created_at']]
test_dataset = SessionDataset(test)
test_generator = SessionDataLoader(test_dataset, batch_size=batch_size)
session_groups = test.groupby("session_id")
mapitem = loader.dataset.itemmap
item_idx_map = {}
idx_item_map = {}
for index, row in mapitem.iterrows():
item_id = row["item_id"]
item_idx = row["item_idx"]
item_idx_map[item_id] = item_idx
idx_item_map[item_idx] = item_id
predict_path = "../../data/cb12/interim/predict/base/"
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
model = pickle.load(open(model_path + model_name, 'rb'))
print("Loaded: " + model_name)
res_list = []
# predict
report_freq = len(session_groups) // 5
count = 0
for sid, session in session_groups:
pred_df = predict_function(sid, session, model, item_idx_map, idx_item_map)
res_list.append(pred_df)
# reset states
model.get_layer('gru_left').reset_states()
model.get_layer('gru_right').reset_states()
# print progress
count += 1
if count % report_freq == 0:
print("Predicted for " + str(count) + " sessions. " + str(len(session_groups) - count) + " sessions to go." )
# concat results
res = pd.concat(res_list)
res = res.reindex(columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"])
res.to_csv(predict_path + "test_14d_prnn2.csv", sep='\t')
print("Stored predictions: " + predict_path + "test_14d_prnn2.csv")
# In[ ]:
| if layer_name == 'gru_left':
# gru left layer will not be trained this mini batch
model.get_layer(layer_name).trainable = False
# but gru right will
model.get_layer('gru_right').trainable = True
elif layer_name == 'gru_right':
# gru right layer will not be trained this mini batch
model.get_layer(layer_name).trainable = False
# but gru left will
model.get_layer('gru_left').trainable = True
else:
raise NotImplementedError
# opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
opt = keras.optimizers.Adagrad(lr=lr)
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
return model |
membound.py | import os
import time
from membound_cases import memory_bound_cases_list
from utils import (arch_name, datatime_with_format, dtype2str, dump2json,
geometric_mean, md_table_header, scaled_repeat_times,
size2str)
import taichi as ti
class MemoryBound:
suite_name = 'memorybound'
supported_archs = [ti.x64, ti.cuda]
test_cases = memory_bound_cases_list
test_dtype_list = [ti.i32, ti.i64, ti.f32, ti.f64]
test_dsize_list = [
(4**i) * 1024 # kibibytes(KiB) = 1024
for i in range(1, 10) # [4KB,16KB...256MB]
]
basic_repeat_times = 10
evaluator = [geometric_mean]
def __init__(self, arch):
self._arch = arch
self._cases_impl = []
for case in self.test_cases:
for dtype in self.test_dtype_list:
impl = CaseImpl(case, arch, dtype, self.test_dsize_list,
self.evaluator)
self._cases_impl.append(impl)
def run(self):
for case in self._cases_impl:
case.run()
def save_as_json(self, arch_dir='./'):
#folder of suite
suite_path = os.path.join(arch_dir, self.suite_name)
os.makedirs(suite_path)
#json files
self._save_suite_info_as_json(suite_path)
self._save_cases_info_as_json(suite_path)
def save_as_markdown(self, arch_dir='./'):
current_time = datatime_with_format()
commit_hash = ti.core.get_commit_hash() #[:8]
file_name = f'{self.suite_name}.md'
file_path = os.path.join(arch_dir, file_name)
with open(file_path, 'w') as f:
lines = [
f'commit_hash: {commit_hash}\n', f'datatime: {current_time}\n'
]
lines += self._get_markdown_lines()
for line in lines:
print(line, file=f)
def _save_suite_info_as_json(self, suite_path='./'):
info_dict = {
'cases': [func.__name__ for func in self.test_cases],
'dtype': [dtype2str(dtype) for dtype in self.test_dtype_list],
'dsize': [size for size in self.test_dsize_list],
'repeat': [
scaled_repeat_times(self._arch, size, self.basic_repeat_times)
for size in self.test_dsize_list
],
'evaluator': [func.__name__ for func in self.evaluator]
}
info_path = os.path.join(suite_path, '_info.json')
with open(info_path, 'w') as f:
print(dump2json(info_dict), file=f)
def _save_cases_info_as_json(self, suite_path='./'):
for case in self.test_cases: #for case [fill,saxpy,reduction]
results_dict = {}
for impl in self._cases_impl: #find [ti.i32, ti.i64, ti.f32, ti.f64]
if impl._name != case.__name__:
continue
result_name = dtype2str(impl._test_dtype)
results_dict[result_name] = impl.get_results_dict()
case_path = os.path.join(suite_path, (case.__name__ + '.json'))
with open(case_path, 'w') as f:
case_str = dump2json(results_dict)
print(case_str, file=f)
def _get_markdown_lines(self):
lines = [] | self.test_dsize_list, self.basic_repeat_times,
self.evaluator)
result_header = '|kernel elapsed time(ms)' + ''.join(
'|' for i in range(
len(self.test_dsize_list) + len(MemoryBound.evaluator)))
lines += [result_header]
for case in self._cases_impl:
lines += case.get_markdown_lines()
lines.append('')
return lines
class CaseImpl:
def __init__(self, func, arch, test_dtype, test_dsize_list, evaluator):
self._func = func
self._name = func.__name__
self._arch = arch
self._test_dtype = test_dtype
self._test_dsize_list = test_dsize_list
self._min_time_in_us = [] #test results
self._evaluator = evaluator
def run(self):
ti.init(kernel_profiler=True, arch=self._arch)
print("TestCase[%s.%s.%s]" % (self._func.__name__, arch_name(
self._arch), dtype2str(self._test_dtype)))
for test_dsize in self._test_dsize_list:
print("test_dsize = %s" % (size2str(test_dsize)))
self._min_time_in_us.append(
self._func(self._arch, self._test_dtype, test_dsize,
MemoryBound.basic_repeat_times))
time.sleep(0.2)
ti.reset()
def get_markdown_lines(self):
string = '|' + self._name + '.' + dtype2str(self._test_dtype) + '|'
string += ''.join(
str(round(time, 4)) + '|' for time in self._min_time_in_us)
string += ''.join(
str(round(item(self._min_time_in_us), 4)) + '|'
for item in self._evaluator)
return [string]
def get_results_dict(self):
results_dict = {}
for i in range(len(self._test_dsize_list)):
dsize = self._test_dsize_list[i]
repeat = scaled_repeat_times(self._arch, dsize,
MemoryBound.basic_repeat_times)
elapsed_time = self._min_time_in_us[i]
item_name = size2str(dsize).replace('.0', '')
item_dict = {
'dsize_byte': dsize,
'repeat': repeat,
'elapsed_time_ms': elapsed_time
}
results_dict[item_name] = item_dict
return results_dict | lines += md_table_header(self.suite_name, self._arch, |
option_bytes.go | // Go Substrate RPC Client (GSRPC) provides APIs and types around Polkadot and any Substrate-based chain RPC calls
//
// Copyright 2020 Stafi Protocol
//
// 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 types
import "github.com/stafiprotocol/go-substrate-rpc-client/scale"
// OptionBytes is a structure that can store a Bytes or a missing value
type OptionBytes struct {
option
value Bytes
}
// NewOptionBytes creates an OptionBytes with a value
func NewOptionBytes(value Bytes) OptionBytes {
return OptionBytes{option{true}, value}
}
// NewOptionBytesEmpty creates an OptionBytes without a value
func NewOptionBytesEmpty() OptionBytes {
return OptionBytes{option: option{false}}
}
func (o OptionBytes) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes) SetSome(value Bytes) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes) SetNone() {
o.hasValue = false
o.value = Bytes{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes) Unwrap() (ok bool, value Bytes) {
return o.hasValue, o.value
}
// OptionBytes8 is a structure that can store a Bytes8 or a missing value
type OptionBytes8 struct {
option
value Bytes8
}
// NewOptionBytes8 creates an OptionBytes8 with a value
func NewOptionBytes8(value Bytes8) OptionBytes8 {
return OptionBytes8{option{true}, value}
}
// NewOptionBytes8Empty creates an OptionBytes8 without a value
func NewOptionBytes8Empty() OptionBytes8 {
return OptionBytes8{option: option{false}}
}
func (o OptionBytes8) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes8) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes8) SetSome(value Bytes8) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes8) SetNone() {
o.hasValue = false
o.value = Bytes8{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes8) Unwrap() (ok bool, value Bytes8) {
return o.hasValue, o.value
}
// OptionBytes16 is a structure that can store a Bytes16 or a missing value
type OptionBytes16 struct {
option
value Bytes16
}
// NewOptionBytes16 creates an OptionBytes16 with a value
func NewOptionBytes16(value Bytes16) OptionBytes16 {
return OptionBytes16{option{true}, value}
}
// NewOptionBytes16Empty creates an OptionBytes16 without a value
func NewOptionBytes16Empty() OptionBytes16 {
return OptionBytes16{option: option{false}}
}
func (o OptionBytes16) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes16) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes16) SetSome(value Bytes16) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes16) SetNone() {
o.hasValue = false
o.value = Bytes16{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes16) Unwrap() (ok bool, value Bytes16) {
return o.hasValue, o.value
}
// OptionBytes32 is a structure that can store a Bytes32 or a missing value
type OptionBytes32 struct {
option
value Bytes32
}
// NewOptionBytes32 creates an OptionBytes32 with a value
func | (value Bytes32) OptionBytes32 {
return OptionBytes32{option{true}, value}
}
// NewOptionBytes32Empty creates an OptionBytes32 without a value
func NewOptionBytes32Empty() OptionBytes32 {
return OptionBytes32{option: option{false}}
}
func (o OptionBytes32) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes32) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes32) SetSome(value Bytes32) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes32) SetNone() {
o.hasValue = false
o.value = Bytes32{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes32) Unwrap() (ok bool, value Bytes32) {
return o.hasValue, o.value
}
// OptionBytes64 is a structure that can store a Bytes64 or a missing value
type OptionBytes64 struct {
option
value Bytes64
}
// NewOptionBytes64 creates an OptionBytes64 with a value
func NewOptionBytes64(value Bytes64) OptionBytes64 {
return OptionBytes64{option{true}, value}
}
// NewOptionBytes64Empty creates an OptionBytes64 without a value
func NewOptionBytes64Empty() OptionBytes64 {
return OptionBytes64{option: option{false}}
}
func (o OptionBytes64) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes64) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes64) SetSome(value Bytes64) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes64) SetNone() {
o.hasValue = false
o.value = Bytes64{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes64) Unwrap() (ok bool, value Bytes64) {
return o.hasValue, o.value
}
// OptionBytes128 is a structure that can store a Bytes128 or a missing value
type OptionBytes128 struct {
option
value Bytes128
}
// NewOptionBytes128 creates an OptionBytes128 with a value
func NewOptionBytes128(value Bytes128) OptionBytes128 {
return OptionBytes128{option{true}, value}
}
// NewOptionBytes128Empty creates an OptionBytes128 without a value
func NewOptionBytes128Empty() OptionBytes128 {
return OptionBytes128{option: option{false}}
}
func (o OptionBytes128) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes128) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes128) SetSome(value Bytes128) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes128) SetNone() {
o.hasValue = false
o.value = Bytes128{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes128) Unwrap() (ok bool, value Bytes128) {
return o.hasValue, o.value
}
// OptionBytes256 is a structure that can store a Bytes256 or a missing value
type OptionBytes256 struct {
option
value Bytes256
}
// NewOptionBytes256 creates an OptionBytes256 with a value
func NewOptionBytes256(value Bytes256) OptionBytes256 {
return OptionBytes256{option{true}, value}
}
// NewOptionBytes256Empty creates an OptionBytes256 without a value
func NewOptionBytes256Empty() OptionBytes256 {
return OptionBytes256{option: option{false}}
}
func (o OptionBytes256) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes256) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes256) SetSome(value Bytes256) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes256) SetNone() {
o.hasValue = false
o.value = Bytes256{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes256) Unwrap() (ok bool, value Bytes256) {
return o.hasValue, o.value
}
// OptionBytes512 is a structure that can store a Bytes512 or a missing value
type OptionBytes512 struct {
option
value Bytes512
}
// NewOptionBytes512 creates an OptionBytes512 with a value
func NewOptionBytes512(value Bytes512) OptionBytes512 {
return OptionBytes512{option{true}, value}
}
// NewOptionBytes512Empty creates an OptionBytes512 without a value
func NewOptionBytes512Empty() OptionBytes512 {
return OptionBytes512{option: option{false}}
}
func (o OptionBytes512) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes512) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes512) SetSome(value Bytes512) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes512) SetNone() {
o.hasValue = false
o.value = Bytes512{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes512) Unwrap() (ok bool, value Bytes512) {
return o.hasValue, o.value
}
// OptionBytes1024 is a structure that can store a Bytes1024 or a missing value
type OptionBytes1024 struct {
option
value Bytes1024
}
// NewOptionBytes1024 creates an OptionBytes1024 with a value
func NewOptionBytes1024(value Bytes1024) OptionBytes1024 {
return OptionBytes1024{option{true}, value}
}
// NewOptionBytes1024Empty creates an OptionBytes1024 without a value
func NewOptionBytes1024Empty() OptionBytes1024 {
return OptionBytes1024{option: option{false}}
}
func (o OptionBytes1024) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes1024) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes1024) SetSome(value Bytes1024) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes1024) SetNone() {
o.hasValue = false
o.value = Bytes1024{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes1024) Unwrap() (ok bool, value Bytes1024) {
return o.hasValue, o.value
}
// OptionBytes2048 is a structure that can store a Bytes2048 or a missing value
type OptionBytes2048 struct {
option
value Bytes2048
}
// NewOptionBytes2048 creates an OptionBytes2048 with a value
func NewOptionBytes2048(value Bytes2048) OptionBytes2048 {
return OptionBytes2048{option{true}, value}
}
// NewOptionBytes2048Empty creates an OptionBytes2048 without a value
func NewOptionBytes2048Empty() OptionBytes2048 {
return OptionBytes2048{option: option{false}}
}
func (o OptionBytes2048) Encode(encoder scale.Encoder) error {
return encoder.EncodeOption(o.hasValue, o.value)
}
func (o *OptionBytes2048) Decode(decoder scale.Decoder) error {
return decoder.DecodeOption(&o.hasValue, &o.value)
}
// SetSome sets a value
func (o *OptionBytes2048) SetSome(value Bytes2048) {
o.hasValue = true
o.value = value
}
// SetNone removes a value and marks it as missing
func (o *OptionBytes2048) SetNone() {
o.hasValue = false
o.value = Bytes2048{}
}
// Unwrap returns a flag that indicates whether a value is present and the stored value
func (o OptionBytes2048) Unwrap() (ok bool, value Bytes2048) {
return o.hasValue, o.value
}
| NewOptionBytes32 |
App.js | (function () {
"use strict";
var App = function () {
var o = this;
this._ready(function () {
o.initialize();
});
};
var p = App.prototype;
p.isProd = false;
p.isMobile = false;
p.screen = {
laptop: 1365,
tablet: 991,
ipad: 767,
phone: 575,
ip5: 320
}
p.initialize = function () { |
p._ready = function (callback) {
if (document.readyState != "loading") {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
p._checkMobile = function () {
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
|| /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) {
this.isMobile = true;
}
};
p.setCookie = function (name, value, day) {
var date = new Date;
date.setTime(date.getTime() + 24 * day * 60 * 60 * 1000);
var expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
};
p.getCookie = function (name) {
for (var t = name + "=", i = decodeURIComponent(document.cookie).split(";"), a = 0; a < i.length; a++) {
for (var n = i[a]; " " === n.charAt(0);)
n = n.substring(1);
if (0 === n.indexOf(t))
return n.substring(t.length, n.length);
}
return "";
};
window.fe = window.fe || {};
window.fe.App = new App;
}()); | // Init
this._checkMobile();
}; |
lib.rs | use jni::JNIEnv;
use jni::objects::{JClass, JString, JValue};
use jni::sys::{jbooleanArray, jbyte, jbyteArray, jobject, jsize};
use pancake_db_core::{RepLevelsAndAtoms, RepLevelsAndBytes};
use pancake_db_core::compression::ValueCodec;
use pancake_db_core::deletion::decompress_deletions;
use pancake_db_core::encoding::{Decoder, DecoderImpl};
use pancake_db_core::primitives::Primitive;
use q_compress::data_types::TimestampMicros;
fn decode_column<P: Primitive>(
env: JNIEnv,
nesting_depth: jbyte,
compressed_bytes: jbyteArray,
uncompressed_bytes: jbyteArray,
codec: JString,
class_name: &str,
signature: &str,
create_jni_array_fn: &dyn Fn(&JNIEnv, &[P::A]) -> jobject,
) -> jobject {
// DECOMPRESS
let bytes = env.convert_byte_array(compressed_bytes).unwrap();
let mut atoms = Vec::new();
let mut rep_levels = Vec::new();
if !bytes.is_empty() {
let codec: String = env.get_string(codec)
.expect("unable to get codec string")
.into();
let decompressor = P::new_codec(&codec)
.expect("invalid codec for data type");
let RepLevelsAndBytes { remaining_bytes: bytes, levels } = decompressor.decompress_rep_levels(&bytes)
.expect("unable to decompress repetition levels");
atoms.extend(decompressor.decompress_atoms(&bytes)
.expect("unable to decompress; data may be corrupt"));
rep_levels.extend(levels);
};
// DECODE
let bytes = env.convert_byte_array(uncompressed_bytes).unwrap();
if !bytes.is_empty() {
let decoder = DecoderImpl::<P, RepLevelsAndAtoms<P::A>>::new(nesting_depth as u8);
let decoded = decoder
.decode(&bytes)
.expect("unable to decode uncompressed bytes; data may be corrupt");
for RepLevelsAndAtoms { levels, atoms: uncompressed_atoms } in &decoded {
rep_levels.extend(levels);
atoms.extend(uncompressed_atoms);
}
}
let java_values = create_jni_array_fn(&env, &atoms);
let java_rep_levels = env.byte_array_from_slice(&rep_levels)
.expect("unable to allocate java rep levels array");
let args = vec![
JValue::from(java_values),
JValue::from(java_rep_levels),
];
let obj = env.new_object(class_name, signature, &args)
.expect("could not construct java object");
obj.into_inner()
}
#[no_mangle]
pub extern "system" fn Java_com_pancakedb_client_NativeCore_00024_decodeInt64s(
env: JNIEnv,
_: JClass,
nesting_depth: jbyte,
compressed_bytes: jbyteArray,
uncompressed_bytes: jbyteArray,
codec: JString,
) -> jobject {
fn create_jni_array(env: &JNIEnv, atoms: &[i64]) -> jobject {
let java_values = env.new_long_array(atoms.len() as jsize)
.expect("unable to allocate java array");
env.set_long_array_region(java_values, 0 as jsize, atoms)
.expect("unable to assign to java array");
java_values
}
decode_column::<i64>(
env,
nesting_depth,
compressed_bytes,
uncompressed_bytes,
codec,
"com/pancakedb/client/NativeCore$LongColumn",
"([J[B)V",
&create_jni_array,
)
}
#[no_mangle]
pub extern "system" fn Java_com_pancakedb_client_NativeCore_00024_decodeBools(
env: JNIEnv,
_: JClass,
nesting_depth: jbyte,
compressed_bytes: jbyteArray,
uncompressed_bytes: jbyteArray,
codec: JString,
) -> jobject {
fn create_jni_array(env: &JNIEnv, atoms: &[bool]) -> jobject {
let java_values = env.new_boolean_array(atoms.len() as jsize)
.expect("unable to allocate java array");
let bools_as_bytes = atoms.iter()
.map(|b| *b as u8)
.collect::<Vec<u8>>();
env.set_boolean_array_region(java_values, 0 as jsize, &bools_as_bytes)
.expect("unable to assign to java array");
java_values
}
decode_column::<bool>(
env,
nesting_depth,
compressed_bytes,
uncompressed_bytes,
codec,
"com/pancakedb/client/NativeCore$BooleanColumn",
"([Z[B)V",
&create_jni_array,
)
}
#[no_mangle]
pub extern "system" fn Java_com_pancakedb_client_NativeCore_00024_decodeFloat32s(
env: JNIEnv,
_: JClass,
nesting_depth: jbyte,
compressed_bytes: jbyteArray,
uncompressed_bytes: jbyteArray,
codec: JString,
) -> jobject {
fn create_jni_array(env: &JNIEnv, atoms: &[f32]) -> jobject {
let java_values = env.new_float_array(atoms.len() as jsize)
.expect("unable to allocate java array");
env.set_float_array_region(java_values, 0 as jsize, atoms)
.expect("unable to assign to java array");
java_values
}
decode_column::<f32>(
env,
nesting_depth,
compressed_bytes,
uncompressed_bytes,
codec,
"com/pancakedb/client/NativeCore$FloatColumn",
"([F[B)V",
&create_jni_array,
)
}
#[no_mangle]
pub extern "system" fn Java_com_pancakedb_client_NativeCore_00024_decodeFloat64s(
env: JNIEnv,
_: JClass,
nesting_depth: jbyte,
compressed_bytes: jbyteArray,
uncompressed_bytes: jbyteArray,
codec: JString,
) -> jobject {
fn create_jni_array(env: &JNIEnv, atoms: &[f64]) -> jobject {
let java_values = env.new_double_array(atoms.len() as jsize)
.expect("unable to allocate java array");
env.set_double_array_region(java_values, 0 as jsize, atoms)
.expect("unable to assign to java array");
java_values
}
decode_column::<f64>(
env,
nesting_depth,
compressed_bytes,
uncompressed_bytes,
codec,
"com/pancakedb/client/NativeCore$DoubleColumn",
"([D[B)V",
&create_jni_array,
)
}
#[no_mangle]
pub extern "system" fn Java_com_pancakedb_client_NativeCore_00024_decodeTimestamps(
env: JNIEnv,
_: JClass,
nesting_depth: jbyte,
compressed_bytes: jbyteArray,
uncompressed_bytes: jbyteArray,
codec: JString,
) -> jobject {
fn create_jni_array(env: &JNIEnv, atoms: &[TimestampMicros]) -> jobject {
let java_values = env.new_long_array(atoms.len() as jsize)
.expect("unable to allocate java array");
// client just encodes timestamps as epoch micros.
// If we ever do TimestampNs or other precisions, or we want the complete time range,
// this part needs to change.
let longs = atoms
.iter()
.map(|ts| ts.to_total_parts() as i64)
.collect::<Vec<i64>>();
env.set_long_array_region(java_values, 0 as jsize, &longs)
.expect("unable to assign to java array");
java_values
}
decode_column::<TimestampMicros>(
env,
nesting_depth,
compressed_bytes,
uncompressed_bytes,
codec,
"com/pancakedb/client/NativeCore$LongColumn",
"([J[B)V",
&create_jni_array,
)
}
#[no_mangle]
pub extern "system" fn | (
env: JNIEnv,
_: JClass,
dtype: JString,
nesting_depth: jbyte,
compressed_bytes: jbyteArray,
uncompressed_bytes: jbyteArray,
codec: JString,
) -> jobject {
fn create_jni_array(env: &JNIEnv, atoms: &[u8]) -> jobject {
env.byte_array_from_slice(&atoms)
.expect("unable to allocate java byte array")
}
let dtype: String = env.get_string(dtype)
.expect("unable to get dtype string")
.into();
if dtype == "STRING" {
decode_column::<String>(
env,
nesting_depth,
compressed_bytes,
uncompressed_bytes,
codec,
"com/pancakedb/client/NativeCore$StringOrBytesColumn",
"([B[B)V",
&create_jni_array,
)
} else {
decode_column::<Vec<u8>>(
env,
nesting_depth,
compressed_bytes,
uncompressed_bytes,
codec,
"com/pancakedb/client/NativeCore$StringOrBytesColumn",
"([B[B)V",
&create_jni_array,
)
}
}
#[no_mangle]
pub extern "system" fn Java_com_pancakedb_client_NativeCore_00024_decodeDeletions(
env: JNIEnv,
_: JClass,
data: jbyteArray,
) -> jbooleanArray {
let bytes = env.convert_byte_array(data)
.unwrap();
let deletions_as_bytes: Vec<_> = decompress_deletions(&bytes)
.expect("corrupt deletion data")
.iter()
.map(|&b| b as u8)
.collect();
let res = env.new_boolean_array(deletions_as_bytes.len() as jsize)
.expect("unable to allocate jbooleanArray for deletions");
env.set_boolean_array_region(res, 0, &deletions_as_bytes)
.expect("unable to assign jbooleanArray for deletions");
res
}
| Java_com_pancakedb_client_NativeCore_00024_decodeStringOrBytes |
api_config.go | /*
Copyright 2018 Turbine Labs, Inc.
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 flags
//go:generate mockgen -source $GOFILE -destination mock_$GOFILE -package $GOPACKAGE -aux_files "apihttp=../../http/fromflags.go" --write_package_comment=false
import (
"errors"
"fmt"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"github.com/turbinelabs/api/client/tokencache"
apihttp "github.com/turbinelabs/api/http"
tbnflag "github.com/turbinelabs/nonstdlib/flag"
"github.com/turbinelabs/nonstdlib/log/console"
)
// APIConfigFromFlags represents command-line flags for specifying
// API authentication, host, port and SSL settings for the Turbine
// Labs API.
type APIConfigFromFlags interface {
// apihttp.FromFlags constructs an API endpoint
apihttp.FromFlags
// APIKey Returns the API authentication key from the command line.
// Equivalent to calling APIAuthKeyFromFlags().Make()
APIKey() string
// APIAuthKeyFromFlags returns the underlying APIAuthKeyFromFlags
// so that it can potentially be shared between APIConfigFromFlags
// via the APIConfigSetAPIAuthKeyFromFlags APIConfigOption.
APIAuthKeyFromFlags() APIAuthKeyFromFlags
}
// APIConfigOption represents an option passed to
// NewAPIConfigFromFlags.
type APIConfigOption func(*apiConfigFromFlags)
// APIConfigSetAPIAuthKeyFromFlags allows the caller to specify a shared
// APIAuthKeyFromFlags, likely obtained via the
// APIConfigFromFlags.APIAuthKeyFromFlags() method.
func APIConfigSetAPIAuthKeyFromFlags(akff APIAuthKeyFromFlags) APIConfigOption {
return func(ff *apiConfigFromFlags) {
ff.apiKeyConfig = akff
}
}
// APIConfigMayUseAuthToken indicates that the API Config can use an auth
// token to authenticate instead of relying on an API key. As a result if
// this is set API Key becomes optional. If an API Key is set it takes
// precedence over an auth token found from the TokenCache.
//
// If an APIAuthKeyFromFlags is provided via APIConfigSetAPIAuthKeyFromFlags
// it may still be considered required depending on the APIAuthKeyFromFlags
// construction.
//
// Parameters:
// cachePath - this is a file where cached authed token should be read from
func APIConfigMayUseAuthToken(cachePath tokencache.PathFromFlags) APIConfigOption {
return func(ff *apiConfigFromFlags) {
ff.mayUseAuthToken = true
ff.cachePath = cachePath
}
}
// NewAPIConfigFromFlags configures the necessary command line flags
// and returns an APIConfigFromFlags.
func NewAPIConfigFromFlags(
flagset tbnflag.FlagSet,
opts ...APIConfigOption,
) APIConfigFromFlags {
ff := &apiConfigFromFlags{}
for _, applyOpt := range opts {
applyOpt(ff)
}
if ff.apiKeyConfig == nil {
opts := []APIAuthKeyOption{}
if ff.mayUseAuthToken {
opts = append(opts, APIAuthKeyFlagsOptional())
}
ff.apiKeyConfig = NewAPIAuthKeyFromFlags(flagset, opts...)
}
ff.clientFromFlags = apihttp.NewFromFlags("api.turbinelabs.io", flagset)
return ff
}
type apiConfigFromFlags struct {
clientFromFlags apihttp.FromFlags
apiKeyConfig APIAuthKeyFromFlags
mayUseAuthToken bool
cachePath tokencache.PathFromFlags
oauth2Config oauth2.Config
tokenCache tokencache.TokenCache
}
func (ff *apiConfigFromFlags) APIKey() string {
return ff.apiKeyConfig.Make()
}
func (ff *apiConfigFromFlags) APIAuthKeyFromFlags() APIAuthKeyFromFlags {
return ff.apiKeyConfig
}
func (ff *apiConfigFromFlags) Validate() error {
err := ff.clientFromFlags.Validate()
if err != nil {
return err
}
if ff.mayUseAuthToken && ff.APIKey() != "" {
console.Info().Println("Preferring --api.key for authentication")
}
if ff.cachePath == nil && ff.APIKey() == "" {
return errors.New("No --api.key specified, and no cached login could be found")
}
return nil
}
func (ff *apiConfigFromFlags) MakeEndpoint() (apihttp.Endpoint, error) {
ep, err := ff.clientFromFlags.MakeEndpoint()
if err != nil {
return apihttp.Endpoint{}, err
}
// If an API Key is present it takes precedence and is assumed valid
if ff.APIKey() != "" {
return ep, nil
}
tc, err := tokencache.NewFromFile(ff.cachePath.CachePath())
if err != nil {
return apihttp.Endpoint{}, err
}
if tc.Expired() |
ff.tokenCache = tc
cfg, err := tokencache.ToOAuthConfig(tc)
if err != nil {
return apihttp.Endpoint{}, fmt.Errorf("unable to construct OIDC client config: %v", err)
}
ff.oauth2Config = cfg
// otherwise use the token from cache
ctx := context.Background()
client := ff.oauth2Config.Client(ctx, ff.tokenCache.Token)
ep.SetClient(apihttp.MakeHeaderPreserving(client))
return ep, nil
}
| {
return apihttp.Endpoint{}, fmt.Errorf("your session has timed out, please login again")
} |
debug.js | "use strict";
/********************************************************************************
* Copyright (C) 2017 TypeFox and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 | exports.DEBUG_MODE = void 0;
function isInDebugMode() {
if (typeof v8debug === 'object') {
return true;
}
if (process && process.execArgv) {
return process.execArgv.some(function (arg) {
return /^--(debug|inspect)(-brk)?=?/.test(arg);
});
}
return false;
}
exports.DEBUG_MODE = isInDebugMode();
//# sourceMappingURL=debug.js.map | ********************************************************************************/
Object.defineProperty(exports, "__esModule", { value: true }); |
normal.rs | use nalgebra::Vector3;
struct | (Vector3<f64>); | Normal |
registryEnterpriseRepo.go | // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package cs
import (
"context"
"reflect"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// This resource will help you to manager Container Registry Enterprise Edition repositories.
//
// For information about Container Registry Enterprise Edition repository and how to use it, see [Create a Repository](https://www.alibabacloud.com/help/doc-detail/145291.htm)
//
// > **NOTE:** Available in v1.86.0+.
//
// > **NOTE:** You need to set your registry password in Container Registry Enterprise Edition console before use this resource.
//
// ## Example Usage
//
// Basic Usage
//
// ```go
// package main
//
// import (
// "github.com/pulumi/pulumi-alicloud/sdk/v3/go/alicloud/cs"
// "github.com/pulumi/pulumi/sdk/v3/go/pulumi"
// )
//
// func main() {
// pulumi.Run(func(ctx *pulumi.Context) error {
// _, err := cs.NewRegistryEnterpriseNamespace(ctx, "my_namespace", &cs.RegistryEnterpriseNamespaceArgs{
// InstanceId: pulumi.String("cri-xxx"),
// AutoCreate: pulumi.Bool(false),
// DefaultVisibility: pulumi.String("PUBLIC"),
// })
// if err != nil {
// return err
// }
// _, err = cs.NewRegistryEnterpriseRepo(ctx, "my_repo", &cs.RegistryEnterpriseRepoArgs{
// InstanceId: my_namespace.InstanceId,
// Namespace: my_namespace.Name,
// Summary: pulumi.String("this is summary of my new repo"),
// RepoType: pulumi.String("PUBLIC"),
// Detail: pulumi.String("this is a public repo"),
// })
// if err != nil {
// return err
// }
// return nil
// })
// }
// ```
//
// ## Import
//
// Container Registry Enterprise Edition repository can be imported using the `{instance_id}:{namespace}:{repository}`, e.g.
//
// ```sh
// $ pulumi import alicloud:cs/registryEnterpriseRepo:RegistryEnterpriseRepo default `cri-xxx:my-namespace:my-repo`
// ```
type RegistryEnterpriseRepo struct {
pulumi.CustomResourceState
// The repository specific information. MarkDown format is supported, and the length limit is 2000.
Detail pulumi.StringPtrOutput `pulumi:"detail"`
// ID of Container Registry Enterprise Edition instance.
InstanceId pulumi.StringOutput `pulumi:"instanceId"`
// Name of Container Registry Enterprise Edition repository. It can contain 2 to 64 characters.
Name pulumi.StringOutput `pulumi:"name"`
// Name of Container Registry Enterprise Edition namespace where repository is located. It can contain 2 to 30 characters.
Namespace pulumi.StringOutput `pulumi:"namespace"`
// The uuid of Container Registry Enterprise Edition repository.
RepoId pulumi.StringOutput `pulumi:"repoId"`
// `PUBLIC` or `PRIVATE`, repo's visibility.
RepoType pulumi.StringOutput `pulumi:"repoType"`
// The repository general information. It can contain 1 to 100 characters.
Summary pulumi.StringOutput `pulumi:"summary"`
}
// NewRegistryEnterpriseRepo registers a new resource with the given unique name, arguments, and options.
func NewRegistryEnterpriseRepo(ctx *pulumi.Context,
name string, args *RegistryEnterpriseRepoArgs, opts ...pulumi.ResourceOption) (*RegistryEnterpriseRepo, error) |
// GetRegistryEnterpriseRepo gets an existing RegistryEnterpriseRepo resource's state with the given name, ID, and optional
// state properties that are used to uniquely qualify the lookup (nil if not required).
func GetRegistryEnterpriseRepo(ctx *pulumi.Context,
name string, id pulumi.IDInput, state *RegistryEnterpriseRepoState, opts ...pulumi.ResourceOption) (*RegistryEnterpriseRepo, error) {
var resource RegistryEnterpriseRepo
err := ctx.ReadResource("alicloud:cs/registryEnterpriseRepo:RegistryEnterpriseRepo", name, id, state, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
}
// Input properties used for looking up and filtering RegistryEnterpriseRepo resources.
type registryEnterpriseRepoState struct {
// The repository specific information. MarkDown format is supported, and the length limit is 2000.
Detail *string `pulumi:"detail"`
// ID of Container Registry Enterprise Edition instance.
InstanceId *string `pulumi:"instanceId"`
// Name of Container Registry Enterprise Edition repository. It can contain 2 to 64 characters.
Name *string `pulumi:"name"`
// Name of Container Registry Enterprise Edition namespace where repository is located. It can contain 2 to 30 characters.
Namespace *string `pulumi:"namespace"`
// The uuid of Container Registry Enterprise Edition repository.
RepoId *string `pulumi:"repoId"`
// `PUBLIC` or `PRIVATE`, repo's visibility.
RepoType *string `pulumi:"repoType"`
// The repository general information. It can contain 1 to 100 characters.
Summary *string `pulumi:"summary"`
}
type RegistryEnterpriseRepoState struct {
// The repository specific information. MarkDown format is supported, and the length limit is 2000.
Detail pulumi.StringPtrInput
// ID of Container Registry Enterprise Edition instance.
InstanceId pulumi.StringPtrInput
// Name of Container Registry Enterprise Edition repository. It can contain 2 to 64 characters.
Name pulumi.StringPtrInput
// Name of Container Registry Enterprise Edition namespace where repository is located. It can contain 2 to 30 characters.
Namespace pulumi.StringPtrInput
// The uuid of Container Registry Enterprise Edition repository.
RepoId pulumi.StringPtrInput
// `PUBLIC` or `PRIVATE`, repo's visibility.
RepoType pulumi.StringPtrInput
// The repository general information. It can contain 1 to 100 characters.
Summary pulumi.StringPtrInput
}
func (RegistryEnterpriseRepoState) ElementType() reflect.Type {
return reflect.TypeOf((*registryEnterpriseRepoState)(nil)).Elem()
}
type registryEnterpriseRepoArgs struct {
// The repository specific information. MarkDown format is supported, and the length limit is 2000.
Detail *string `pulumi:"detail"`
// ID of Container Registry Enterprise Edition instance.
InstanceId string `pulumi:"instanceId"`
// Name of Container Registry Enterprise Edition repository. It can contain 2 to 64 characters.
Name *string `pulumi:"name"`
// Name of Container Registry Enterprise Edition namespace where repository is located. It can contain 2 to 30 characters.
Namespace string `pulumi:"namespace"`
// `PUBLIC` or `PRIVATE`, repo's visibility.
RepoType string `pulumi:"repoType"`
// The repository general information. It can contain 1 to 100 characters.
Summary string `pulumi:"summary"`
}
// The set of arguments for constructing a RegistryEnterpriseRepo resource.
type RegistryEnterpriseRepoArgs struct {
// The repository specific information. MarkDown format is supported, and the length limit is 2000.
Detail pulumi.StringPtrInput
// ID of Container Registry Enterprise Edition instance.
InstanceId pulumi.StringInput
// Name of Container Registry Enterprise Edition repository. It can contain 2 to 64 characters.
Name pulumi.StringPtrInput
// Name of Container Registry Enterprise Edition namespace where repository is located. It can contain 2 to 30 characters.
Namespace pulumi.StringInput
// `PUBLIC` or `PRIVATE`, repo's visibility.
RepoType pulumi.StringInput
// The repository general information. It can contain 1 to 100 characters.
Summary pulumi.StringInput
}
func (RegistryEnterpriseRepoArgs) ElementType() reflect.Type {
return reflect.TypeOf((*registryEnterpriseRepoArgs)(nil)).Elem()
}
type RegistryEnterpriseRepoInput interface {
pulumi.Input
ToRegistryEnterpriseRepoOutput() RegistryEnterpriseRepoOutput
ToRegistryEnterpriseRepoOutputWithContext(ctx context.Context) RegistryEnterpriseRepoOutput
}
func (*RegistryEnterpriseRepo) ElementType() reflect.Type {
return reflect.TypeOf((*RegistryEnterpriseRepo)(nil))
}
func (i *RegistryEnterpriseRepo) ToRegistryEnterpriseRepoOutput() RegistryEnterpriseRepoOutput {
return i.ToRegistryEnterpriseRepoOutputWithContext(context.Background())
}
func (i *RegistryEnterpriseRepo) ToRegistryEnterpriseRepoOutputWithContext(ctx context.Context) RegistryEnterpriseRepoOutput {
return pulumi.ToOutputWithContext(ctx, i).(RegistryEnterpriseRepoOutput)
}
func (i *RegistryEnterpriseRepo) ToRegistryEnterpriseRepoPtrOutput() RegistryEnterpriseRepoPtrOutput {
return i.ToRegistryEnterpriseRepoPtrOutputWithContext(context.Background())
}
func (i *RegistryEnterpriseRepo) ToRegistryEnterpriseRepoPtrOutputWithContext(ctx context.Context) RegistryEnterpriseRepoPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(RegistryEnterpriseRepoPtrOutput)
}
type RegistryEnterpriseRepoPtrInput interface {
pulumi.Input
ToRegistryEnterpriseRepoPtrOutput() RegistryEnterpriseRepoPtrOutput
ToRegistryEnterpriseRepoPtrOutputWithContext(ctx context.Context) RegistryEnterpriseRepoPtrOutput
}
type registryEnterpriseRepoPtrType RegistryEnterpriseRepoArgs
func (*registryEnterpriseRepoPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**RegistryEnterpriseRepo)(nil))
}
func (i *registryEnterpriseRepoPtrType) ToRegistryEnterpriseRepoPtrOutput() RegistryEnterpriseRepoPtrOutput {
return i.ToRegistryEnterpriseRepoPtrOutputWithContext(context.Background())
}
func (i *registryEnterpriseRepoPtrType) ToRegistryEnterpriseRepoPtrOutputWithContext(ctx context.Context) RegistryEnterpriseRepoPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(RegistryEnterpriseRepoPtrOutput)
}
// RegistryEnterpriseRepoArrayInput is an input type that accepts RegistryEnterpriseRepoArray and RegistryEnterpriseRepoArrayOutput values.
// You can construct a concrete instance of `RegistryEnterpriseRepoArrayInput` via:
//
// RegistryEnterpriseRepoArray{ RegistryEnterpriseRepoArgs{...} }
type RegistryEnterpriseRepoArrayInput interface {
pulumi.Input
ToRegistryEnterpriseRepoArrayOutput() RegistryEnterpriseRepoArrayOutput
ToRegistryEnterpriseRepoArrayOutputWithContext(context.Context) RegistryEnterpriseRepoArrayOutput
}
type RegistryEnterpriseRepoArray []RegistryEnterpriseRepoInput
func (RegistryEnterpriseRepoArray) ElementType() reflect.Type {
return reflect.TypeOf(([]*RegistryEnterpriseRepo)(nil))
}
func (i RegistryEnterpriseRepoArray) ToRegistryEnterpriseRepoArrayOutput() RegistryEnterpriseRepoArrayOutput {
return i.ToRegistryEnterpriseRepoArrayOutputWithContext(context.Background())
}
func (i RegistryEnterpriseRepoArray) ToRegistryEnterpriseRepoArrayOutputWithContext(ctx context.Context) RegistryEnterpriseRepoArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(RegistryEnterpriseRepoArrayOutput)
}
// RegistryEnterpriseRepoMapInput is an input type that accepts RegistryEnterpriseRepoMap and RegistryEnterpriseRepoMapOutput values.
// You can construct a concrete instance of `RegistryEnterpriseRepoMapInput` via:
//
// RegistryEnterpriseRepoMap{ "key": RegistryEnterpriseRepoArgs{...} }
type RegistryEnterpriseRepoMapInput interface {
pulumi.Input
ToRegistryEnterpriseRepoMapOutput() RegistryEnterpriseRepoMapOutput
ToRegistryEnterpriseRepoMapOutputWithContext(context.Context) RegistryEnterpriseRepoMapOutput
}
type RegistryEnterpriseRepoMap map[string]RegistryEnterpriseRepoInput
func (RegistryEnterpriseRepoMap) ElementType() reflect.Type {
return reflect.TypeOf((map[string]*RegistryEnterpriseRepo)(nil))
}
func (i RegistryEnterpriseRepoMap) ToRegistryEnterpriseRepoMapOutput() RegistryEnterpriseRepoMapOutput {
return i.ToRegistryEnterpriseRepoMapOutputWithContext(context.Background())
}
func (i RegistryEnterpriseRepoMap) ToRegistryEnterpriseRepoMapOutputWithContext(ctx context.Context) RegistryEnterpriseRepoMapOutput {
return pulumi.ToOutputWithContext(ctx, i).(RegistryEnterpriseRepoMapOutput)
}
type RegistryEnterpriseRepoOutput struct {
*pulumi.OutputState
}
func (RegistryEnterpriseRepoOutput) ElementType() reflect.Type {
return reflect.TypeOf((*RegistryEnterpriseRepo)(nil))
}
func (o RegistryEnterpriseRepoOutput) ToRegistryEnterpriseRepoOutput() RegistryEnterpriseRepoOutput {
return o
}
func (o RegistryEnterpriseRepoOutput) ToRegistryEnterpriseRepoOutputWithContext(ctx context.Context) RegistryEnterpriseRepoOutput {
return o
}
func (o RegistryEnterpriseRepoOutput) ToRegistryEnterpriseRepoPtrOutput() RegistryEnterpriseRepoPtrOutput {
return o.ToRegistryEnterpriseRepoPtrOutputWithContext(context.Background())
}
func (o RegistryEnterpriseRepoOutput) ToRegistryEnterpriseRepoPtrOutputWithContext(ctx context.Context) RegistryEnterpriseRepoPtrOutput {
return o.ApplyT(func(v RegistryEnterpriseRepo) *RegistryEnterpriseRepo {
return &v
}).(RegistryEnterpriseRepoPtrOutput)
}
type RegistryEnterpriseRepoPtrOutput struct {
*pulumi.OutputState
}
func (RegistryEnterpriseRepoPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**RegistryEnterpriseRepo)(nil))
}
func (o RegistryEnterpriseRepoPtrOutput) ToRegistryEnterpriseRepoPtrOutput() RegistryEnterpriseRepoPtrOutput {
return o
}
func (o RegistryEnterpriseRepoPtrOutput) ToRegistryEnterpriseRepoPtrOutputWithContext(ctx context.Context) RegistryEnterpriseRepoPtrOutput {
return o
}
type RegistryEnterpriseRepoArrayOutput struct{ *pulumi.OutputState }
func (RegistryEnterpriseRepoArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]RegistryEnterpriseRepo)(nil))
}
func (o RegistryEnterpriseRepoArrayOutput) ToRegistryEnterpriseRepoArrayOutput() RegistryEnterpriseRepoArrayOutput {
return o
}
func (o RegistryEnterpriseRepoArrayOutput) ToRegistryEnterpriseRepoArrayOutputWithContext(ctx context.Context) RegistryEnterpriseRepoArrayOutput {
return o
}
func (o RegistryEnterpriseRepoArrayOutput) Index(i pulumi.IntInput) RegistryEnterpriseRepoOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) RegistryEnterpriseRepo {
return vs[0].([]RegistryEnterpriseRepo)[vs[1].(int)]
}).(RegistryEnterpriseRepoOutput)
}
type RegistryEnterpriseRepoMapOutput struct{ *pulumi.OutputState }
func (RegistryEnterpriseRepoMapOutput) ElementType() reflect.Type {
return reflect.TypeOf((*map[string]RegistryEnterpriseRepo)(nil))
}
func (o RegistryEnterpriseRepoMapOutput) ToRegistryEnterpriseRepoMapOutput() RegistryEnterpriseRepoMapOutput {
return o
}
func (o RegistryEnterpriseRepoMapOutput) ToRegistryEnterpriseRepoMapOutputWithContext(ctx context.Context) RegistryEnterpriseRepoMapOutput {
return o
}
func (o RegistryEnterpriseRepoMapOutput) MapIndex(k pulumi.StringInput) RegistryEnterpriseRepoOutput {
return pulumi.All(o, k).ApplyT(func(vs []interface{}) RegistryEnterpriseRepo {
return vs[0].(map[string]RegistryEnterpriseRepo)[vs[1].(string)]
}).(RegistryEnterpriseRepoOutput)
}
func init() {
pulumi.RegisterOutputType(RegistryEnterpriseRepoOutput{})
pulumi.RegisterOutputType(RegistryEnterpriseRepoPtrOutput{})
pulumi.RegisterOutputType(RegistryEnterpriseRepoArrayOutput{})
pulumi.RegisterOutputType(RegistryEnterpriseRepoMapOutput{})
}
| {
if args == nil {
return nil, errors.New("missing one or more required arguments")
}
if args.InstanceId == nil {
return nil, errors.New("invalid value for required argument 'InstanceId'")
}
if args.Namespace == nil {
return nil, errors.New("invalid value for required argument 'Namespace'")
}
if args.RepoType == nil {
return nil, errors.New("invalid value for required argument 'RepoType'")
}
if args.Summary == nil {
return nil, errors.New("invalid value for required argument 'Summary'")
}
var resource RegistryEnterpriseRepo
err := ctx.RegisterResource("alicloud:cs/registryEnterpriseRepo:RegistryEnterpriseRepo", name, args, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
} |
schemachange.go | // Copyright 2018 The Cockroach 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. See the AUTHORS file
// for names of contributors.
package main
import (
"context"
gosql "database/sql"
"fmt"
"time"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/pkg/errors"
)
func registerSchemaChangeKV(r *registry) {
r.Add(testSpec{
Name: `schemachange/mixed/kv`,
Nodes: nodes(5),
Run: func(ctx context.Context, t *test, c *cluster) {
const fixturePath = `gs://cockroach-fixtures/workload/tpch/scalefactor=10/backup`
c.Put(ctx, cockroach, "./cockroach")
c.Put(ctx, workload, "./workload")
c.Start(ctx, t, c.All())
db := c.Conn(ctx, 1)
defer db.Close()
m := newMonitor(ctx, c, c.All())
m.Go(func(ctx context.Context) error {
t.Status("loading fixture")
if _, err := db.Exec(`RESTORE DATABASE tpch FROM $1`, fixturePath); err != nil {
t.Fatal(err)
}
return nil
})
m.Wait()
c.Run(ctx, c.Node(1), `./workload init kv --drop --db=test`)
for node := 1; node <= c.nodes; node++ {
node := node
// TODO(dan): Ideally, the test would fail if this queryload failed,
// but we can't put it in monitor as-is because the test deadlocks.
go func() {
const cmd = `./workload run kv --tolerate-errors --min-block-bytes=8 --max-block-bytes=128 --db=test`
l, err := t.l.ChildLogger(fmt.Sprintf(`kv-%d`, node))
if err != nil {
t.Fatal(err)
}
defer l.close()
_ = execCmd(ctx, t.l, roachprod, "ssh", c.makeNodes(c.Node(node)), "--", cmd)
}()
}
m = newMonitor(ctx, c, c.All())
m.Go(func(ctx context.Context) error {
t.Status("running schema change tests")
return waitForSchemaChanges(ctx, t.l, db)
})
m.Wait()
},
})
}
func waitForSchemaChanges(ctx context.Context, l *logger, db *gosql.DB) error {
start := timeutil.Now()
// These schema changes are over a table that is not actively
// being updated.
l.Printf("running schema changes over tpch.customer\n")
schemaChanges := []string{
"ALTER TABLE tpch.customer ADD COLUMN newcol INT DEFAULT 23456",
"CREATE INDEX foo ON tpch.customer (c_name)",
}
if err := runSchemaChanges(ctx, l, db, schemaChanges); err != nil {
return err
}
// TODO(vivek): Fix #21544.
// if err := sqlutils.RunScrub(db, `test`, `kv`); err != nil {
// return err
// }
// All these return the same result.
validationQueries := []string{
"SELECT count(*) FROM tpch.customer AS OF SYSTEM TIME %s",
"SELECT count(newcol) FROM tpch.customer AS OF SYSTEM TIME %s",
"SELECT count(c_name) FROM tpch.customer@foo AS OF SYSTEM TIME %s",
}
if err := runValidationQueries(ctx, l, db, start, validationQueries, nil); err != nil {
return err
}
// These schema changes are run later because the above schema
// changes run for a decent amount of time giving kv.kv
// an opportunity to get populate through the load generator. These
// schema changes are acting upon a decent sized table that is also
// being updated.
l.Printf("running schema changes over test.kv\n")
schemaChanges = []string{
"ALTER TABLE test.kv ADD COLUMN created_at TIMESTAMP DEFAULT now()",
"CREATE INDEX foo ON test.kv (v)",
}
if err := runSchemaChanges(ctx, l, db, schemaChanges); err != nil {
return err
}
// TODO(vivek): Fix #21544.
// if err := sqlutils.RunScrub(db, `test`, `kv`); err != nil {
// return err
// }
// All these return the same result.
validationQueries = []string{
"SELECT count(*) FROM test.kv AS OF SYSTEM TIME %s",
"SELECT count(v) FROM test.kv AS OF SYSTEM TIME %s",
"SELECT count(v) FROM test.kv@foo AS OF SYSTEM TIME %s",
}
// Queries to hone in on index validation problems.
indexValidationQueries := []string{
"SELECT count(k) FROM test.kv@primary AS OF SYSTEM TIME %s WHERE created_at > $1 AND created_at <= $2",
"SELECT count(v) FROM test.kv@foo AS OF SYSTEM TIME %s WHERE created_at > $1 AND created_at <= $2",
}
return runValidationQueries(ctx, l, db, start, validationQueries, indexValidationQueries)
}
func runSchemaChanges(ctx context.Context, l *logger, db *gosql.DB, schemaChanges []string) error {
for _, cmd := range schemaChanges {
start := timeutil.Now()
l.Printf("starting schema change: %s\n", cmd)
if _, err := db.Exec(cmd); err != nil {
l.Errorf("hit schema change error: %s, for %s, in %s\n", err, cmd, timeutil.Since(start))
return err
}
l.Printf("completed schema change: %s, in %s\n", cmd, timeutil.Since(start))
// TODO(vivek): Monitor progress of schema changes and log progress.
}
return nil
}
// The validationQueries all return the same result.
func runValidationQueries(
ctx context.Context,
l *logger,
db *gosql.DB,
start time.Time,
validationQueries []string,
indexValidationQueries []string,
) error {
// Sleep for a bit before validating the schema changes to
// accommodate for time differences between nodes. Some of the
// schema change backfill transactions might use a timestamp a bit
// into the future. This is not a problem normally because a read
// of schema data written into the impending future gets pushed,
// but the reads being done here are at a specific timestamp through
// AS OF SYSTEM TIME.
time.Sleep(5 * time.Second)
var nowString string
if err := db.QueryRow("SELECT cluster_logical_timestamp()").Scan(&nowString); err != nil {
return err
}
var nowInNanos int64
if _, err := fmt.Sscanf(nowString, "%d", &nowInNanos); err != nil {
return err
}
now := timeutil.Unix(0, nowInNanos)
// Validate the different schema changes
var eCount int64
for i := range validationQueries {
var count int64
q := fmt.Sprintf(validationQueries[i], nowString)
if err := db.QueryRow(q).Scan(&count); err != nil {
return err
}
l.Printf("query: %s, found %d rows\n", q, count)
if count == 0 {
return errors.Errorf("%s: %d rows found", q, count)
}
if eCount == 0 {
eCount = count
// Investigate index creation problems. Always run this so we know
// it works.
if indexValidationQueries != nil {
sp := timeSpan{start: start, end: now}
if err := findIndexProblem(
ctx, l, db, sp, nowString, indexValidationQueries,
); err != nil {
return err
}
}
} else if count != eCount {
return errors.Errorf("%s: %d rows found, expected %d rows", q, count, eCount)
}
}
return nil
}
type timeSpan struct {
start, end time.Time
}
// Check index inconsistencies over the timeSpan and return true when
// problems are seen.
func checkIndexOverTimeSpan(
ctx context.Context,
l *logger,
db *gosql.DB,
s timeSpan,
nowString string,
indexValidationQueries []string,
) (bool, error) {
var eCount int64
q := fmt.Sprintf(indexValidationQueries[0], nowString)
if err := db.QueryRow(q, s.start, s.end).Scan(&eCount); err != nil {
return false, err
}
var count int64
q = fmt.Sprintf(indexValidationQueries[1], nowString)
if err := db.QueryRow(q, s.start, s.end).Scan(&count); err != nil {
return false, err
}
l.Printf("counts seen %d, %d, over [%s, %s]\n", count, eCount, s.start, s.end)
return count != eCount, nil
}
// Keep splitting the span of time passed and log where index
// inconsistencies are seen.
func findIndexProblem(
ctx context.Context,
l *logger,
db *gosql.DB,
s timeSpan,
nowString string,
indexValidationQueries []string,
) error {
spans := []timeSpan{s}
// process all the outstanding time spans.
for len(spans) > 0 {
s := spans[0]
spans = spans[1:]
// split span into two time ranges.
leftSpan, rightSpan := s, s
d := s.end.Sub(s.start) / 2
if d < 50*time.Millisecond {
l.Printf("problem seen over [%s, %s]\n", s.start, s.end)
continue
}
m := s.start.Add(d)
leftSpan.end = m
rightSpan.start = m
leftState, err := checkIndexOverTimeSpan(
ctx, l, db, leftSpan, nowString, indexValidationQueries)
if err != nil {
return err
}
rightState, err := checkIndexOverTimeSpan(
ctx, l, db, rightSpan, nowString, indexValidationQueries)
if err != nil {
return err
}
if leftState {
spans = append(spans, leftSpan)
}
if rightState {
spans = append(spans, rightSpan)
}
if !(leftState || rightState) {
l.Printf("no problem seen over [%s, %s]\n", s.start, s.end)
}
}
return nil
}
func registerSchemaChangeIndexTPCC1000(r *registry) {
r.Add(makeIndexAddTpccTest(5, 1000, time.Hour*3))
}
func registerSchemaChangeIndexTPCC100(r *registry) {
r.Add(makeIndexAddTpccTest(5, 100, time.Minute*10))
}
func makeIndexAddTpccTest(numNodes, warehouses int, length time.Duration) testSpec {
return testSpec{
Name: fmt.Sprintf("schemachange/index/tpcc-%d", warehouses),
Nodes: nodes(numNodes),
Timeout: length * 2,
Run: func(ctx context.Context, t *test, c *cluster) {
runTPCC(ctx, t, c, tpccOptions{
Warehouses: warehouses,
Extra: "--wait=false --tolerate-errors",
During: func(ctx context.Context) error {
return runAndLogStmts(ctx, t, c, "addindex", []string{
`CREATE UNIQUE INDEX ON tpcc.order (o_entry_d, o_w_id, o_d_id, o_carrier_id, o_id);`,
`CREATE INDEX ON tpcc.order (o_carrier_id);`,
`CREATE INDEX ON tpcc.customer (c_last, c_first);`,
})
},
Duration: length,
})
},
}
}
func runAndLogStmts(ctx context.Context, t *test, c *cluster, prefix string, stmts []string) error | {
conn := c.Conn(ctx, 1)
c.l.Printf("%s: running %d statements\n", prefix, len(stmts))
start := timeutil.Now()
for i, stmt := range stmts {
c.l.Printf("%s: running statement %d...\n", prefix, i+1)
before := timeutil.Now()
if _, err := conn.Exec(stmt); err != nil {
t.Fatal(err)
}
c.l.Printf("%s: statement %d: %q took %v\n", prefix, i+1, stmt, timeutil.Since(before))
}
c.l.Printf("%s: ran %d statements in %v\n", prefix, len(stmts), timeutil.Since(start))
return nil
} |
|
config.go | package unifipoller
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"path"
"reflect"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
influx "github.com/influxdata/influxdb1-client/v2"
"github.com/spf13/pflag"
"golift.io/unifi"
yaml "gopkg.in/yaml.v2"
)
// Version is injected by the Makefile
var Version = "development"
const (
// App defaults in case they're missing from the config.
defaultInterval = 30 * time.Second
defaultInfluxDB = "unifi"
defaultInfluxUser = "unifi"
defaultInfluxPass = "unifi"
defaultInfluxURL = "http://127.0.0.1:8086"
defaultUnifiUser = "influx"
defaultUnifiURL = "https://127.0.0.1:8443"
)
// ENVConfigPrefix is the prefix appended to an env variable tag
// name before retrieving the value from the OS.
const ENVConfigPrefix = "UP_"
// UnifiPoller contains the application startup data, and auth info for UniFi & Influx.
type UnifiPoller struct {
Influx influx.Client
Unifi *unifi.Unifi
Flag *Flag
Config *Config
errorCount int
LastCheck time.Time
}
// Flag represents the CLI args available and their settings.
type Flag struct {
ConfigFile string
DumpJSON string
ShowVer bool
*pflag.FlagSet
}
// Metrics contains all the data from the controller and an influx endpoint to send it to.
type Metrics struct {
TS time.Time
unifi.Sites
unifi.IDSList
unifi.Clients
*unifi.Devices
influx.BatchPoints
}
// Config represents the data needed to poll a controller and report to influxdb.
// This is all of the data stored in the config file.
// Any with explicit defaults have _omitempty on json and toml tags.
type Config struct {
MaxErrors int `json:"max_errors" toml:"max_errors" xml:"max_errors" yaml:"max_errors" env:"MAX_ERRORS"`
Interval Duration `json:"interval,_omitempty" toml:"interval,_omitempty" xml:"interval" yaml:"interval" env:"POLLING_INTERVAL"`
Debug bool `json:"debug" toml:"debug" xml:"debug" yaml:"debug" env:"DEBUG_MODE"`
Quiet bool `json:"quiet,_omitempty" toml:"quiet,_omitempty" xml:"quiet" yaml:"quiet" env:"QUIET_MODE"`
VerifySSL bool `json:"verify_ssl" toml:"verify_ssl" xml:"verify_ssl" yaml:"verify_ssl" env:"VERIFY_SSL"`
CollectIDS bool `json:"collect_ids" toml:"collect_ids" xml:"collect_ids" yaml:"collect_ids" env:"COLLECT_IDS"`
ReAuth bool `json:"reauthenticate" toml:"reauthenticate" xml:"reauthenticate" yaml:"reauthenticate" env:"REAUTHENTICATE"`
Mode string `json:"mode" toml:"mode" xml:"mode" yaml:"mode" env:"POLLING_MODE"`
InfluxURL string `json:"influx_url,_omitempty" toml:"influx_url,_omitempty" xml:"influx_url" yaml:"influx_url" env:"INFLUX_URL"`
InfluxUser string `json:"influx_user,_omitempty" toml:"influx_user,_omitempty" xml:"influx_user" yaml:"influx_user" env:"INFLUX_USER"`
InfluxPass string `json:"influx_pass,_omitempty" toml:"influx_pass,_omitempty" xml:"influx_pass" yaml:"influx_pass" env:"INFLUX_PASS"`
InfluxDB string `json:"influx_db,_omitempty" toml:"influx_db,_omitempty" xml:"influx_db" yaml:"influx_db" env:"INFLUX_DB"`
UnifiUser string `json:"unifi_user,_omitempty" toml:"unifi_user,_omitempty" xml:"unifi_user" yaml:"unifi_user" env:"UNIFI_USER"`
UnifiPass string `json:"unifi_pass,_omitempty" toml:"unifi_pass,_omitempty" xml:"unifi_pass" yaml:"unifi_pass" env:"UNIFI_PASS"`
UnifiBase string `json:"unifi_url,_omitempty" toml:"unifi_url,_omitempty" xml:"unifi_url" yaml:"unifi_url" env:"UNIFI_URL"`
Sites []string `json:"sites,_omitempty" toml:"sites,_omitempty" xml:"sites" yaml:"sites" env:"POLL_SITES"`
}
// Duration is used to UnmarshalTOML into a time.Duration value.
type Duration struct{ time.Duration }
// UnmarshalText parses a duration type from a config file.
func (d *Duration) UnmarshalText(data []byte) (err error) {
d.Duration, err = time.ParseDuration(string(data))
return
}
// ParseFile parses and returns our configuration data.
func (c *Config) ParseFile(configFile string) error {
switch buf, err := ioutil.ReadFile(configFile); {
case err != nil:
return err
case strings.Contains(configFile, ".json"):
return json.Unmarshal(buf, c)
case strings.Contains(configFile, ".xml"):
return xml.Unmarshal(buf, c) | return yaml.Unmarshal(buf, c)
default:
return toml.Unmarshal(buf, c)
}
}
// ParseENV copies environment variables into configuration values.
// This is useful for Docker users that find it easier to pass ENV variables
// than a specific configuration file. Uses reflection to find struct tags.
func (c *Config) ParseENV() error {
t := reflect.TypeOf(Config{}) // Get tag names from the Config struct.
// Loop each Config struct member; get reflect tag & env var value; update config.
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag.Get("env") // Get the ENV variable name from "env" struct tag
env := os.Getenv(ENVConfigPrefix + tag) // Then pull value from OS.
if tag == "" || env == "" {
continue // Skip if either are empty.
}
// Reflect and update the u.Config struct member at position i.
switch c := reflect.ValueOf(c).Elem().Field(i); c.Type().String() {
// Handle each member type appropriately (differently).
case "string":
// This is a reflect package method to update a struct member by index.
c.SetString(env)
case "int":
val, err := strconv.Atoi(env)
if err != nil {
return fmt.Errorf("%s: %v", tag, err)
}
c.Set(reflect.ValueOf(val))
case "[]string":
c.Set(reflect.ValueOf(strings.Split(env, ",")))
case path.Base(t.PkgPath()) + ".Duration":
val, err := time.ParseDuration(env)
if err != nil {
return fmt.Errorf("%s: %v", tag, err)
}
c.Set(reflect.ValueOf(Duration{val}))
case "bool":
val, err := strconv.ParseBool(env)
if err != nil {
return fmt.Errorf("%s: %v", tag, err)
}
c.SetBool(val)
}
}
return nil
} | case strings.Contains(configFile, ".yaml"): |
main.go | package main
import (
"os" |
"github.com/karmada-io/karmada/cmd/aggregated-apiserver/app"
)
func main() {
if err := runAggregatedApiserverCmd(); err != nil {
os.Exit(1)
}
}
func runAggregatedApiserverCmd() error {
logs.InitLogs()
defer logs.FlushLogs()
ctx := apiserver.SetupSignalContext()
if err := app.NewAggregatedApiserverCommand(ctx).Execute(); err != nil {
return err
}
return nil
} |
apiserver "k8s.io/apiserver/pkg/server"
"k8s.io/component-base/logs" |
ccr.py | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. 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.
from .utils import SKIP_IN_PATH, NamespacedClient, _make_path, query_params
class CcrClient(NamespacedClient):
@query_params()
def delete_auto_follow_pattern(self, name, params=None, headers=None):
"""
Deletes auto-follow patterns.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-delete-auto-follow-pattern.html>`_
:arg name: The name of the auto follow pattern.
"""
if name in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'name'.")
return self.transport.perform_request(
"DELETE",
_make_path("_ccr", "auto_follow", name),
params=params,
headers=headers,
)
@query_params("wait_for_active_shards")
def follow(self, index, body, params=None, headers=None):
"""
Creates a new follower index configured to follow the referenced leader index.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-put-follow.html>`_
:arg index: The name of the follower index
:arg body: The name of the leader index and other optional ccr
related parameters
:arg wait_for_active_shards: Sets the number of shard copies
that must be active before returning. Defaults to 0. Set to `all` for
all shard copies, otherwise set to any non-negative value less than or
equal to the total number of copies for the shard (number of replicas +
1) Default: 0
"""
for param in (index, body):
if param in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument.")
return self.transport.perform_request(
"PUT",
_make_path(index, "_ccr", "follow"),
params=params,
headers=headers,
body=body,
)
@query_params()
def follow_info(self, index, params=None, headers=None):
"""
Retrieves information about all follower indices, including parameters and
status for each follower index
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-get-follow-info.html>`_
:arg index: A comma-separated list of index patterns; use `_all`
to perform the operation on all indices
"""
if index in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'index'.")
return self.transport.perform_request(
"GET", _make_path(index, "_ccr", "info"), params=params, headers=headers
)
@query_params()
def follow_stats(self, index, params=None, headers=None):
"""
Retrieves follower stats. return shard-level stats about the following tasks
associated with each shard for the specified indices.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-get-follow-stats.html>`_
:arg index: A comma-separated list of index patterns; use `_all`
to perform the operation on all indices
"""
if index in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'index'.")
return self.transport.perform_request(
"GET", _make_path(index, "_ccr", "stats"), params=params, headers=headers
)
@query_params()
def forget_follower(self, index, body, params=None, headers=None):
"""
Removes the follower retention leases from the leader.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-post-forget-follower.html>`_
:arg index: the name of the leader index for which specified
follower retention leases should be removed
:arg body: the name and UUID of the follower index, the name of
the cluster containing the follower index, and the alias from the
perspective of that cluster for the remote cluster containing the leader
index
"""
for param in (index, body):
if param in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument.")
return self.transport.perform_request(
"POST",
_make_path(index, "_ccr", "forget_follower"),
params=params,
headers=headers,
body=body,
)
@query_params()
def get_auto_follow_pattern(self, name=None, params=None, headers=None):
"""
Gets configured auto-follow patterns. Returns the specified auto-follow pattern
collection.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-get-auto-follow-pattern.html>`_
:arg name: The name of the auto follow pattern.
"""
return self.transport.perform_request(
"GET",
_make_path("_ccr", "auto_follow", name),
params=params,
headers=headers,
)
@query_params()
def pause_follow(self, index, params=None, headers=None):
|
@query_params()
def put_auto_follow_pattern(self, name, body, params=None, headers=None):
"""
Creates a new named collection of auto-follow patterns against a specified
remote cluster. Newly created indices on the remote cluster matching any of the
specified patterns will be automatically configured as follower indices.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-put-auto-follow-pattern.html>`_
:arg name: The name of the auto follow pattern.
:arg body: The specification of the auto follow pattern
"""
for param in (name, body):
if param in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument.")
return self.transport.perform_request(
"PUT",
_make_path("_ccr", "auto_follow", name),
params=params,
headers=headers,
body=body,
)
@query_params()
def resume_follow(self, index, body=None, params=None, headers=None):
"""
Resumes a follower index that has been paused
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-post-resume-follow.html>`_
:arg index: The name of the follow index to resume following.
:arg body: The name of the leader index and other optional ccr
related parameters
"""
if index in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'index'.")
return self.transport.perform_request(
"POST",
_make_path(index, "_ccr", "resume_follow"),
params=params,
headers=headers,
body=body,
)
@query_params()
def stats(self, params=None, headers=None):
"""
Gets all stats related to cross-cluster replication.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-get-stats.html>`_
"""
return self.transport.perform_request(
"GET", "/_ccr/stats", params=params, headers=headers
)
@query_params()
def unfollow(self, index, params=None, headers=None):
"""
Stops the following task associated with a follower index and removes index
metadata and settings associated with cross-cluster replication.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-post-unfollow.html>`_
:arg index: The name of the follower index that should be turned
into a regular index.
"""
if index in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'index'.")
return self.transport.perform_request(
"POST",
_make_path(index, "_ccr", "unfollow"),
params=params,
headers=headers,
)
@query_params()
def pause_auto_follow_pattern(self, name, params=None, headers=None):
"""
Pauses an auto-follow pattern
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-pause-auto-follow-pattern.html>`_
:arg name: The name of the auto follow pattern that should pause
discovering new indices to follow.
"""
if name in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'name'.")
return self.transport.perform_request(
"POST",
_make_path("_ccr", "auto_follow", name, "pause"),
params=params,
headers=headers,
)
@query_params()
def resume_auto_follow_pattern(self, name, params=None, headers=None):
"""
Resumes an auto-follow pattern that has been paused
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-resume-auto-follow-pattern.html>`_
:arg name: The name of the auto follow pattern to resume
discovering new indices to follow.
"""
if name in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'name'.")
return self.transport.perform_request(
"POST",
_make_path("_ccr", "auto_follow", name, "resume"),
params=params,
headers=headers,
)
| """
Pauses a follower index. The follower index will not fetch any additional
operations from the leader index.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.14/ccr-post-pause-follow.html>`_
:arg index: The name of the follower index that should pause
following its leader index.
"""
if index in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'index'.")
return self.transport.perform_request(
"POST",
_make_path(index, "_ccr", "pause_follow"),
params=params,
headers=headers,
) |
agents.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.teachers import DialogTeacher
from .build import build
import json
import os
class DefaultTeacher(DialogTeacher):
"""MutualFriends dataset."""
def __init__(self, opt, shared=None):
|
def act(self):
"""Use DialogTeacher act but set id to "Teacher" for intro message."""
reply = super().act()
if reply.get('text', '').startswith('You have the following friends'):
reply['id'] = 'Teacher'
return reply
def setup_data(self, path):
"""Load json data of conversations."""
print('loading: ' + path)
with open(path) as data_file:
self.loaded_data = json.load(data_file)
for ex in self.loaded_data:
if len(ex['events']) > 0:
# TODO: add reverse conversation as well
curr_agent = ex['events'][0]['agent']
conversation = [
(
'You have the following friends:\n'
+ '\n'.join(
', '.join('{}={}'.format(k, v) for k, v in person.items())
for person in ex['scenario']['kbs'][int(curr_agent)]
)
+ '\nTry to find out which friend the other person has in common.'
)
]
curr = ''
idx = 0
while idx < len(ex['events']):
msg = ex['events'][idx]['data']
if type(msg) == dict:
msg = 'SELECT({})'.format(
', '.join('{}={}'.format(k, v) for k, v in msg.items())
)
next_agent = ex['events'][idx]['agent']
if curr_agent == next_agent:
curr += '\n' + msg
curr = curr.strip()
else:
conversation.append(curr)
curr = msg
curr_agent = next_agent
idx += 1
conversation.append(curr)
for i in range(0, len(conversation), 2):
if i + 1 < len(conversation) - 1:
yield (conversation[i], [conversation[i + 1]]), i == 0
elif i + 1 == len(conversation) - 1:
yield (
(conversation[i], [conversation[i + 1]], ex['outcome']),
False,
)
else:
yield (conversation[i], None, ex['outcome']), False
| self.datatype = opt['datatype']
build(opt)
if not opt['datatype'].startswith('train'):
raise RuntimeError('MutualFriends only has a training set.')
opt['datafile'] = os.path.join(opt['datapath'], 'MutualFriends', 'data.json')
self.id = 'mutualfriends'
super().__init__(opt, shared) |
app.module.ts | import { registerLocaleData } from '@angular/common';
import localeES from '@angular/common/locales/es';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { AngularFireModule } from '@angular/fire';
import { ScreenTrackingService } from '@angular/fire/analytics';
// import { SmsRetriever } from '@ionic-native/sms-retriever/ngx';
import {
AngularFireAuthModule,
USE_EMULATOR as USE_AUTH_EMULATOR,
} from '@angular/fire/auth';
import { AngularFireAuthGuardModule } from '@angular/fire/auth-guard';
import {
AngularFirestoreModule,
SETTINGS,
USE_EMULATOR as USE_FIRESTORE_EMULATOR,
} from '@angular/fire/firestore';
import {
REGION,
USE_EMULATOR as USE_FUNCTIONS_EMULATOR,
} from '@angular/fire/functions';
import { AngularFirePerformanceModule } from '@angular/fire/performance';
import { AngularFireStorageModule } from '@angular/fire/storage';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { ServiceWorkerModule } from '@angular/service-worker';
import { FirebaseAuthentication } from '@ionic-native/firebase-authentication/ngx';
import { GooglePlus } from '@ionic-native/google-plus/ngx';
import { ImagePicker } from '@ionic-native/image-picker/ngx';
import { Keyboard } from '@ionic-native/keyboard/ngx';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import 'reflect-metadata';
import { environment } from '../environments/environment';
import { AddAgendaPageModule } from './add-agenda/add-agenda.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AppSharedModule } from './core/shared.module';
import './firebase-initialization';
import { PaginationService } from './services/pagination-service.service';
registerLocaleData(localeES, 'es');
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirePerformanceModule,
AngularFirestoreModule,
AngularFireAuthModule,
AngularFireStorageModule,
AngularFireAuthGuardModule,
AddAgendaPageModule,
FormsModule,
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production,
}),
AppSharedModule,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [
StatusBar,
GooglePlus,
SplashScreen,
PaginationService,
ScreenTrackingService,
Keyboard,
ImagePicker,
FirebaseAuthentication,
// SmsRetriever,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
{ provide: REGION, useValue: 'europe-west1' },
{
provide: SETTINGS,
useValue: { experimentalAutoDetectLongPolling: true, merge: true },
},
{
provide: USE_FIRESTORE_EMULATOR,
useValue: !environment.production ? ['localhost', 8080] : undefined,
},
{
provide: USE_AUTH_EMULATOR,
useValue: !environment.production ? ['localhost', 9099] : undefined,
},
{
provide: USE_FUNCTIONS_EMULATOR,
useValue: !environment.production ? ['localhost', 5001] : undefined,
},
],
bootstrap: [AppComponent],
})
export class | {}
| AppModule |
sol2.py | class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
# Firstly, we count frequencies
freq = {}
freq_to_chars = {}
result = []
for c in s:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
for c, f in freq.iteritems():
if f in freq_to_chars:
freq_to_chars[f] = ''.join([freq_to_chars[f], c * f])
else: | result.extend(freq_to_chars[i])
return ''.join(result) | freq_to_chars[f] = c * f
for i in range(len(s), 0, -1):
if i in freq_to_chars: |
StrategyManager.py | class | ():
def __init__():
pass | StrategyManager |
preprocess.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
from itertools import zip_longest
def replace_oovs(source_in, target_in, vocabulary, source_out, target_out):
"""Replaces out-of-vocabulary words in source and target text with <unk-N>,
where N in is the position of the word in the source sequence.
"""
def format_unk(pos):
return "<unk-{}>".format(pos)
if target_in is None:
target_in = []
for seq_num, (source_seq, target_seq) in enumerate(
zip_longest(source_in, target_in)
):
source_seq_out = []
target_seq_out = []
word_to_pos = dict()
for position, token in enumerate(source_seq.strip().split()):
if token in vocabulary:
token_out = token
else:
if token in word_to_pos:
oov_pos = word_to_pos[token]
else:
word_to_pos[token] = position
oov_pos = position
token_out = format_unk(oov_pos)
source_seq_out.append(token_out)
source_out.write(" ".join(source_seq_out) + "\n")
if target_seq is not None:
for token in target_seq.strip().split():
if token in word_to_pos:
token_out = format_unk(word_to_pos[token])
else:
token_out = token
target_seq_out.append(token_out)
if target_out is not None:
target_out.write(" ".join(target_seq_out) + "\n")
def main():
parser = argparse.ArgumentParser(
description="Replaces out-of-vocabulary words in both source and target "
"sequences with tokens that indicate the position of the word "
"in the source sequence."
)
parser.add_argument(
"--source", type=str, help="text file with source sequences", required=True
)
parser.add_argument( | "--source-out",
type=str,
help="where to write source sequences with <unk-N> entries",
required=True,
)
parser.add_argument(
"--target-out",
type=str,
help="where to write target sequences with <unk-N> entries",
default=None,
)
args = parser.parse_args()
with open(args.vocab, encoding="utf-8") as vocab:
vocabulary = vocab.read().splitlines()
target_in = (
open(args.target, "r", encoding="utf-8") if args.target is not None else None
)
target_out = (
open(args.target_out, "w", encoding="utf-8")
if args.target_out is not None
else None
)
with open(args.source, "r", encoding="utf-8") as source_in, open(
args.source_out, "w", encoding="utf-8"
) as source_out:
replace_oovs(source_in, target_in, vocabulary, source_out, target_out)
if target_in is not None:
target_in.close()
if target_out is not None:
target_out.close()
if __name__ == "__main__":
main() | "--target", type=str, help="text file with target sequences", default=None
)
parser.add_argument("--vocab", type=str, help="vocabulary file", required=True)
parser.add_argument( |
firmata_cat_toy.go | // +build example
//
// Do not build by default.
/*
How to run
Pass serial port to use as the first param:
go run examples/firmata_cat_toy.go /dev/ttyACM0
*/
package main
import (
"fmt"
"os"
"time"
"github.com/matipan/gobot"
"github.com/matipan/gobot/drivers/gpio"
"github.com/matipan/gobot/platforms/firmata"
"github.com/matipan/gobot/platforms/leap"
)
func | () {
firmataAdaptor := firmata.NewAdaptor(os.Args[1])
servo1 := gpio.NewServoDriver(firmataAdaptor, "5")
servo2 := gpio.NewServoDriver(firmataAdaptor, "3")
leapAdaptor := leap.NewAdaptor("127.0.0.1:6437")
leapDriver := leap.NewDriver(leapAdaptor)
work := func() {
x := 90.0
z := 90.0
leapDriver.On(leap.MessageEvent, func(data interface{}) {
if len(data.(leap.Frame).Hands) > 0 {
hand := data.(leap.Frame).Hands[0]
x = gobot.ToScale(gobot.FromScale(hand.X(), -300, 300), 30, 150)
z = gobot.ToScale(gobot.FromScale(hand.Z(), -300, 300), 30, 150)
}
})
gobot.Every(10*time.Millisecond, func() {
servo1.Move(uint8(x))
servo2.Move(uint8(z))
fmt.Println("Current Angle: ", servo1.CurrentAngle, ",", servo2.CurrentAngle)
})
}
robot := gobot.NewRobot("pwmBot",
[]gobot.Connection{firmataAdaptor, leapAdaptor},
[]gobot.Device{servo1, servo2, leapDriver},
work,
)
robot.Start()
}
| main |
index.js | /* @flow */
import {
__,
always,
assoc,
concat,
pipe,
prop,
reduce,
set,
lensPath,
flip,
map,
sortBy,
ifElse,
equals,
propSatisfies,
lte,
path,
subtract,
T,
includes,
cond,
nth,
not,
apply,
both,
propEq,
slice,
over,
lensProp,
assocPath,
add,
max,
min,
lens,
juxt,
isNil,
remove,
filter,
} from "ramda";
import { Input, Output, State } from "eff";
import {
getNotesOfFolder,
openFolder,
getAllFoldersWithChildrenFolders,
showNote,
moveNoteToFolder,
deleteNote,
createFolder,
} from "./notes.js";
import { activateApplication } from "./system.js";
// eslint-disable-next-line
const exampleState = {
folders: {
containerMap: {},
allFolders: { name: "", containers: [] },
},
notesToTriage: [],
currentNoteIndex: 0,
currentInput: {
substring: "",
selectedIndex: 0,
eligibleFolders: [],
},
};
const substringStartDifference = pipe(
map(prop("substringStart")),
apply(subtract),
);
const nameLengthDifference = pipe(
map(path(["name", "length"])),
apply(subtract),
);
type FolderSubstringDetails = {
name: string,
containers: Array<string>,
substringStart: number,
};
export const folderSubstringSort = (
a: FolderSubstringDetails,
b: FolderSubstringDetails,
) =>
cond([
[
both(
pipe(
nth(0),
propSatisfies(includes("4 Archive"))("containers"),
),
pipe(
nth(1),
propSatisfies(includes("4 Archive"))("containers"),
not,
),
),
always(1),
],
[
both(
pipe(
nth(0),
propSatisfies(includes("4 Archive"))("containers"),
not,
),
pipe(
nth(1),
propSatisfies(includes("4 Archive"))("containers"),
),
),
always(-1),
],
[
pipe(
substringStartDifference,
equals(0),
not,
),
substringStartDifference, | ])([a, b]);
const ESC = String.fromCharCode(27);
const cursorUpLines = n => `${ESC}[${n}F`;
const cursorHorizontalPosition = n => `${ESC}[${n}G`;
const clearToEndOfScreen = `${ESC}[0J`;
const selectedItemColor = `${ESC}[100;97m`;
const resetColors = `${ESC}[0m`;
const suffix = suffix => string => string + suffix;
const prefix = prefix => string => prefix + string;
const editWithKeypress = cond([
[
propEq("name", "backspace"),
always(over(lensProp("substring"), slice(0, -1))),
],
[
propEq("name", "up"),
always(
over(
lensProp("selectedIndex"),
pipe(
flip(subtract)(1),
max(0),
),
),
),
],
[
propEq("name", "down"),
always(
over(
lens(s => [s.selectedIndex, s.eligibleFolders], assoc("selectedIndex")),
([selectedIndex, eligibleFolders]) =>
min(selectedIndex + 1, eligibleFolders.length - 1),
),
),
],
[
T,
pipe(
prop("string"),
suffix,
over(lensProp("substring")),
),
],
]);
const updateCurrentInput = keypress =>
State.modify(over(lensProp("currentInput"), editWithKeypress(keypress)))
.chain(State.get)
.map(({ currentInput, folders }) =>
currentInput.substring.length > 0
? folders.allFolders
.map(y => ({
...y,
substringStart: y.name
.toLowerCase()
.search(currentInput.substring.toLowerCase()),
}))
.filter(propSatisfies(lte(0))("substringStart"))
.sort(folderSubstringSort)
.slice(0, 4)
: [],
)
.chain(
pipe(
assocPath(["currentInput", "eligibleFolders"]),
State.modify,
),
)
.chain(
always(
State.modify(
over(
lens(
s => [
s.currentInput.selectedIndex,
s.currentInput.eligibleFolders.length - 1,
],
assocPath(["currentInput", "selectedIndex"]),
),
pipe(
apply(min),
max(0),
),
),
),
),
)
.chain(keyStrokeLoop);
const moveNoteBasedOnCurrentInput = State.get()
.map(
juxt([
pipe(
state => nth(state.currentNoteIndex)(state.notesToTriage),
prop("id"),
),
state =>
path(["name"])(
state.currentInput.eligibleFolders[state.currentInput.selectedIndex],
),
]),
)
.chain(
ifElse(args => isNil(args[1]), keyStrokeLoop, x =>
apply(moveNoteToFolder)(x)
.chain(State.get)
.chain(s =>
State.modify(
over(lensProp("notesToTriage"), remove(s.currentNoteIndex, 1)),
),
),
),
);
const activateSelf = always(activateApplication("Terminal"));
const showCurrentNote = always(
State.get()
.map(state => nth(state.currentNoteIndex)(state.notesToTriage))
.chain(
pipe(
prop("id"),
showNote,
),
)
.chain(activateSelf),
);
const deleteNoteWithConfirmation = always(
Output.putString(
`${cursorHorizontalPosition(
1,
)}${clearToEndOfScreen}Are you sure you want to delete this note? (y/N)`,
)
.chain(showCurrentNote)
.chain(Input.getKeypress)
.chain(
cond([
[
equals({
name: "y",
ctrl: false,
meta: false,
shift: false,
string: "y",
}),
always(
State.get()
.map(
pipe(
state => nth(state.currentNoteIndex)(state.notesToTriage),
prop("id"),
),
)
.chain(deleteNote)
.chain(State.get)
.chain(s =>
State.modify(
over(
lensProp("notesToTriage"),
remove(s.currentNoteIndex, 1),
),
),
),
),
],
[T, mainLoop],
]),
),
);
function folderNameLoop({ folderName, parentFolderName }) {
return Output.putString(
`${cursorHorizontalPosition(
1,
)}${clearToEndOfScreen}(${parentFolderName}) Name: ${folderName}`,
)
.chain(Input.getKeypress)
.chain(
cond([
[
equals({
name: "c",
ctrl: true,
meta: false,
shift: false,
string: "c",
}),
pipe(
always(0),
process.exit,
),
],
[
equals({
name: "return",
ctrl: false,
meta: false,
shift: false,
string: "\r",
}),
always(
createFolder({ folderName, parentFolderName }).chain(
always(
State.modify(
over(lensPath(["folders", "allFolders"]))(
concat([
{ name: folderName, containers: [parentFolderName] },
]),
),
),
),
),
),
],
[
equals({
name: "backspace",
ctrl: false,
meta: false,
shift: false,
string: "",
}),
() =>
folderNameLoop({
folderName: slice(0, -1)(folderName),
parentFolderName,
}),
],
[
T,
({ string }) =>
folderNameLoop({
folderName: folderName + string,
parentFolderName,
}),
],
]),
);
}
function createNewFolder() {
return Output.putString(
`${cursorHorizontalPosition(
1,
)}${clearToEndOfScreen}Where should this folder be created?\n1) Projects\n2) Areas\n3) Resources\n4) Archive${cursorUpLines(
4,
)}${cursorHorizontalPosition(38)}`,
)
.chain(Input.getKeypress)
.chain(
cond([
[
equals({
name: "c",
ctrl: true,
meta: false,
shift: false,
string: "c",
}),
pipe(
always(0),
process.exit,
),
],
[
equals({
name: "1",
ctrl: false,
meta: false,
shift: false,
string: "1",
}),
always(
folderNameLoop({ folderName: "", parentFolderName: "1 Projects" }),
),
],
[
equals({
name: "2",
ctrl: false,
meta: false,
shift: false,
string: "2",
}),
always(
folderNameLoop({ folderName: "", parentFolderName: "2 Areas" }),
),
],
[
equals({
name: "3",
ctrl: false,
meta: false,
shift: false,
string: "3",
}),
always(
folderNameLoop({ folderName: "", parentFolderName: "3 Resources" }),
),
],
[
equals({
name: "4",
ctrl: false,
meta: false,
shift: false,
string: "4",
}),
always(
folderNameLoop({ folderName: "", parentFolderName: "4 Archive" }),
),
],
[T, () => createNewFolder()],
]),
);
}
const nameAsListItem = pipe(
prop("name"),
prefix(" * "),
);
function keyStrokeLoop() {
return State.get()
.chain(({ currentInput }) =>
Output.putString(
`${cursorHorizontalPosition(
1,
)}${clearToEndOfScreen}Which folder should this note be moved to ? ${currentInput.substring.toString()}\n${currentInput.eligibleFolders
.map((folder, index) =>
index === currentInput.selectedIndex
? selectedItemColor + nameAsListItem(folder) + " " + resetColors
: nameAsListItem(folder),
)
.map(suffix(`\n`))
.join(
"",
)}(^c = close, ^d = delete, ^n = new folder, ^r = reshow, ^s = skip)${cursorUpLines(
currentInput.eligibleFolders.length + 1,
)}${cursorHorizontalPosition(45 + currentInput.substring.length)}`,
),
)
.chain(Input.getKeypress)
.chain(
cond([
[
equals({
name: "c",
ctrl: true,
meta: false,
shift: false,
string: "c",
}),
pipe(
always(0),
process.exit,
),
],
[
equals({
name: "s",
ctrl: true,
meta: false,
shift: false,
string: "s",
}),
always(State.modify(over(lensProp("currentNoteIndex"), add(1)))),
],
[
equals({
name: "r",
ctrl: true,
meta: false,
shift: false,
string: "r",
}),
mainLoop,
],
[
equals({
name: "d",
ctrl: true,
meta: false,
shift: false,
string: "d",
}),
deleteNoteWithConfirmation,
],
[
equals({
name: "n",
ctrl: true,
meta: false,
shift: false,
string: "n",
}),
createNewFolder,
],
[
equals({
name: "return",
ctrl: false,
meta: false,
shift: false,
string: "\r",
}),
always(moveNoteBasedOnCurrentInput),
],
[T, updateCurrentInput],
]),
);
}
function mainLoop() {
return showCurrentNote()
.chain(
always(State.modify(assocPath(["currentInput", "eligibleFolders"])([]))),
)
.chain(always(State.modify(assocPath(["currentInput", "substring"])(""))))
.chain(
always(State.modify(assocPath(["currentInput", "selectedIndex"])(0))),
)
.chain(keyStrokeLoop)
.chain(mainLoop);
}
const containersFromMapping = containerMap => folder =>
containerMap[folder]
? [containerMap[folder]].concat(
containersFromMapping(containerMap)(containerMap[folder]),
)
: [];
const addFoldersToState = getAllFoldersWithChildrenFolders()
.map(
reduce(
(containerMap, container) => ({
...containerMap,
...reduce(flip(assoc(__, container.name)))({})(container.folders),
}),
{},
),
)
.map(set(lensPath(["folders", "containerMap"])))
.chain(State.modify)
.chain(State.get)
.map(path(["folders", "containerMap"]))
.map(containerMap =>
map(folder => ({
name: folder,
containers: containersFromMapping(containerMap)(folder),
}))(Object.keys(containerMap)),
)
.map(set(lensPath(["folders", "allFolders"])))
.chain(State.modify);
const addNotesToTriageToState = getNotesOfFolder("Notes")
.map(sortBy(prop("modificationDate")))
.map(filter(note => note.name !== "Daily Focus"))
.chain(
pipe(
assoc("notesToTriage"),
State.modify,
),
);
export const application = openFolder("Notes")
.chain(always(addFoldersToState))
.chain(always(addNotesToTriageToState))
.chain(activateSelf)
.chain(mainLoop); | ],
[T, nameLengthDifference], |
User.js | const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const User = sequelize.define('user', {
id: { | primaryKey: true,
allowNull: false,
},
name: {
type: Sequelize.TEXT,
allowNull: false,
},
email: {
type: Sequelize.TEXT,
allowNull: false,
},
password: {
type: Sequelize.TEXT,
allowNull: false,
},
admin: {
type: Sequelize.BOOLEAN,
allowNull: true,
},
testUser: {
type: Sequelize.BOOLEAN,
allowNull: true,
},
});
module.exports = User; | type: Sequelize.INTEGER,
autoIncrement: true, |
membership.js | 'use strict'
const got = require('got')
const fs = require('fs-extra')
const execa = require('execa')
const diffparser = require('diffparser')
const { DateTime } = require('luxon')
module.exports = {
processMembershipRequests,
openMembershipRequests,
processPR,
getApprovals
}
const DEFAULTS = {
label: 'membership-request',
filename: 'README.md',
requiredApprovals: 2,
requiredOpenDays: 2
}
async function processMembershipRequests (client, options = {}) {
// Default options
const opts = {
...DEFAULTS,
...options
}
const [members, pulls] = await Promise.all([
// Get current team members
getTeamMembers(client, opts),
// Get open requests
openMembershipRequests(client, opts)
])
// Merge open pull requests
const pullsMerged = []
for (const pull of pulls) {
if (pull instanceof Error) {
// @TODO review on PR with required changes
console.error(pull)
continue
}
// Must be open for 48 hours and have 2 approvals
const openTime = DateTime.local().minus({ days: opts.requiredOpenDays }).startOf('day')
if (pull.created > openTime && pull.approvals < opts.requiredApprovals) {
// wait for approvals or open time
console.error(`Skipping ${pull.number}. ${pull.approvals} approvals. ${DateTime.local().diff(pull.created, 'days')}`)
continue
}
// Not already a member, add them before merging
if (!members.find(({ login }) => login === pull.username)) {
await addTeamMember(client, {
...opts,
username: pull.username
})
}
await mergePR(client, {
...opts,
pullNumber: pull.number
})
pullsMerged.push(pull)
}
// Sync to the members file
await syncList(members, opts)
return {
members,
pullsMerged
}
}
async function openMembershipRequests (client, options = {}) {
// Default options
const opts = {
...DEFAULTS,
...options
}
const resp = await client.issues.listForRepo({
owner: opts.owner,
repo: opts.repo,
state: 'open',
labels: opts.label
})
return (await Promise.all(resp.data.map(async (issue) => {
if (!issue.pull_request) {
// Convert issue to PR?
return
}
try {
const pull = await processPR(client, issue, opts)
return pull
} catch (e) {
// Return error for logging
return e
}
}))).filter((p) => p !== undefined)
}
async function processPR (client, pull, options = {}) {
const opts = {
...DEFAULTS,
...options
}
// Get diff should contain only file with a single change
const diffResp = await got(pull.diff_url || pull.pull_request.diff_url)
const diff = diffparser(diffResp.body)
// Should only have one changed file
if (diff.length > 1) {
throw new Error(`Too many changed files: ${diff.length}`)
}
let match
for (const file of diff) {
// no moving file
if (file.from !== file.to) {
throw new Error(`No moving files: ${file.from} ${file.to}`)
}
// wrong file
if (file.to !== opts.filename) {
throw new Error(`Wrong file changed: ${file.to}, expected ${opts.filename}`)
}
// If there are multiple chunks that means a change to multiple
// parts of the file, it should just be one line
if (file.chunks.length > 1) {
throw new Error(`Too many changes: ${file.chunks.length}`)
}
// Find line which is a single line addition
// error on deletions of improperly formated changes
for (const chunk of file.chunks) {
for (const change of chunk.changes) {
if (change.type === 'normal') {
continue
}
if (change.type === 'del') {
throw new Error(`Do not remove lines: ${change.content}`)
}
// If we have already matched a line error with too many lines changed
if (match && change.type === 'add') {
throw new Error('Too many lines added, only add one name at a time.')
}
// Check format
match = change.content.match(/^\+- \[@(.+)\]\(https:\/\/github\.com\/(.+)\) - (.+)$/)
if (!match) {
throw new Error(`Invalid format: ${change.content}`)
}
if (match[1] !== match[2]) {
throw new Error(`Username should match github url: ${match[1]} !== ${match[2]}`)
}
if (match[1] !== pull.user.login) {
throw new Error(`Username should match author of PR: ${match[1]} !== ${pull.user.login}`)
}
}
}
}
return {
number: pull.number,
title: pull.title,
username: match[1],
displayName: match[3],
body: pull.body,
approvals: await getApprovals(client, pull.number, opts),
authorAssociation: pull.author_association,
created: DateTime.fromISO(pull.created_at)
}
}
async function getApprovals (client, pullNumber, options = {}) {
const opts = {
...DEFAULTS,
...options
}
// Get reviewer data
const reviewsResp = await client.pulls.listReviews({
owner: opts.owner,
repo: opts.repo,
pull_number: pullNumber
})
let approvals = 0
for (const review of reviewsResp.data) {
// Only care about member reviews
if (review.author_association !== 'MEMBER') {
continue
}
// Error if pending review changes
if (review.state === 'REQUEST_CHANGES') {
throw new Error(`Request for changes: ${review.body}`)
}
++approvals
}
return approvals
}
async function getTeamMembers (client, options = {}) {
const opts = {
...DEFAULTS,
...options
}
try {
const resp = await client.teams.listMembersInOrg({
org: opts.owner,
team_slug: opts.team
})
return Promise.all(resp.data.sort((a, b) => {
return a.login > b.login ? 1 : -1
}).map(async (u) => {
const resp = await client.users.getByUsername({
username: u.login
})
return {
login: resp.data.login,
name: resp.data.name,
url: resp.data.html_url
}
}))
} catch (e) {
throw new Error(`Failed to get team members: ${e.message}`)
}
}
async function addTeamMember (client, options = {}) {
const opts = {
...DEFAULTS,
...options
}
try {
const resp = await client.teams.addOrUpdateMembershipInOrg({
org: opts.owner,
team_slug: opts.team,
username: opts.username
})
return resp.data
} catch (e) {
throw new Error(`Failed to add team member: ${e.message}`)
}
}
async function mergePR (client, options = {}) {
const opts = {
...DEFAULTS,
...options
}
try {
const resp = await client.pulls.merge({
owner: opts.owner,
repo: opts.repo,
pull_number: opts.pullNumber,
merge_method: 'rebase'
})
return resp.data
} catch (e) {
throw new Error(`Failed to merge PR: ${e.message}`)
}
}
async function syncList (members, options = {}) {
const opts = {
...DEFAULTS,
...options
}
const prefix = `<!-- pkgjs-team-start(${opts.team}) -->`
const suffix = `<!-- pkgjs-team-end(${opts.team}) -->`
const sectionRe = new RegExp(`${escape(prefix)}[\\s\\S]+?${escape(suffix)}`, 'mg')
// File to replace in
let membersFile = await fs.readFile(opts.filename, 'utf8')
// Members list
let list = members.reduce((str, member) => {
str += '\n' + getContact(member)
return str
}, '')
list = `${prefix}\n${list}\n\n${suffix}`
membersFile = membersFile.replace(sectionRe, list)
await fs.writeFile(opts.filename, membersFile)
// await execa('git', ['add', opts.filename])
// await execa('git', ['commit', '--message', `chore (members): sync ${opts.team}`])
// await execa('git', ['push', 'origin', 'master'])
}
function getContact ({ login, url, name }) {
if (!name) return `- [@${login}](${url})`
return `- [@${login}](${url}) - ${name}`
}
function escape (str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
} | ||
router.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 denco provides fast URL router.
package cobweb
import (
"fmt"
"sort"
"strings"
)
const (
// ParamCharacter is a special character for path parameter.
ParamCharacter = ':'
// WildcardCharacter is a special character for wildcard path parameter.
WildcardCharacter = '*'
// TerminationCharacter is a special character for end of path.
TerminationCharacter = '#'
// MaxSize is max size of records and internal slice.
MaxSize = (1 << 22) - 1
)
// Router represents a URL router.
type Router struct {
// SizeHint expects the maximum number of path parameters in records to Build.
// SizeHint will be used to determine the capacity of the memory to allocate.
// By default, SizeHint will be determined from given records to Build.
SizeHint int
static map[string]interface{}
param *doubleArray
}
// New returns a new Router.
func NewRouter() *Router {
return &Router{
SizeHint: -1,
static: make(map[string]interface{}),
param: newDoubleArray(),
}
}
// Lookup returns data and path parameters that associated with path.
// params is a slice of the Param that arranged in the order in which parameters appeared.
// e.g. when built routing path is "/path/to/:id/:name" and given path is "/path/to/1/alice". params order is [{"id": "1"}, {"name": "alice"}], not [{"name": "alice"}, {"id": "1"}].
func (rt *Router) Lookup(path string) (data interface{}, params Params, found bool) {
if data, found := rt.static[path]; found {
return data, nil, true
}
if len(rt.param.node) == 1 {
return nil, nil, false
}
nd, params, found := rt.param.lookup(path, make([]Param, 0, rt.SizeHint), 1)
if !found {
return nil, nil, false
}
for i := 0; i < len(params); i++ {
params[i].Name = nd.paramNames[i]
}
return nd.data, params, true
}
// Build builds URL router from records.
func (rt *Router) Build(records []Record) error {
statics, params := makeRecords(records)
if len(params) > MaxSize {
return fmt.Errorf("denco: too many records")
}
if rt.SizeHint < 0 {
rt.SizeHint = 0
for _, p := range params {
size := 0
for _, k := range p.Key {
if k == ParamCharacter || k == WildcardCharacter {
size++
}
}
if size > rt.SizeHint {
rt.SizeHint = size
}
}
}
for _, r := range statics {
rt.static[r.Key] = r.Value
}
if err := rt.param.build(params, 1, 0, make(map[int]struct{})); err != nil {
return err
}
return nil
}
// Param represents name and value of path parameter.
type Param struct {
Name string
Value string
}
// Params represents the name and value of path parameters.
type Params []Param
// Get gets the first value associated with the given name.
// If there are no values associated with the key, Get returns "".
func (ps Params) Get(name string) string {
for _, p := range ps {
if p.Name == name {
return p.Value
}
}
return ""
}
type doubleArray struct {
bc []baseCheck
node []*node
}
func newDoubleArray() *doubleArray {
return &doubleArray{
bc: []baseCheck{0},
node: []*node{nil}, // A start index is adjusting to 1 because 0 will be used as a mark of non-existent node.
}
}
// baseCheck contains BASE, CHECK and Extra flags.
// From the top, 22bits of BASE, 2bits of Extra flags and 8bits of CHECK.
//
// BASE (22bit) | Extra flags (2bit) | CHECK (8bit)
// |----------------------|--|--------|
// 32 10 8 0
type baseCheck uint32
func (bc baseCheck) Base() int {
return int(bc >> 10)
}
func (bc *baseCheck) SetBase(base int) {
*bc |= baseCheck(base) << 10
}
func (bc baseCheck) Check() byte {
return byte(bc)
}
func (bc *baseCheck) SetCheck(check byte) {
*bc |= baseCheck(check)
}
func (bc baseCheck) IsEmpty() bool {
return bc&0xfffffcff == 0
}
func (bc baseCheck) IsSingleParam() bool {
return bc¶mTypeSingle == paramTypeSingle
}
func (bc baseCheck) IsWildcardParam() bool {
return bc¶mTypeWildcard == paramTypeWildcard
}
func (bc baseCheck) IsAnyParam() bool {
return bc¶mTypeAny != 0
}
func (bc *baseCheck) SetSingleParam() {
*bc |= (1 << 8)
}
func (bc *baseCheck) SetWildcardParam() {
*bc |= (1 << 9)
}
const (
paramTypeSingle = 0x0100
paramTypeWildcard = 0x0200
paramTypeAny = 0x0300
)
func (da *doubleArray) lookup(path string, params []Param, idx int) (*node, []Param, bool) {
indices := make([]uint64, 0, 1)
for i := 0; i < len(path); i++ {
if da.bc[idx].IsAnyParam() {
indices = append(indices, (uint64(i)<<32)|(uint64(idx)&0xffffffff))
}
c := path[i]
if idx = nextIndex(da.bc[idx].Base(), c); idx >= len(da.bc) || da.bc[idx].Check() != c {
goto BACKTRACKING
}
}
if next := nextIndex(da.bc[idx].Base(), TerminationCharacter); next < len(da.bc) && da.bc[next].Check() == TerminationCharacter {
return da.node[da.bc[next].Base()], params, true
}
if len(indices) > 0 {
goto BACKTRACKING
}
return nil, nil, false
BACKTRACKING:
for j := len(indices) - 1; j >= 0; j-- {
i, idx := int(indices[j]>>32), int(indices[j]&0xffffffff)
if da.bc[idx].IsSingleParam() {
idx := nextIndex(da.bc[idx].Base(), ParamCharacter)
if idx >= len(da.bc) {
break
}
next := NextSeparator(path, i)
params := append(params, Param{Value: path[i:next]})
if nd, params, found := da.lookup(path[next:], params, idx); found {
return nd, params, true
}
}
if da.bc[idx].IsWildcardParam() {
idx := nextIndex(da.bc[idx].Base(), WildcardCharacter)
params := append(params, Param{Value: path[i:]})
return da.node[da.bc[idx].Base()], params, true
}
}
return nil, nil, false
}
// build builds double-array from records.
func (da *doubleArray) build(srcs []*record, idx, depth int, usedBase map[int]struct{}) error {
sort.Stable(recordSlice(srcs))
base, siblings, leaf, err := da.arrange(srcs, idx, depth, usedBase)
if err != nil {
return err
}
if leaf != nil {
nd, err := makeNode(leaf)
if err != nil {
return err
}
da.bc[idx].SetBase(len(da.node))
da.node = append(da.node, nd)
}
for _, sib := range siblings {
da.setCheck(nextIndex(base, sib.c), sib.c)
}
for _, sib := range siblings { | for _, r := range records {
next := NextSeparator(r.Key, depth+1)
name := r.Key[depth+1 : next]
r.paramNames = append(r.paramNames, name)
r.Key = r.Key[next:]
}
da.bc[idx].SetSingleParam()
if err := da.build(records, nextIndex(base, sib.c), 0, usedBase); err != nil {
return err
}
case WildcardCharacter:
r := records[0]
name := r.Key[depth+1 : len(r.Key)-1]
r.paramNames = append(r.paramNames, name)
r.Key = ""
da.bc[idx].SetWildcardParam()
if err := da.build(records, nextIndex(base, sib.c), 0, usedBase); err != nil {
return err
}
default:
if err := da.build(records, nextIndex(base, sib.c), depth+1, usedBase); err != nil {
return err
}
}
}
return nil
}
// setBase sets BASE.
func (da *doubleArray) setBase(i, base int) {
da.bc[i].SetBase(base)
}
// setCheck sets CHECK.
func (da *doubleArray) setCheck(i int, check byte) {
da.bc[i].SetCheck(check)
}
// findEmptyIndex returns an index of unused BASE/CHECK node.
func (da *doubleArray) findEmptyIndex(start int) int {
i := start
for ; i < len(da.bc); i++ {
if da.bc[i].IsEmpty() {
break
}
}
return i
}
// findBase returns good BASE.
func (da *doubleArray) findBase(siblings []sibling, start int, usedBase map[int]struct{}) (base int) {
for idx, firstChar := start+1, siblings[0].c; ; idx = da.findEmptyIndex(idx + 1) {
base = nextIndex(idx, firstChar)
if _, used := usedBase[base]; used {
continue
}
i := 0
for ; i < len(siblings); i++ {
next := nextIndex(base, siblings[i].c)
if len(da.bc) <= next {
da.bc = append(da.bc, make([]baseCheck, next-len(da.bc)+1)...)
}
if !da.bc[next].IsEmpty() {
break
}
}
if i == len(siblings) {
break
}
}
usedBase[base] = struct{}{}
return base
}
func (da *doubleArray) arrange(records []*record, idx, depth int, usedBase map[int]struct{}) (base int, siblings []sibling, leaf *record, err error) {
siblings, leaf, err = makeSiblings(records, depth)
if err != nil {
return -1, nil, nil, err
}
if len(siblings) < 1 {
return -1, nil, leaf, nil
}
base = da.findBase(siblings, idx, usedBase)
if base > MaxSize {
return -1, nil, nil, fmt.Errorf("denco: too many elements of internal slice")
}
da.setBase(idx, base)
return base, siblings, leaf, err
}
// node represents a node of Double-Array.
type node struct {
data interface{}
// Names of path parameters.
paramNames []string
}
// makeNode returns a new node from record.
func makeNode(r *record) (*node, error) {
dups := make(map[string]bool)
for _, name := range r.paramNames {
if dups[name] {
return nil, fmt.Errorf("denco: path parameter `%v' is duplicated in the key `%v'", name, r.Key)
}
dups[name] = true
}
return &node{data: r.Value, paramNames: r.paramNames}, nil
}
// sibling represents an intermediate data of build for Double-Array.
type sibling struct {
// An index of start of duplicated characters.
start int
// An index of end of duplicated characters.
end int
// A character of sibling.
c byte
}
// nextIndex returns a next index of array of BASE/CHECK.
func nextIndex(base int, c byte) int {
return base ^ int(c)
}
// makeSiblings returns slice of sibling.
func makeSiblings(records []*record, depth int) (sib []sibling, leaf *record, err error) {
var (
pc byte
n int
)
for i, r := range records {
if len(r.Key) <= depth {
leaf = r
continue
}
c := r.Key[depth]
switch {
case pc < c:
sib = append(sib, sibling{start: i, c: c})
case pc == c:
continue
default:
return nil, nil, fmt.Errorf("denco: BUG: routing table hasn't been sorted")
}
if n > 0 {
sib[n-1].end = i
}
pc = c
n++
}
if n == 0 {
return nil, leaf, nil
}
sib[n-1].end = len(records)
return sib, leaf, nil
}
// Record represents a record data for router construction.
type Record struct {
// Key for router construction.
Key string
// Result value for Key.
Value interface{}
}
// NewRecord returns a new Record.
func NewRecord(key string, value interface{}) Record {
return Record{
Key: key,
Value: value,
}
}
// record represents a record that use to build the Double-Array.
type record struct {
Record
paramNames []string
}
// makeRecords returns the records that use to build Double-Arrays.
func makeRecords(srcs []Record) (statics, params []*record) {
spChars := string([]byte{ParamCharacter, WildcardCharacter})
termChar := string(TerminationCharacter)
for _, r := range srcs {
if strings.ContainsAny(r.Key, spChars) {
r.Key += termChar
params = append(params, &record{Record: r})
} else {
statics = append(statics, &record{Record: r})
}
}
return statics, params
}
// recordSlice represents a slice of Record for sort and implements the sort.Interface.
type recordSlice []*record
// Len implements the sort.Interface.Len.
func (rs recordSlice) Len() int {
return len(rs)
}
// Less implements the sort.Interface.Less.
func (rs recordSlice) Less(i, j int) bool {
return rs[i].Key < rs[j].Key
}
// Swap implements the sort.Interface.Swap.
func (rs recordSlice) Swap(i, j int) {
rs[i], rs[j] = rs[j], rs[i]
} | records := srcs[sib.start:sib.end]
switch sib.c {
case ParamCharacter: |
train.py | import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim
from TextDataset import TextDataset
from Model.BasicModel.TextCLRModel import TextCLRModel
from Model.BasicModel.TextSLBModel import TextSLBModel
from Model.BasicModel.TextNMTModel import TextNMTModel
from Model.BasicModel.TextDSMModel import TextDSMModel
from Model.Transformer.Transformer import Transformer
from Vectorizer.CLRVectorizer import CLRVectorizer
from Vectorizer.SLBVectorizer import SLBVectorizer
from Vectorizer.NMTVectorizer import NMTVectorizer
from Vectorizer.DSMVectorizer import DSMVectorizer
from Utils.Data import read_json_dataset
from ModelTrainer import ModelTrainer
from Utils.Config import Config
import json
import sys
import os
def get_data_loaders(args, dataset):
'''通过数据集创建用于训练,验证和测试的数据批生成器'''
if not os.path.exists(args.save_folder):
os.makedirs(args.save_folder)
if os.path.exists(args.vectorizer_file):
parameters = {'dataset': dataset,
'split_ratio': args.split_ratio,
'max_seq_length': args.max_seq_length,
'task': args.task,
'vectorizer_file': args.vectorizer_file}
dataset = TextDataset.dataset_load_vectorizer(**parameters)
else:
parameters = {'dataset': dataset,
'split_ratio': args.split_ratio,
'max_seq_length': args.max_seq_length,
'task': args.task,
'cutoff': args.cutoff}
dataset = TextDataset.dataset_make_vectorizer(**parameters)
dataset.save_vectorizer(args.vectorizer_file)
dataset.set_split('train')
train_data_loader = DataLoader(dataset=dataset, batch_size=args.batch_size,
shuffle=True, drop_last=True)
dataset.set_split('val')
val_data_loader = DataLoader(dataset=dataset, batch_size=args.batch_size,
shuffle=True, drop_last=True)
dataset.set_split('test')
test_data_loader = DataLoader(dataset=dataset, batch_size=args.batch_size,
shuffle=True, drop_last=True)
data_loaders = (train_data_loader, val_data_loader, test_data_loader)
return data_loaders
def get_task_model(args, vectorizer):
'''根据任务类型获取用于训练的模型类型'''
model = None
if args.task == 'classification':
if args.model_name == 'TextCLRModel':
model = TextCLRModel(
num_embeddings=len(vectorizer.source_vocab),
embedding_dim=args.embedding_size,
rnn_hidden_size=args.rnn_hidden_size,
num_classes=len(vectorizer.label_vocab),
padding_idx=vectorizer.source_vocab.mask_index,
batch_first=True)
if args.task == 'labeling':
if args.model_name == 'TextSLBModel':
model = TextSLBModel(
num_embeddings=len(vectorizer.source_vocab),
embedding_dim=args.embedding_size,
rnn_hidden_size=args.rnn_hidden_size,
padding_idx=vectorizer.source_vocab.mask_index,
batch_first=True)
if args.task == 'matching':
if args.model_name == 'TextDSMModel':
model = TextDSMModel(
num_embeddings1=len(vectorizer.source_vocab),
num_embeddings2=len(vectorizer.target_vocab),
embedding_dim=args.embedding_size,
rnn_hidden_size=args.rnn_hidden_size,
padding_idx=vectorizer.source_vocab.mask_index,
batch_first=True)
if args.task == 'translation':
if args.model_name == 'Transformer':
model = Transformer(
source_vocab_size=len(vectorizer.source_vocab),
target_vocab_size=len(vectorizer.target_vocab),
source_embed_dim=args.source_embed_dim,
target_embed_dim=args.target_embed_dim,
encoder_n_heads=args.encoder_n_heads,
decoder_n_heads=args.decoder_n_heads,
encoder_hid_dim=args.encoder_hid_dim,
decoder_hid_dim=args.decoder_hid_dim,
encoder_n_layers=args.encoder_n_layers,
decoder_n_layers=args.decoder_n_layers,
encoder_max_seq_len=args.max_seq_length,
decoder_max_seq_len=args.max_seq_length
)
if args.model_name == 'TextNMTModel':
model = TextNMTModel(
source_num_embeddings=len(vectorizer.source_vocab),
source_embedding_size=args.source_embedding_size,
target_num_embeddings=len(vectorizer.target_vocab),
target_embedding_size=args.target_embedding_size,
encoding_size=args.encoding_size)
return model
def get_optimizer(args, model):
'''获取想要使用的优化器'''
if args.optimizer == 'adam':
return optim.Adam(model.parameters(), lr=args.learning_rate)
def get_loss_func(args):
'''根据任务类型获取损失函数'''
if args.task == 'classification':
return nn.CrossEntropyLoss()
if args.task == 'matching':
return nn.CrossEntropyLoss()
if args.task == 'labeling':
return sequence_loss
if args.task == 'translation':
return sequence_loss
def sequence_loss(pred, target, mask_index):
'''用于计算序列模型的损失函数'''
pred = pred.contiguous().view(-1, pred.size(2))
target = target.contiguous().view(-1)
return F.cross_entropy(pred, target, ignore_index=mask_index)
def get_vectorizer(args):
'''根据任务获取矢量化器'''
with open(args.vectorizer_file, "r") as fp:
if args.task == 'classification':
return CLRVectorizer.from_serializable(json.load(fp))
if args.task == 'matching':
return DSMVectorizer.from_serializable(json.load(fp))
if args.task == 'labeling':
return GENVectorizer.from_serializable(json.load(fp))
if args.task == 'translation': | if __name__ == '__main__':
# 获取配置文件信息
config_filename = sys.argv[1]
config = Config.from_config_json(config_filename)
args = config.args
# 获取数据集
dataset = read_json_dataset(args.data_filepath, args.max_seq_length)
# 获取数据批生成器
data_loaders = get_data_loaders(args, dataset)
# 获取模型
vectorizer = get_vectorizer(args)
model = get_task_model(args, vectorizer)
# 获取优化器
optimizer = get_optimizer(args, model)
# 获取损失函数
loss_func = get_loss_func(args)
# 获取训练器
model_trainer = ModelTrainer(
args, data_loaders, model, optimizer, loss_func)
# 训练模型
model_trainer.train_val_test_model() | return NMTVectorizer.from_serializable(json.load(fp))
|
branch.go | package git
import (
"fmt"
"regexp"
"strings"
)
// FormatAsValidRef transforms `s` to a string that is a valid refname
//
// A reference is used in git to specify branches and tags. The following rules
// must be followed when is comes to naming references:
// https://git-scm.com/docs/git-check-ref-format
func FormatAsValidRef(s string) string {
// Remove everything inside () and [] to remove tags.
innerValRe, _ := regexp.Compile(`([\(\[]).*?([\)\]])`)
s = innerValRe.ReplaceAllString(s, "")
// Remove all non alpha numeric chars expect whitespace.
special, _ := regexp.Compile(`[^a-zA-Z\d\s]`)
s = special.ReplaceAllString(s, " ")
// Remove leading and trailing whitespace.
s = strings.TrimSpace(s)
s = strings.ToLower(s)
// Remove spaces with single space.
d, _ := regexp.Compile(`\s\s+`)
s = d.ReplaceAllString(s, " ")
// Split the string on the spaces.
parts := strings.Split(s, " ")
cutoff := GetLengthWithUpperbound(parts, 12)
// Return hyphenated string
return strings.Join(parts[:cutoff], "-")
}
func | (s []string, m int) int {
l := len(s)
if l > m {
return m
}
return l
}
func GetBranchName(base, key, title string) string {
//TODO: should we check key and base here to also valid for refname?
ref := FormatAsValidRef(title)
return fmt.Sprintf("%s/%s/%s", base, key, ref)
}
| GetLengthWithUpperbound |
clipboard.rs | // Copyright 2019 The Druid 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. | /// A handle to the system clipboard.
///
/// To get access to the global clipboard, call [`Application::clipboard()`].
///
///
/// # Working with text
///
/// Copying and pasting text is simple, using [`Clipboard::put_string`] and
/// [`Clipboard::get_string`]. If this is all you need, you're in luck.
///
/// # Advanced usage
///
/// When working with data more complicated than plaintext, you will generally
/// want to make that data available in multiple formats.
///
/// For instance, if you are writing an image editor, you may have a preferred
/// private format, that preserves metadata or layer information; but in order
/// to interoperate with your user's other programs, you might also make your
/// data available as an SVG, for other editors, and a bitmap image for applications
/// that can accept general image data.
///
/// ## `FormatId`entifiers
///
/// In order for other applications to find data we put on the clipboard,
/// (and for us to use data from other applications) we need to use agreed-upon
/// identifiers for our data types. On macOS, these should be
/// [`Universal Type Identifier`]s; on other platforms they appear to be
/// mostly [MIME types]. Several common types are exposed as constants on
/// [`ClipboardFormat`], these `const`s are set per-platform.
///
/// When defining custom formats, you should use the correct identifier for
/// the current platform.
///
/// ## Setting custom data
///
/// To put custom data on the clipboard, you create a [`ClipboardFormat`] for
/// each type of data you support. You are responsible for ensuring that the
/// data is already correctly serialized.
///
///
/// ### `ClipboardFormat` for text
///
/// If you wish to put text on the clipboard in addition to other formats,
/// take special care to use `ClipboardFormat::TEXT` as the [`FormatId`]. On
/// windows, we treat this identifier specially, and make sure the data is
/// encoded as a wide string; all other data going into and out of the
/// clipboard is treated as an array of bytes.
///
/// # Examples
///
/// ## Getting and setting text:
///
/// ```no_run
/// use druid_shell::{Application, Clipboard};
///
/// let mut clipboard = Application::global().clipboard();
/// clipboard.put_string("watch it there pal");
/// if let Some(contents) = clipboard.get_string() {
/// assert_eq!("what it there pal", contents.as_str());
/// }
///
/// ```
///
/// ## Copying multi-format data
///
/// ```no_run
/// use druid_shell::{Application, Clipboard, ClipboardFormat};
///
/// let mut clipboard = Application::global().clipboard();
///
/// let custom_type_id = "io.xieditor.path-clipboard-type";
///
/// let formats = [
/// ClipboardFormat::new(custom_type_id, make_custom_data()),
/// ClipboardFormat::new(ClipboardFormat::SVG, make_svg_data()),
/// ClipboardFormat::new(ClipboardFormat::PDF, make_pdf_data()),
/// ];
///
/// clipboard.put_formats(&formats);
///
/// # fn make_custom_data() -> Vec<u8> { unimplemented!() }
/// # fn make_svg_data() -> Vec<u8> { unimplemented!() }
/// # fn make_pdf_data() -> Vec<u8> { unimplemented!() }
/// ```
/// ## Supporting multi-format paste
///
/// ```no_run
/// use druid_shell::{Application, Clipboard, ClipboardFormat};
///
/// let clipboard = Application::global().clipboard();
///
/// let custom_type_id = "io.xieditor.path-clipboard-type";
/// let supported_types = &[custom_type_id, ClipboardFormat::SVG, ClipboardFormat::PDF];
/// let best_available_type = clipboard.preferred_format(supported_types);
///
/// if let Some(format) = best_available_type {
/// let data = clipboard.get_format(format).expect("I promise not to unwrap in production");
/// do_something_with_data(format, data)
/// }
///
/// # fn do_something_with_data(_: &str, _: Vec<u8>) {}
/// ```
///
/// [`Application::clipboard()`]: struct.Application.html#method.clipboard
/// [`Clipboard::put_string`]: struct.Clipboard.html#method.put_string
/// [`Clipboard::get_string`]: struct.Clipboard.html#method.get_string
/// [`FormatId`]: type.FormatId.html
/// [`Universal Type Identifier`]: https://escapetech.eu/manuals/qdrop/uti.html
/// [MIME types]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
/// [`ClipboardFormat`]: struct.ClipboardFormat.html
#[derive(Debug, Clone)]
pub struct Clipboard(platform::Clipboard);
impl Clipboard {
/// Put a string onto the system clipboard.
pub fn put_string(&mut self, s: impl AsRef<str>) {
self.0.put_string(s);
}
/// Put multi-format data on the system clipboard.
pub fn put_formats(&mut self, formats: &[ClipboardFormat]) {
self.0.put_formats(formats)
}
/// Get a string from the system clipboard, if one is available.
pub fn get_string(&self) -> Option<String> {
self.0.get_string()
}
/// Given a list of supported clipboard types, returns the supported type which has
/// highest priority on the system clipboard, or `None` if no types are supported.
pub fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> {
self.0.preferred_format(formats)
}
/// Return data in a given format, if available.
///
/// It is recommended that the [`FormatId`] argument be a format returned by
/// [`Clipboard::preferred_format`].
///
/// [`Clipboard::preferred_format`]: struct.Clipboard.html#method.preferred_format
/// [`FormatId`]: type.FormatId.html
pub fn get_format(&self, format: FormatId) -> Option<Vec<u8>> {
self.0.get_format(format)
}
/// For debugging: print the resolved identifiers for each type currently
/// on the clipboard.
#[doc(hidden)]
pub fn available_type_names(&self) -> Vec<String> {
self.0.available_type_names()
}
}
/// A type identifer for the system clipboard.
///
/// These should be [`UTI` strings] on macOS, and (by convention?) [MIME types] elsewhere.
///
/// [`UTI` strings]: https://escapetech.eu/manuals/qdrop/uti.html
/// [MIME types]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
pub type FormatId = &'static str;
/// Data coupled with a type identifier.
#[derive(Debug, Clone)]
pub struct ClipboardFormat {
pub(crate) identifier: FormatId,
pub(crate) data: Vec<u8>,
}
impl ClipboardFormat {
/// Create a new `ClipboardFormat` with the given `FormatId` and bytes.
///
/// You are responsible for ensuring that this data can be interpreted
/// as the provided format.
pub fn new(identifier: FormatId, data: impl Into<Vec<u8>>) -> Self {
let data = data.into();
ClipboardFormat { identifier, data }
}
}
impl From<String> for ClipboardFormat {
fn from(src: String) -> ClipboardFormat {
let data = src.into_bytes();
ClipboardFormat::new(ClipboardFormat::TEXT, data)
}
}
impl From<&str> for ClipboardFormat {
fn from(src: &str) -> ClipboardFormat {
src.to_string().into()
}
}
impl From<platform::Clipboard> for Clipboard {
fn from(src: platform::Clipboard) -> Clipboard {
Clipboard(src)
}
}
cfg_if::cfg_if! {
if #[cfg(target_os = "macos")] {
impl ClipboardFormat {
pub const PDF: &'static str = "com.adobe.pdf";
pub const TEXT: &'static str = "public.utf8-plain-text";
pub const SVG: &'static str = "public.svg-image";
}
} else {
impl ClipboardFormat {
cfg_if::cfg_if! {
if #[cfg(target_os = "linux")] {
// trial and error; this is the most supported string type for gtk?
pub const TEXT: &'static str = "UTF8_STRING";
} else {
pub const TEXT: &'static str = "text/plain";
}
}
pub const PDF: &'static str = "application/pdf";
pub const SVG: &'static str = "image/svg+xml";
}
}
} |
//! Interacting with the system pasteboard/clipboard.
pub use crate::platform::clipboard as platform;
|
message_withdraw_test.go | package types_test
import (
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/stafihub/stafihub/testutil/sample"
"github.com/stafihub/stafihub/x/mining/types"
"github.com/stretchr/testify/require"
)
func TestMsgWithdraw_ValidateBasic(t *testing.T) | {
tests := []struct {
name string
msg types.MsgWithdraw
err error
}{
{
name: "invalid address",
msg: types.MsgWithdraw{
Creator: "invalid_address",
WithdrawAmount: sdk.NewInt(10),
},
err: sdkerrors.ErrInvalidAddress,
}, {
name: "valid address",
msg: types.MsgWithdraw{
Creator: sample.AccAddress(),
WithdrawAmount: sdk.NewInt(10),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.msg.ValidateBasic()
if tt.err != nil {
require.ErrorIs(t, err, tt.err)
return
}
require.NoError(t, err)
})
}
} |
|
roulette.py | import logging
from sqlalchemy import Column, INT
from sqlalchemy_utc import UtcDateTime
from pajbot import utils
from pajbot.managers.db import Base
log = logging.getLogger(__name__)
class Roulette(Base):
__tablename__ = "roulette"
id = Column(INT, primary_key=True)
user_id = Column(INT, index=True, nullable=False)
created_at = Column(UtcDateTime(), nullable=False) | points = Column(INT, nullable=False)
def __init__(self, user_id, points):
self.user_id = user_id
self.created_at = utils.now()
self.points = points | |
model_additional_properties_any_type.go | /*
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package petstore
| "encoding/json"
)
// AdditionalPropertiesAnyType struct for AdditionalPropertiesAnyType
type AdditionalPropertiesAnyType struct {
Name *string `json:"name,omitempty"`
}
// NewAdditionalPropertiesAnyType instantiates a new AdditionalPropertiesAnyType object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewAdditionalPropertiesAnyType() *AdditionalPropertiesAnyType {
this := AdditionalPropertiesAnyType{}
return &this
}
// NewAdditionalPropertiesAnyTypeWithDefaults instantiates a new AdditionalPropertiesAnyType object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewAdditionalPropertiesAnyTypeWithDefaults() *AdditionalPropertiesAnyType {
this := AdditionalPropertiesAnyType{}
return &this
}
// GetName returns the Name field value if set, zero value otherwise.
func (o *AdditionalPropertiesAnyType) GetName() string {
if o == nil || o.Name == nil {
var ret string
return ret
}
return *o.Name
}
// GetNameOk returns a tuple with the Name field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *AdditionalPropertiesAnyType) GetNameOk() (*string, bool) {
if o == nil || o.Name == nil {
return nil, false
}
return o.Name, true
}
// HasName returns a boolean if a field has been set.
func (o *AdditionalPropertiesAnyType) HasName() bool {
if o != nil && o.Name != nil {
return true
}
return false
}
// SetName gets a reference to the given string and assigns it to the Name field.
func (o *AdditionalPropertiesAnyType) SetName(v string) {
o.Name = &v
}
func (o AdditionalPropertiesAnyType) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.Name != nil {
toSerialize["name"] = o.Name
}
return json.Marshal(toSerialize)
}
type NullableAdditionalPropertiesAnyType struct {
value *AdditionalPropertiesAnyType
isSet bool
}
func (v NullableAdditionalPropertiesAnyType) Get() *AdditionalPropertiesAnyType {
return v.value
}
func (v *NullableAdditionalPropertiesAnyType) Set(val *AdditionalPropertiesAnyType) {
v.value = val
v.isSet = true
}
func (v NullableAdditionalPropertiesAnyType) IsSet() bool {
return v.isSet
}
func (v *NullableAdditionalPropertiesAnyType) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableAdditionalPropertiesAnyType(val *AdditionalPropertiesAnyType) *NullableAdditionalPropertiesAnyType {
return &NullableAdditionalPropertiesAnyType{value: val, isSet: true}
}
func (v NullableAdditionalPropertiesAnyType) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableAdditionalPropertiesAnyType) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | import ( |
noop_waker.rs | //! Utilities for creating zero-cost wakers that don't do anything.
use core::ptr::null;
use core::task::{RawWaker, RawWakerVTable, Waker};
unsafe fn noop_clone(_data: *const ()) -> RawWaker {
noop_raw_waker()
}
unsafe fn noop(_data: *const ()) {}
const NOOP_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(noop_clone, noop, noop, noop);
const fn noop_raw_waker() -> RawWaker {
RawWaker::new(null(), &NOOP_WAKER_VTABLE)
}
/// Create a new [`Waker`] which does
/// nothing when `wake()` is called on it.
///
/// # Examples
///
/// ```
/// use futures::task::noop_waker;
/// let waker = noop_waker();
/// waker.wake();
/// ```
#[inline]
pub fn noop_waker() -> Waker {
// FIXME: Since 1.46.0 we can use transmute in consts, allowing this function to be const.
unsafe { Waker::from_raw(noop_raw_waker()) }
}
/// Get a static reference to a [`Waker`] which
/// does nothing when `wake()` is called on it.
///
/// # Examples
///
/// ```
/// use futures::task::noop_waker_ref;
/// let waker = noop_waker_ref();
/// waker.wake_by_ref();
/// ```
#[inline]
pub fn noop_waker_ref() -> &'static Waker {
struct SyncRawWaker(RawWaker);
unsafe impl Sync for SyncRawWaker {}
static NOOP_WAKER_INSTANCE: SyncRawWaker = SyncRawWaker(noop_raw_waker());
// SAFETY: `Waker` is #[repr(transparent)] over its `RawWaker`.
unsafe { &*(&NOOP_WAKER_INSTANCE.0 as *const RawWaker as *const Waker) }
}
#[cfg(test)]
mod tests {
#[test] | }
} | #[cfg(feature = "std")]
fn issue_2091_cross_thread_segfault() {
let waker = std::thread::spawn(super::noop_waker_ref).join().unwrap();
waker.wake_by_ref(); |
comiis_hideShowPassword.js | (function(factory){if(typeof define==="function"&&define.amd){define(["jquery"],factory)}else if(typeof exports==="object"){factory(require("jquery"))}else{factory(jQuery)}})(function($,undef){var dataKey="plugin_hideShowPassword",shorthandArgs=["show","innerToggle"],SPACE=32,ENTER=13;var canSetInputAttribute=function(){var body=document.body,input=document.createElement("input"),result=true;if(!body){body=document.createElement("body")}input=body.appendChild(input);try{input.setAttribute("type","text")}catch(e){result=false}body.removeChild(input);return result}();var defaults={show:"infer",innerToggle:false,enable:canSetInputAttribute,className:" ",initEvent:"hideShowPasswordInit",changeEvent:"passwordVisibilityChange",props:{autocapitalize:"off",autocomplete:"off",autocorrect:"off",spellcheck:"false"},toggle:{element:'<div>',className:" ",touchSupport:typeof Modernizr==="undefined"?false:Modernizr.touch,attachToEvent:"click.hideShowPassword",attachToTouchEvent:"touchstart.hideShowPassword mousedown.hideShowPassword",attachToKeyEvent:"keyup",attachToKeyCodes:true,styles:{position:"absolute"},touchStyles:{pointerEvents:"none"},position:"infer",verticalAlign:"middle",offset:0,attr:{role:"div","aria-label":"Show Password",tabIndex:0}},wrapper:{element:"<div>",className:" ",enforceWidth:true,styles:{position:"relative"},inheritStyles:["display","verticalAlign","marginTop","marginRight","marginBottom","marginLeft"],innerElementStyles:{marginTop:0,marginRight:0,marginBottom:0,marginLeft:0}},states:{shown:{className:" ",changeEvent:"passwordShown",props:{type:"text"},toggle:{className:"comiis_Password_hide",content:"<i class='comiis_font f_d'></i>",attr:{"aria-pressed":"true"}}},hidden:{className:" ",changeEvent:"passwordHidden",props:{type:"password"},toggle:{className:"comiis_Password_show",content:"<i class='comiis_font f_d'></i>",attr:{"aria-pressed":"false"}}}}};function HideShowPassword(element,options){this.element=$(element);this.wrapperElement=$();this.toggleElement=$();this.init(options)}HideShowPassword.prototype={init:function(options){if(this.update(options,defaults)){this.element.addClass(this.options.className);if(this.options.innerToggle){this.wrapElement(this.options.wrapper);this.initToggle(this.options.toggle);if(typeof this.options.innerToggle==="string"){this.toggleElement.hide();this.element.one(this.options.innerToggle,$.proxy(function(){this.toggleElement.show()},this))}}this.element.trigger(this.options.initEvent,[this])}},update:function(options,base){this.options=this.prepareOptions(options,base);if(this.updateElement()){this.element.trigger(this.options.changeEvent,[this]).trigger(this.state().changeEvent,[this])}return this.options.enable},toggle:function(showVal){showVal=showVal||"toggle";return this.update({show:showVal})},prepareOptions:function(options,base){var original=options||{},keyCodes=[],testElement;base=base||this.options;options=$.extend(true,{},base,options);if(original.hasOwnProperty("wrapper")&&original.wrapper.hasOwnProperty("inheritStyles")){options.wrapper.inheritStyles=original.wrapper.inheritStyles}if(options.enable){if(options.show==="toggle"){options.show=this.isType("hidden",options.states)}else if(options.show==="infer"){options.show=this.isType("shown",options.states)}if(options.toggle.position==="infer"){options.toggle.position=this.element.css("text-direction")==="rtl"?"left":"right"}if(!$.isArray(options.toggle.attachToKeyCodes)){if(options.toggle.attachToKeyCodes===true){testElement=$(options.toggle.element);switch(testElement.prop("tagName").toLowerCase()){case"button":case"input":break;case"a":if(testElement.filter("[href]").length){keyCodes.push(SPACE);break}default:keyCodes.push(SPACE,ENTER);break}}options.toggle.attachToKeyCodes=keyCodes}}return options},updateElement:function(){if(!this.options.enable||this.isType())return false;this.element.prop($.extend({},this.options.props,this.state().props)).addClass(this.state().className).removeClass(this.otherState().className);this.updateToggle();return true},isType:function(comparison,states){states=states||this.options.states;comparison=comparison||this.state(undef,undef,states).props.type;if(states[comparison]){comparison=states[comparison].props.type}return this.element.prop("type")===comparison},state:function(key,invert,states){states=states||this.options.states;if(key===undef){key=this.options.show}if(typeof key==="boolean"){key=key?"shown":"hidden"}if(invert){key=key==="shown"?"hidden":"shown"}return states[key]},otherState:function(key){return this.state(key,true)},wrapElement:function(options){var enforceWidth=options.enforceWidth,targetWidth;if(!this.wrapperElement.length){targetWidth=this.element.outerWidth();$.each(options.inheritStyles,$.proxy(function(index,prop){options.styles[prop]=this.element.css(prop)},this));this.element.css(options.innerElementStyles).wrap($(options.element).addClass(options.className).css(options.styles));this.wrapperElement=this.element.parent();if(enforceWidth===true){enforceWidth=this.wrapperElement.outerWidth()===targetWidth?false:targetWidth}if(enforceWidth!==false){this.wrapperElement.css("width",enforceWidth)}}return this.wrapperElement},initToggle:function(options){if(!this.toggleElement.length){this.toggleElement=$(options.element).attr(options.attr).addClass(options.className).css(options.styles).appendTo(this.wrapperElement);this.updateToggle();this.positionToggle(options.position,options.verticalAlign,options.offset);if(options.touchSupport){this.toggleElement.css(options.touchStyles);this.element.on(options.attachToTouchEvent,$.proxy(this.toggleTouchEvent,this))}else{this.toggleElement.on(options.attachToEvent,$.proxy(this.toggleEvent,this))}if(options.attachToKeyCodes.length){this.toggleElement.on(options.attachToKeyEvent,$.proxy(this.toggleKeyEvent,this))}}return this.toggleElement},positionToggle:function(position,verticalAlign,offset){var styles={};styles[position]=offset;switch(verticalAlign){case"top":case"bottom":styles[verticalAlign]=offset;break;case"middle":styles.top="50%";styles.marginTop=this.toggleElement.outerHeight()/-2;break}return this.toggleElement.css(styles)},updateToggle:function(state,otherState){var paddingProp,targetPadding;if(this.toggleElement.length){paddingProp="padding-"+this.options.toggle.position;state=state||this.state().toggle;otherState=otherState||this.otherState().toggle;this.toggleElement.attr(state.attr).addClass(state.className).removeClass(otherState.className).html(state.content);targetPadding=this.toggleElement.outerWidth()+this.options.toggle.offset*2}return this.toggleElement},toggleEvent:function(event){event.preventDefault();this.toggle()},toggleKeyEvent:function(event){$.each(this.options.toggle.attachToKeyCodes,$.proxy(function(index,keyCode){if(event.which===keyCode){this.toggleEvent(event);return false}},this))},toggleTouchEvent:function(event){var toggleX=this.toggleElement.offset().left,eventX,lesser,greater;if(toggleX){eventX=event.pageX||event.originalEvent.pageX;if(this.options.toggle.position==="left"){toggleX+=this.toggleElement.outerWidth();lesser=eventX;greater=toggleX}else{lesser=toggleX;greater=eventX}if(greater>=lesser){this.toggleEvent(event)}}}};$.fn.hideShowPassword=function(){var options={};$.each(arguments,function(index,value){var newOptions={};if(typeof value==="object"){newOptions=value}else if(shorthandArgs[index]){newOptions[shorthandArgs[index]]=value}else{return false}$.extend(true,options,newOptions)});return this.each(function(){var $this=$(this),data=$this.data(dataKey);if(data){data.update(options)}else{$this.data(dataKey,new HideShowPassword(this,options))}})};$.each({show:true,hide:false,toggle:"toggle"},function(verb,showVal){$.fn[verb+"Password"]=function(innerToggle,options){return this.hideShowPassword(showVal,innerToggle,options)}})}); |
||
volumeattachment.go | /*
Copyright The Kubernetes 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 v1
import (
"time"
v1 "k8s.io/api/storage/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
scheme "k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
// VolumeAttachmentsGetter has a method to return a VolumeAttachmentInterface.
// A group's client should implement this interface.
type VolumeAttachmentsGetter interface {
VolumeAttachments() VolumeAttachmentInterface
}
// VolumeAttachmentInterface has methods to work with VolumeAttachment resources.
type VolumeAttachmentInterface interface {
Create(*v1.VolumeAttachment) (*v1.VolumeAttachment, error)
Update(*v1.VolumeAttachment) (*v1.VolumeAttachment, error)
UpdateStatus(*v1.VolumeAttachment) (*v1.VolumeAttachment, error)
Delete(name string, options *metav1.DeleteOptions) error
DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error
Get(name string, options metav1.GetOptions) (*v1.VolumeAttachment, error)
List(opts metav1.ListOptions) (*v1.VolumeAttachmentList, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VolumeAttachment, err error)
VolumeAttachmentExpansion
}
// volumeAttachments implements VolumeAttachmentInterface
type volumeAttachments struct {
client rest.Interface
}
// newVolumeAttachments returns a VolumeAttachments
func newVolumeAttachments(c *StorageV1Client) *volumeAttachments {
return &volumeAttachments{
client: c.RESTClient(),
}
}
// Get takes name of the volumeAttachment, and returns the corresponding volumeAttachment object, and an error if there is any.
func (c *volumeAttachments) Get(name string, options metav1.GetOptions) (result *v1.VolumeAttachment, err error) {
result = &v1.VolumeAttachment{}
err = c.client.Get().
Resource("volumeattachments").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do().
Into(result)
return
}
// List takes label and field selectors, and returns the list of VolumeAttachments that match those selectors.
func (c *volumeAttachments) List(opts metav1.ListOptions) (result *v1.VolumeAttachmentList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v1.VolumeAttachmentList{}
err = c.client.Get().
Resource("volumeattachments").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do().
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested volumeAttachments.
func (c *volumeAttachments) Watch(opts metav1.ListOptions) (watch.Interface, error) {
| var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Resource("volumeattachments").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch()
}
// Create takes the representation of a volumeAttachment and creates it. Returns the server's representation of the volumeAttachment, and an error, if there is any.
func (c *volumeAttachments) Create(volumeAttachment *v1.VolumeAttachment) (result *v1.VolumeAttachment, err error) {
result = &v1.VolumeAttachment{}
err = c.client.Post().
Resource("volumeattachments").
Body(volumeAttachment).
Do().
Into(result)
return
}
// Update takes the representation of a volumeAttachment and updates it. Returns the server's representation of the volumeAttachment, and an error, if there is any.
func (c *volumeAttachments) Update(volumeAttachment *v1.VolumeAttachment) (result *v1.VolumeAttachment, err error) {
result = &v1.VolumeAttachment{}
err = c.client.Put().
Resource("volumeattachments").
Name(volumeAttachment.Name).
Body(volumeAttachment).
Do().
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *volumeAttachments) UpdateStatus(volumeAttachment *v1.VolumeAttachment) (result *v1.VolumeAttachment, err error) {
result = &v1.VolumeAttachment{}
err = c.client.Put().
Resource("volumeattachments").
Name(volumeAttachment.Name).
SubResource("status").
Body(volumeAttachment).
Do().
Into(result)
return
}
// Delete takes name of the volumeAttachment and deletes it. Returns an error if one occurs.
func (c *volumeAttachments) Delete(name string, options *metav1.DeleteOptions) error {
return c.client.Delete().
Resource("volumeattachments").
Name(name).
Body(options).
Do().
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *volumeAttachments) DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error {
var timeout time.Duration
if listOptions.TimeoutSeconds != nil {
timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Resource("volumeattachments").
VersionedParams(&listOptions, scheme.ParameterCodec).
Timeout(timeout).
Body(options).
Do().
Error()
}
// Patch applies the patch and returns the patched volumeAttachment.
func (c *volumeAttachments) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VolumeAttachment, err error) {
result = &v1.VolumeAttachment{}
err = c.client.Patch(pt).
Resource("volumeattachments").
SubResource(subresources...).
Name(name).
Body(data).
Do().
Into(result)
return
} | |
main.go | package main
import (
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"strconv"
"github.com/jle35/proxmox-api-go/proxmox"
)
func main() {
var insecure *bool
insecure = flag.Bool("insecure", false, "TLS insecure mode")
proxmox.Debug = flag.Bool("debug", false, "debug mode")
taskTimeout := flag.Int("timeout", 300, "api task timeout in seconds")
fvmid := flag.Int("vmid", -1, "custom vmid (instead of auto)")
flag.Parse()
tlsconf := &tls.Config{InsecureSkipVerify: true}
if !*insecure {
tlsconf = nil
}
c, _ := proxmox.NewClient(os.Getenv("PM_API_URL"), nil, tlsconf, *taskTimeout)
err := c.Login(os.Getenv("PM_USER"), os.Getenv("PM_PASS"), os.Getenv("PM_OTP"))
if err != nil {
log.Fatal(err)
}
vmid := *fvmid
if vmid < 0 {
if len(flag.Args()) > 1 {
vmid, err = strconv.Atoi(flag.Args()[len(flag.Args())-1])
if err != nil {
vmid = 0
}
} else if flag.Args()[0] == "idstatus" {
vmid = 0
}
}
var jbody interface{}
var vmr *proxmox.VmRef
if len(flag.Args()) == 0 {
fmt.Printf("Missing action, try start|stop vmid\n")
os.Exit(0)
}
switch flag.Args()[0] {
case "start":
vmr = proxmox.NewVmRef(vmid)
jbody, _ = c.StartVm(vmr)
case "stop":
vmr = proxmox.NewVmRef(vmid)
jbody, _ = c.StopVm(vmr)
case "destroy":
vmr = proxmox.NewVmRef(vmid)
jbody, err = c.StopVm(vmr)
failError(err)
jbody, _ = c.DeleteVm(vmr)
case "getConfig":
vmr = proxmox.NewVmRef(vmid)
c.CheckVmRef(vmr)
vmType := vmr.GetVmType()
var config interface{}
var err error
if vmType == "qemu" {
config, err = proxmox.NewConfigQemuFromApi(vmr, c)
} else if vmType == "lxc" {
config, err = proxmox.NewConfigLxcFromApi(vmr, c)
}
failError(err)
cj, err := json.MarshalIndent(config, "", " ")
log.Println(string(cj))
case "getNetworkInterfaces":
vmr = proxmox.NewVmRef(vmid)
c.CheckVmRef(vmr)
networkInterfaces, err := c.GetVmAgentNetworkInterfaces(vmr)
failError(err)
networkInterfaceJson, err := json.Marshal(networkInterfaces) | fmt.Println(string(networkInterfaceJson))
case "createQemu":
config, err := proxmox.NewConfigQemuFromJson(os.Stdin)
failError(err)
vmr = proxmox.NewVmRef(vmid)
vmr.SetNode(flag.Args()[2])
failError(config.CreateVm(vmr, c))
log.Println("Complete")
case "createLxc":
config, err := proxmox.NewConfigLxcFromJson(os.Stdin)
failError(err)
vmr = proxmox.NewVmRef(vmid)
vmr.SetNode(flag.Args()[2])
failError(config.CreateLxc(vmr, c))
log.Println("Complete")
case "installQemu":
config, err := proxmox.NewConfigQemuFromJson(os.Stdin)
failError(err)
if vmid > 0 {
vmr = proxmox.NewVmRef(vmid)
} else {
nextid, err := c.GetNextID(0)
failError(err)
vmr = proxmox.NewVmRef(nextid)
}
vmr.SetNode(flag.Args()[1])
log.Print("Creating node: ")
log.Println(vmr)
failError(config.CreateVm(vmr, c))
_, err = c.StartVm(vmr)
failError(err)
sshPort, err := proxmox.SshForwardUsernet(vmr, c)
failError(err)
log.Println("Waiting for CDRom install shutdown (at least 5 minutes)")
failError(proxmox.WaitForShutdown(vmr, c))
log.Println("Restarting")
_, err = c.StartVm(vmr)
failError(err)
sshPort, err = proxmox.SshForwardUsernet(vmr, c)
failError(err)
log.Println("SSH Portforward on:" + sshPort)
log.Println("Complete")
case "idstatus":
maxid, err := proxmox.MaxVmId(c)
failError(err)
nextid, err := c.GetNextID(vmid)
failError(err)
log.Println("---")
log.Printf("MaxID: %d\n", maxid)
log.Printf("NextID: %d\n", nextid)
log.Println("---")
case "cloneQemu":
config, err := proxmox.NewConfigQemuFromJson(os.Stdin)
failError(err)
log.Println("Looking for template: " + flag.Args()[1])
sourceVmr, err := c.GetVmRefByName(flag.Args()[1])
failError(err)
if sourceVmr == nil {
log.Fatal("Can't find template")
return
}
if vmid == 0 {
vmid, err = c.GetNextID(0)
}
vmr = proxmox.NewVmRef(vmid)
vmr.SetNode(flag.Args()[2])
log.Print("Creating node: ")
log.Println(vmr)
failError(config.CloneVm(sourceVmr, vmr, c))
failError(config.UpdateConfig(vmr, c))
log.Println("Complete")
case "rollbackQemu":
vmr = proxmox.NewVmRef(vmid)
jbody, err = c.RollbackQemuVm(vmr, flag.Args()[2])
failError(err)
case "sshforward":
vmr = proxmox.NewVmRef(vmid)
sshPort, err := proxmox.SshForwardUsernet(vmr, c)
failError(err)
log.Println("SSH Portforward on:" + sshPort)
case "sshbackward":
vmr = proxmox.NewVmRef(vmid)
err = proxmox.RemoveSshForwardUsernet(vmr, c)
failError(err)
log.Println("SSH Portforward off")
case "sendstring":
vmr = proxmox.NewVmRef(vmid)
err = proxmox.SendKeysString(vmr, c, flag.Args()[2])
failError(err)
log.Println("Keys sent")
case "nextid":
id, err := c.NextId()
failError(err)
log.Printf("Getting Next Free ID: %d\n", id)
case "checkid":
i, err := strconv.Atoi(flag.Args()[1])
failError(err)
id, err := c.VMIdExists(i)
failError(err)
log.Printf("Selected ID is free: %d\n", id)
case "migrate":
vmr := proxmox.NewVmRef(vmid)
c.GetVmInfo(vmr)
args := flag.Args()
if len(args) <= 1 {
fmt.Printf("Missing target node\n")
os.Exit(1)
}
_, err := c.MigrateNode(vmr, args[1], true)
if err != nil {
log.Printf("Error to move %+v\n", err)
os.Exit(1)
}
log.Printf("VM %d is moved on %s\n", vmid, args[1])
default:
fmt.Printf("unknown action, try start|stop vmid\n")
}
if jbody != nil {
log.Println(jbody)
}
//log.Println(vmr)
}
func failError(err error) {
if err != nil {
log.Fatal(err)
}
return
} | |
arguments.py | # Copyright 2017, 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
"""
Defines commandline arguments for the main CLIs with reasonable defaults.
"""
import argparse
import os
import sys
import types
import yaml
from typing import Any, Callable, Dict, List, Tuple, Optional
from . import constants as C
from . import data_io
from .lr_scheduler import LearningRateSchedulerFixedStep
class ConfigArgumentParser(argparse.ArgumentParser):
"""
Extension of argparse.ArgumentParser supporting config files.
The option --config is added automatically and expects a YAML serialized
dictionary, similar to the return value of parse_args(). Command line
parameters have precedence over config file values. Usage should be
transparent, just substitute argparse.ArgumentParser with this class.
Extended from
https://stackoverflow.com/questions/28579661/getting-required-option-from-namespace-in-python
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.argument_definitions = {} # type: Dict[Tuple, Dict]
self.argument_actions = [] # type: List[Any]
self._overwrite_add_argument(self)
self.add_argument("--config", help="Config file in YAML format.", type=str)
# Note: not FileType so that we can get the path here
def _register_argument(self, _action, *args, **kwargs):
self.argument_definitions[args] = kwargs
self.argument_actions.append(_action)
def _overwrite_add_argument(self, original_object):
def _new_add_argument(this_self, *args, **kwargs):
action = this_self.original_add_argument(*args, **kwargs)
this_self.config_container._register_argument(action, *args, **kwargs)
original_object.original_add_argument = original_object.add_argument
original_object.config_container = self
original_object.add_argument = types.MethodType(_new_add_argument, original_object)
return original_object
def add_argument_group(self, *args, **kwargs):
group = super().add_argument_group(*args, **kwargs)
return self._overwrite_add_argument(group)
def parse_args(self, args=None, namespace=None) -> argparse.Namespace:
# Mini argument parser to find the config file
config_parser = argparse.ArgumentParser(add_help=False)
config_parser.add_argument("--config", type=regular_file())
config_args, _ = config_parser.parse_known_args(args=args)
initial_args = argparse.Namespace()
if config_args.config:
initial_args = load_args(config_args.config)
# Remove the 'required' flag from options loaded from config file
for action in self.argument_actions:
if action.dest in initial_args:
action.required = False
return super().parse_args(args=args, namespace=initial_args)
def save_args(args: argparse.Namespace, fname: str):
with open(fname, 'w') as out:
yaml.safe_dump(args.__dict__, out, default_flow_style=False)
def load_args(fname: str) -> argparse.Namespace:
with open(fname, 'r') as inp:
return argparse.Namespace(**yaml.safe_load(inp))
def regular_file() -> Callable:
"""
Returns a method that can be used in argument parsing to check the argument is a regular file or a symbolic link,
but not, e.g., a process substitution.
:return: A method that can be used as a type in argparse.
"""
def check_regular_file(value_to_check):
value_to_check = str(value_to_check)
if not os.path.isfile(value_to_check):
raise argparse.ArgumentTypeError("must exist and be a regular file.")
return value_to_check
return check_regular_file
def regular_folder() -> Callable:
"""
Returns a method that can be used in argument parsing to check the argument is a directory.
:return: A method that can be used as a type in argparse.
"""
def check_regular_directory(value_to_check):
value_to_check = str(value_to_check)
if not os.path.isdir(value_to_check):
raise argparse.ArgumentTypeError("must be a directory.")
return value_to_check
return check_regular_directory
def int_greater_or_equal(threshold: int) -> Callable:
"""
Returns a method that can be used in argument parsing to check that the argument is greater or equal to `threshold`.
:param threshold: The threshold that we assume the cli argument value is greater or equal to.
:return: A method that can be used as a type in argparse.
"""
def check_greater_equal(value_to_check):
value_to_check = int(value_to_check)
if value_to_check < threshold:
raise argparse.ArgumentTypeError("must be greater or equal to %d." % threshold)
return value_to_check
return check_greater_equal
def learning_schedule() -> Callable:
"""
Returns a method that can be used in argument parsing to check that the argument is a valid learning rate schedule
string.
:return: A method that can be used as a type in argparse.
"""
def parse(schedule_str):
try:
schedule = LearningRateSchedulerFixedStep.parse_schedule_str(schedule_str)
except ValueError:
raise argparse.ArgumentTypeError(
"Learning rate schedule string should have form rate1:num_updates1[,rate2:num_updates2,...]")
return schedule
return parse
def simple_dict() -> Callable:
"""
A simple dictionary format that does not require spaces or quoting.
Supported types: bool, int, float
:return: A method that can be used as a type in argparse.
"""
def parse(dict_str: str):
def | (value: str):
if value == "True":
return True
if value == "False":
return False
if "." in value:
return float(value)
return int(value)
_dict = dict()
try:
for entry in dict_str.split(","):
key, value = entry.split(":")
_dict[key] = _parse(value)
except ValueError:
raise argparse.ArgumentTypeError("Specify argument dictionary as key1:value1,key2:value2,..."
" Supported types: bool, int, float.")
return _dict
return parse
def multiple_values(num_values: int = 0,
greater_or_equal: Optional[float] = None,
data_type: Callable = int) -> Callable:
"""
Returns a method to be used in argument parsing to parse a string of the form "<val>:<val>[:<val>...]" into
a tuple of values of type data_type.
:param num_values: Optional number of ints required.
:param greater_or_equal: Optional constraint that all values should be greater or equal to this value.
:param data_type: Type of values. Default: int.
:return: Method for parsing.
"""
def parse(value_to_check):
if ':' in value_to_check:
expected_num_separators = num_values - 1 if num_values else 0
if expected_num_separators > 0 and (value_to_check.count(':') != expected_num_separators):
raise argparse.ArgumentTypeError("Expected either a single value or %d values separated by %s" %
(num_values, C.ARG_SEPARATOR))
values = tuple(map(data_type, value_to_check.split(C.ARG_SEPARATOR, num_values - 1)))
else:
values = tuple([data_type(value_to_check)] * num_values)
if greater_or_equal is not None:
if any((value < greater_or_equal for value in values)):
raise argparse.ArgumentTypeError("Must provide value greater or equal to %d" % greater_or_equal)
return values
return parse
def file_or_stdin() -> Callable:
"""
Returns a file descriptor from stdin or opening a file from a given path.
"""
def parse(path):
if path is None or path == "-":
return sys.stdin
else:
return data_io.smart_open(path)
return parse
def add_average_args(params):
average_params = params.add_argument_group("Averaging")
average_params.add_argument(
"inputs",
metavar="INPUT",
type=str,
nargs="+",
help="either a single model directory (automatic checkpoint selection) "
"or multiple .params files (manual checkpoint selection)")
average_params.add_argument(
"--metric",
help="Name of the metric to choose n-best checkpoints from. Default: %(default)s.",
default=C.PERPLEXITY,
choices=C.METRICS)
average_params.add_argument(
"-n",
type=int,
default=4,
help="number of checkpoints to find. Default: %(default)s.")
average_params.add_argument(
"--output", "-o", required=True, type=str, help="File to write averaged parameters to.")
average_params.add_argument(
"--strategy",
choices=["best", "last", "lifespan"],
default="best",
help="selection method. Default: %(default)s.")
def add_extract_args(params):
extract_params = params.add_argument_group("Extracting")
extract_params.add_argument("input",
metavar="INPUT",
type=str,
help="Either a model directory (using params.best) or a specific params.x file.")
extract_params.add_argument('--names', '-n',
nargs='*',
default=[],
help='Names of parameters to be extracted.')
extract_params.add_argument('--list-all', '-l',
action='store_true',
help='List names of all available parameters.')
extract_params.add_argument('--output', '-o',
type=str,
help="File to write extracted parameters to (in .npz format).")
def add_rerank_args(params):
rerank_params = params.add_argument_group("Reranking")
rerank_params.add_argument("--reference", "-r",
type=str,
required=True,
help="File where target reference translations are stored.")
rerank_params.add_argument("--hypotheses", "-hy",
type=str,
required=True,
help="File with nbest translations, one nbest list per line,"
"in JSON format as returned by sockeye.translate with --nbest-size x.")
rerank_params.add_argument("--metric", "-m",
type=str,
required=False,
default=C.RERANK_BLEU,
choices=C.RERANK_METRICS,
help="Sentence-level metric used to compare each nbest translation to the reference."
"Default: %(default)s.")
rerank_params.add_argument("--output-best",
action="store_true",
help="Output only the best hypothesis from each nbest list.")
rerank_params.add_argument("--return-score",
action="store_true",
help="Returns the reranking scores as scores in output JSON objects.")
def add_lexicon_args(params):
lexicon_params = params.add_argument_group("Model & Top-k")
lexicon_params.add_argument("--model", "-m", required=True,
help="Model directory containing source and target vocabularies.")
lexicon_params.add_argument("-k", type=int, default=200,
help="Number of target translations to keep per source. Default: %(default)s.")
def add_lexicon_create_args(params):
lexicon_params = params.add_argument_group("I/O")
lexicon_params.add_argument("--input", "-i", required=True,
help="Probabilistic lexicon (fast_align format) to build top-k lexicon from.")
lexicon_params.add_argument("--output", "-o", required=True, help="File name to write top-k lexicon to.")
def add_lexicon_inspect_args(params):
lexicon_params = params.add_argument_group("Lexicon to inspect")
lexicon_params.add_argument("--lexicon", "-l", required=True, help="File name of top-k lexicon to inspect.")
def add_logging_args(params):
logging_params = params.add_argument_group("Logging")
logging_params.add_argument('--quiet', '-q',
default=False,
action="store_true",
help='Suppress console logging.')
def add_training_data_args(params, required=False):
params.add_argument(C.TRAINING_ARG_SOURCE, '-s',
required=required,
type=regular_file(),
help='Source side of parallel training data.')
params.add_argument('--source-factors', '-sf',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='File(s) containing additional token-parallel source side factors. Default: %(default)s.')
params.add_argument(C.TRAINING_ARG_TARGET, '-t',
required=required,
type=regular_file(),
help='Target side of parallel training data.')
def add_validation_data_params(params):
params.add_argument('--validation-source', '-vs',
required=True,
type=regular_file(),
help='Source side of validation data.')
params.add_argument('--validation-source-factors', '-vsf',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='File(s) containing additional token-parallel validation source side factors. '
'Default: %(default)s.')
params.add_argument('--validation-target', '-vt',
required=True,
type=regular_file(),
help='Target side of validation data.')
def add_prepared_data_args(params):
params.add_argument(C.TRAINING_ARG_PREPARED_DATA, '-d',
type=regular_folder(),
help='Prepared training data directory created through python -m sockeye.prepare_data.')
def add_monitoring_args(params):
params.add_argument('--monitor-pattern',
default=None,
type=str,
help="Pattern to match outputs/weights/gradients to monitor. '.*' monitors everything. "
"Default: %(default)s.")
params.add_argument('--monitor-stat-func',
default=C.STAT_FUNC_DEFAULT,
choices=list(C.MONITOR_STAT_FUNCS.keys()),
help="Statistics function to run on monitored outputs/weights/gradients. "
"Default: %(default)s.")
def add_training_output_args(params):
params.add_argument('--output', '-o',
required=True,
help='Folder where model & training results are written to.')
params.add_argument('--overwrite-output',
action='store_true',
help='Delete all contents of the model directory if it already exists.')
def add_training_io_args(params):
params = params.add_argument_group("Data & I/O")
# Unfortunately we must set --source/--target to not required as we either accept these parameters
# or --prepared-data which can not easily be encoded in argparse.
add_training_data_args(params, required=False)
add_prepared_data_args(params)
add_validation_data_params(params)
add_bucketing_args(params)
add_vocab_args(params)
add_training_output_args(params)
add_monitoring_args(params)
def add_bucketing_args(params):
params.add_argument('--no-bucketing',
action='store_true',
help='Disable bucketing: always unroll the graph to --max-seq-len. Default: %(default)s.')
params.add_argument('--bucket-width',
type=int_greater_or_equal(1),
default=10,
help='Width of buckets in tokens. Default: %(default)s.')
params.add_argument(C.TRAINING_ARG_MAX_SEQ_LEN,
type=multiple_values(num_values=2, greater_or_equal=1),
default=(99, 99),
help='Maximum sequence length in tokens.'
'Use "x:x" to specify separate values for src&tgt. Default: %(default)s.')
def add_prepare_data_cli_args(params):
params = params.add_argument_group("Data preparation.")
add_training_data_args(params, required=True)
add_vocab_args(params)
add_bucketing_args(params)
params.add_argument('--num-samples-per-shard',
type=int_greater_or_equal(1),
default=1000000,
help='The approximate number of samples per shard. Default: %(default)s.')
params.add_argument('--min-num-shards',
default=1,
type=int_greater_or_equal(1),
help='The minimum number of shards to use, even if they would not '
'reach the desired number of samples per shard. Default: %(default)s.')
params.add_argument('--seed',
type=int,
default=13,
help='Random seed used that makes shard assignments deterministic. Default: %(default)s.')
params.add_argument('--output', '-o',
required=True,
help='Folder where the prepared and possibly sharded data is written to.')
def add_device_args(params):
device_params = params.add_argument_group("Device parameters")
device_params.add_argument('--device-ids', default=[-1],
help='List or number of GPUs ids to use. Default: %(default)s. '
'Use negative numbers to automatically acquire a certain number of GPUs, e.g. -5 '
'will find 5 free GPUs. '
'Use positive numbers to acquire a specific GPU id on this host. '
'(Note that automatic acquisition of GPUs assumes that all GPU processes on '
'this host are using automatic sockeye GPU acquisition).',
nargs='+', type=int)
device_params.add_argument('--use-cpu',
action='store_true',
help='Use CPU device instead of GPU.')
device_params.add_argument('--disable-device-locking',
action='store_true',
help='Just use the specified device ids without locking.')
device_params.add_argument('--lock-dir',
default="/tmp",
help='When acquiring a GPU we do file based locking so that only one Sockeye process '
'can run on the a GPU. This is the folder in which we store the file '
'locks. For locking to work correctly it is assumed all processes use the same '
'lock directory. The only requirement for the directory are file '
'write permissions.')
def add_vocab_args(params):
params.add_argument('--source-vocab',
required=False,
default=None,
help='Existing source vocabulary (JSON).')
params.add_argument('--target-vocab',
required=False,
default=None,
help='Existing target vocabulary (JSON).')
params.add_argument('--source-factor-vocabs',
required=False,
nargs='+',
type=regular_file(),
default=[],
help='Existing source factor vocabulary (-ies) (JSON).')
params.add_argument(C.VOCAB_ARG_SHARED_VOCAB,
action='store_true',
default=False,
help='Share source and target vocabulary. '
'Will be automatically turned on when using weight tying. Default: %(default)s.')
params.add_argument('--num-words',
type=multiple_values(num_values=2, greater_or_equal=0),
default=(0, 0),
help='Maximum vocabulary size. Use "x:x" to specify separate values for src&tgt. '
'A value of 0 indicates that the vocabulary unrestricted and determined from the data by '
'creating an entry for all words that occur at least --word-min-count times.'
'Default: %(default)s.')
params.add_argument('--word-min-count',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(1, 1),
help='Minimum frequency of words to be included in vocabularies. Default: %(default)s.')
params.add_argument('--pad-vocab-to-multiple-of',
type=int,
default=None,
help='Pad vocabulary to a multiple of this integer. Default: %(default)s.')
def add_model_parameters(params):
model_params = params.add_argument_group("ModelConfig")
model_params.add_argument('--params', '-p',
type=str,
default=None,
help='Initialize model parameters from file. Overrides random initializations.')
model_params.add_argument('--allow-missing-params',
action="store_true",
default=False,
help="Allow missing parameters when initializing model parameters from file. "
"Default: %(default)s.")
model_params.add_argument('--encoder',
choices=C.ENCODERS,
default=C.TRANSFORMER_TYPE,
help="Type of encoder. Default: %(default)s.")
model_params.add_argument('--decoder',
choices=C.DECODERS,
default=C.TRANSFORMER_TYPE,
help="Type of encoder. Default: %(default)s.")
model_params.add_argument('--num-layers',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(6, 6),
help='Number of layers for encoder & decoder. '
'Use "x:x" to specify separate values for encoder & decoder. Default: %(default)s.')
model_params.add_argument('--conv-embed-output-dim',
type=int_greater_or_equal(1),
default=None,
help="Project segment embeddings to this size for ConvolutionalEmbeddingEncoder. Omit to"
" avoid projection, leaving segment embeddings total size of all filters. Default:"
" %(default)s.")
model_params.add_argument('--conv-embed-max-filter-width',
type=int_greater_or_equal(1),
default=8,
help="Maximum filter width for ConvolutionalEmbeddingEncoder. Default: %(default)s.")
model_params.add_argument('--conv-embed-num-filters',
type=multiple_values(greater_or_equal=1),
default=(200, 200, 250, 250, 300, 300, 300, 300),
help="List of number of filters of each width 1..max for ConvolutionalEmbeddingEncoder. "
"Default: %(default)s.")
model_params.add_argument('--conv-embed-pool-stride',
type=int_greater_or_equal(1),
default=5,
help="Pooling stride for ConvolutionalEmbeddingEncoder. Default: %(default)s.")
model_params.add_argument('--conv-embed-num-highway-layers',
type=int_greater_or_equal(0),
default=4,
help="Number of highway layers for ConvolutionalEmbeddingEncoder. Default: %(default)s.")
model_params.add_argument('--conv-embed-add-positional-encodings',
action='store_true',
default=False,
help="Add positional encodings to final segment embeddings for"
" ConvolutionalEmbeddingEncoder. Default: %(default)s.")
# convolutional encoder/decoder arguments arguments
model_params.add_argument('--cnn-kernel-width',
type=multiple_values(num_values=2, greater_or_equal=1, data_type=int),
default=(3, 3),
help='Kernel width of the convolutional encoder and decoder. Default: %(default)s.')
model_params.add_argument('--cnn-num-hidden',
type=int_greater_or_equal(1),
default=512,
help='Number of hidden units for the convolutional encoder and decoder. '
'Default: %(default)s.')
model_params.add_argument('--cnn-activation-type',
choices=C.CNN_ACTIVATION_TYPES,
default=C.GLU,
help="Type activation to use for each convolutional layer. Default: %(default)s.")
model_params.add_argument('--cnn-positional-embedding-type',
choices=C.POSITIONAL_EMBEDDING_TYPES,
default=C.LEARNED_POSITIONAL_EMBEDDING,
help='The type of positional embedding. Default: %(default)s.')
model_params.add_argument('--cnn-project-qkv',
action='store_true',
default=False,
help="Optionally apply query, key and value projections to the source and target hidden "
"vectors before applying the attention mechanism.")
# rnn arguments
model_params.add_argument('--rnn-cell-type',
choices=C.CELL_TYPES,
default=C.LSTM_TYPE,
help='RNN cell type for encoder and decoder. Default: %(default)s.')
model_params.add_argument('--rnn-num-hidden',
type=int_greater_or_equal(1),
default=1024,
help='Number of RNN hidden units for encoder and decoder. Default: %(default)s.')
model_params.add_argument('--rnn-encoder-reverse-input',
action='store_true',
help='Reverse input sequence for RNN encoder. Default: %(default)s.')
model_params.add_argument('--rnn-decoder-state-init',
default=C.RNN_DEC_INIT_LAST,
choices=C.RNN_DEC_INIT_CHOICES,
help='How to initialize RNN decoder states. Default: %(default)s.')
model_params.add_argument('--rnn-residual-connections',
action="store_true",
default=False,
help="Add residual connections to stacked RNNs. (see Wu ETAL'16). Default: %(default)s.")
model_params.add_argument('--rnn-first-residual-layer',
type=int_greater_or_equal(2),
default=2,
help='First RNN layer to have a residual connection. Default: %(default)s.')
model_params.add_argument('--rnn-context-gating', action="store_true",
help="Enables a context gate which adaptively weighs the RNN decoder input against the "
"source context vector before each update of the decoder hidden state.")
# transformer arguments
model_params.add_argument('--transformer-model-size',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(512, 512),
help='Number of hidden units in transformer layers. '
'Use "x:x" to specify separate values for encoder & decoder. Default: %(default)s.')
model_params.add_argument('--transformer-attention-heads',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(8, 8),
help='Number of heads for all self-attention when using transformer layers. '
'Use "x:x" to specify separate values for encoder & decoder. Default: %(default)s.')
model_params.add_argument('--transformer-feed-forward-num-hidden',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(2048, 2048),
help='Number of hidden units in transformers feed forward layers. '
'Use "x:x" to specify separate values for encoder & decoder. Default: %(default)s.')
model_params.add_argument('--transformer-activation-type',
choices=C.TRANSFORMER_ACTIVATION_TYPES,
default=C.RELU,
help="Type activation to use for each feed forward layer. Default: %(default)s.")
model_params.add_argument('--transformer-positional-embedding-type',
choices=C.POSITIONAL_EMBEDDING_TYPES,
default=C.FIXED_POSITIONAL_EMBEDDING,
help='The type of positional embedding. Default: %(default)s.')
model_params.add_argument('--transformer-preprocess',
type=multiple_values(num_values=2, greater_or_equal=None, data_type=str),
default=('n', 'n'),
help='Transformer preprocess sequence for encoder and decoder. Supports three types of '
'operations: d=dropout, r=residual connection, n=layer normalization. You can '
'combine in any order, for example: "ndr". '
'Leave empty to not use any of these operations. '
'You can specify separate sequences for encoder and decoder by separating with ":" '
'For example: n:drn '
'Default: %(default)s.')
model_params.add_argument('--transformer-postprocess',
type=multiple_values(num_values=2, greater_or_equal=None, data_type=str),
default=('dr', 'dr'),
help='Transformer postprocess sequence for encoder and decoder. Supports three types of '
'operations: d=dropout, r=residual connection, n=layer normalization. You can '
'combine in any order, for example: "ndr". '
'Leave empty to not use any of these operations. '
'You can specify separate sequences for encoder and decoder by separating with ":" '
'For example: n:drn '
'Default: %(default)s.')
# LHUC
# TODO: The convolutional model does not support lhuc yet
model_params.add_argument('--lhuc',
nargs="+",
default=None,
choices=C.LHUC_CHOICES,
metavar="COMPONENT",
help="Use LHUC (Vilar 2018). Include an amplitude parameter to hidden units for"
" domain adaptation. Needs a pre-trained model. Valid values: {values}. Currently not"
" supported for convolutional models. Default: %(default)s.".format(
values=", ".join(C.LHUC_CHOICES)))
# embedding arguments
model_params.add_argument('--num-embed',
type=multiple_values(num_values=2, greater_or_equal=1),
default=(512, 512),
help='Embedding size for source and target tokens. '
'Use "x:x" to specify separate values for src&tgt. Default: %(default)s.')
model_params.add_argument('--source-factors-num-embed',
type=int,
nargs='+',
default=[],
help='Embedding size for additional source factors. '
'You must provide as many dimensions as '
'(validation) source factor files. Default: %(default)s.')
# attention arguments
model_params.add_argument('--rnn-attention-type',
choices=C.ATT_TYPES,
default=C.ATT_MLP,
help='Attention model for RNN decoders. Choices: {%(choices)s}. '
'Default: %(default)s.')
model_params.add_argument('--rnn-attention-num-hidden',
default=None,
type=int,
help='Number of hidden units for attention layers. Default: equal to --rnn-num-hidden.')
model_params.add_argument('--rnn-attention-use-prev-word', action="store_true",
help="Feed the previous target embedding into the attention mechanism.")
model_params.add_argument('--rnn-scale-dot-attention',
action='store_true',
help='Optional scale before dot product. Only applicable to \'dot\' attention type. '
'[Vaswani et al, 2017]')
model_params.add_argument('--rnn-attention-coverage-type',
choices=C.COVERAGE_TYPES,
default=C.COVERAGE_COUNT,
help="Type of model for updating coverage vectors. 'count' refers to an update method "
"that accumulates attention scores. 'fertility' accumulates attention scores as well "
"but also computes a fertility value for every source word. "
"'tanh', 'sigmoid', 'relu', 'softrelu' "
"use non-linear layers with the respective activation type, and 'gru' uses a "
"GRU to update the coverage vectors. Default: %(default)s.")
model_params.add_argument('--rnn-attention-coverage-max-fertility',
type=int,
default=2,
help="Maximum fertility for individual source words. Default: %(default)s.")
model_params.add_argument('--rnn-attention-coverage-num-hidden',
type=int,
default=1,
help="Number of hidden units for coverage vectors. Default: %(default)s.")
model_params.add_argument('--rnn-attention-in-upper-layers',
action="store_true",
help="Pass the attention to the upper layers of the RNN decoder, similar "
"to GNMT paper. Only applicable if more than one layer is used.")
model_params.add_argument('--rnn-attention-mhdot-heads',
type=int, default=None,
help='Number of heads for Multi-head dot attention. Default: %(default)s.')
model_params.add_argument('--weight-tying',
action='store_true',
help='Turn on weight tying (see arxiv.org/abs/1608.05859). '
'The type of weight sharing is determined through '
'--weight-tying-type. Default: %(default)s.')
model_params.add_argument('--weight-tying-type',
default=C.WEIGHT_TYING_TRG_SOFTMAX,
choices=[C.WEIGHT_TYING_SRC_TRG_SOFTMAX,
C.WEIGHT_TYING_SRC_TRG,
C.WEIGHT_TYING_TRG_SOFTMAX],
help='The type of weight tying. source embeddings=src, target embeddings=trg, '
'target softmax weight matrix=softmax. Default: %(default)s.')
model_params.add_argument('--layer-normalization', action="store_true",
help="Adds layer normalization before non-linear activations. "
"This includes MLP attention, RNN decoder state initialization, "
"RNN decoder hidden state, and cnn layers."
"It does not normalize RNN cell activations "
"(this can be done using the '%s' or '%s' rnn-cell-type." % (C.LNLSTM_TYPE,
C.LNGLSTM_TYPE))
model_params.add_argument('--weight-normalization', action="store_true",
help="Adds weight normalization to decoder output layers "
"(and all convolutional weight matrices for CNN decoders). Default: %(default)s.")
def add_batch_args(params, default_batch_size=4096):
params.add_argument('--batch-size', '-b',
type=int_greater_or_equal(1),
default=default_batch_size,
help='Mini-batch size. Note that depending on the batch-type this either refers to '
'words or sentences.'
'Sentence: each batch contains X sentences, number of words varies. '
'Word: each batch contains (approximately) X words, number of sentences varies. '
'Default: %(default)s.')
params.add_argument("--batch-type",
type=str,
default=C.BATCH_TYPE_WORD,
choices=[C.BATCH_TYPE_SENTENCE, C.BATCH_TYPE_WORD],
help="Sentence: each batch contains X sentences, number of words varies."
"Word: each batch contains (approximately) X target words, "
"number of sentences varies. Default: %(default)s.")
def add_training_args(params):
train_params = params.add_argument_group("Training parameters")
add_batch_args(train_params)
train_params.add_argument('--decoder-only',
action='store_true',
help='Pre-train a decoder. This is currently for RNN decoders only. '
'Default: %(default)s.')
train_params.add_argument('--fill-up',
type=str,
default=C.FILL_UP_DEFAULT,
choices=C.FILL_UP_CHOICES,
help=argparse.SUPPRESS)
train_params.add_argument('--loss',
default=C.CROSS_ENTROPY,
choices=[C.CROSS_ENTROPY],
help='Loss to optimize. Default: %(default)s.')
train_params.add_argument('--label-smoothing',
default=0.1,
type=float,
help='Smoothing constant for label smoothing. Default: %(default)s.')
train_params.add_argument('--loss-normalization-type',
default=C.LOSS_NORM_VALID,
choices=[C.LOSS_NORM_VALID, C.LOSS_NORM_BATCH],
help='How to normalize the loss. By default loss is normalized by the number '
'of valid (non-PAD) tokens (%s).' % C.LOSS_NORM_VALID)
train_params.add_argument('--metrics',
nargs='+',
default=[C.PERPLEXITY],
choices=[C.PERPLEXITY, C.ACCURACY],
help='Names of metrics to track on training and validation data. Default: %(default)s.')
train_params.add_argument('--optimized-metric',
default=C.PERPLEXITY,
choices=C.METRICS,
help='Metric to optimize with early stopping {%(choices)s}. Default: %(default)s.')
train_params.add_argument('--min-updates',
type=int,
default=None,
help='Minimum number of updates before training can stop. Default: %(default)s.')
train_params.add_argument('--max-updates',
type=int,
default=None,
help='Maximum number of updates. Default: %(default)s.')
train_params.add_argument('--min-samples',
type=int,
default=None,
help='Minimum number of samples before training can stop. Default: %(default)s.')
train_params.add_argument('--max-samples',
type=int,
default=None,
help='Maximum number of samples. Default: %(default)s.')
train_params.add_argument(C.TRAIN_ARGS_CHECKPOINT_FREQUENCY,
type=int_greater_or_equal(1),
default=4000,
help='Checkpoint and evaluate every x updates/batches. Default: %(default)s.')
train_params.add_argument('--max-num-checkpoint-not-improved',
type=int,
default=32,
help='Maximum number of checkpoints the model is allowed to not improve in '
'<optimized-metric> on validation data before training is stopped. '
'Default: %(default)s.')
train_params.add_argument('--min-num-epochs',
type=int,
default=None,
help='Minimum number of epochs (passes through the training data) '
'before training can stop. Default: %(default)s.')
train_params.add_argument('--max-num-epochs',
type=int,
default=None,
help='Maximum number of epochs (passes through the training data) Default: %(default)s.')
train_params.add_argument('--embed-dropout',
type=multiple_values(2, data_type=float),
default=(.0, .0),
help='Dropout probability for source & target embeddings. Use "x:x" to specify '
'separate values. Default: %(default)s.')
train_params.add_argument('--rnn-dropout-inputs',
type=multiple_values(2, data_type=float),
default=(.0, .0),
help='RNN variational dropout probability for encoder & decoder RNN inputs. (Gal, 2015)'
'Use "x:x" to specify separate values. Default: %(default)s.')
train_params.add_argument('--rnn-dropout-states',
type=multiple_values(2, data_type=float),
default=(.0, .0),
help='RNN variational dropout probability for encoder & decoder RNN states. (Gal, 2015)'
'Use "x:x" to specify separate values. Default: %(default)s.')
train_params.add_argument('--rnn-dropout-recurrent',
type=multiple_values(2, data_type=float),
default=(.0, .0),
help='Recurrent dropout without memory loss (Semeniuta, 2016) for encoder & decoder '
'LSTMs. Use "x:x" to specify separate values. Default: %(default)s.')
train_params.add_argument('--rnn-no-attention',
action="store_true",
help='Disable attention mechanism,')
train_params.add_argument('--rnn-enc-last-hidden-concat-to-embedding',
action="store_true",
help='Concatenate the last hidden layer of the encoder to the input of the decoder, '
'instead of the previous state of the decoder. Default: %(default)s.')
train_params.add_argument('--rnn-decoder-hidden-dropout',
type=float,
default=.2,
help='Dropout probability for hidden state that combines the context with the '
'RNN hidden state in the decoder. Default: %(default)s.')
train_params.add_argument('--transformer-dropout-attention',
type=float,
default=0.1,
help='Dropout probability for multi-head attention. Default: %(default)s.')
train_params.add_argument('--transformer-dropout-act',
type=float,
default=0.1,
help='Dropout probability before activation in feed-forward block. Default: %(default)s.')
train_params.add_argument('--transformer-dropout-prepost',
type=float,
default=0.1,
help='Dropout probability for pre/postprocessing blocks. Default: %(default)s.')
train_params.add_argument('--conv-embed-dropout',
type=float,
default=.0,
help="Dropout probability for ConvolutionalEmbeddingEncoder. Default: %(default)s.")
train_params.add_argument('--cnn-hidden-dropout',
type=float,
default=.2,
help="Dropout probability for dropout between convolutional layers. Default: %(default)s.")
train_params.add_argument('--optimizer',
default=C.OPTIMIZER_ADAM,
choices=C.OPTIMIZERS,
help='SGD update rule. Default: %(default)s.')
train_params.add_argument('--optimizer-params',
type=simple_dict(),
default=None,
help='Additional optimizer params as dictionary. Format: key1:value1,key2:value2,...')
train_params.add_argument("--kvstore",
type=str,
default=C.KVSTORE_DEVICE,
choices=C.KVSTORE_TYPES,
help="The MXNet kvstore to use. 'device' is recommended for single process training. "
"Use any of 'dist_sync', 'dist_device_sync' and 'dist_async' for distributed "
"training. Default: %(default)s.")
train_params.add_argument("--gradient-compression-type",
type=str,
default=C.GRADIENT_COMPRESSION_NONE,
choices=C.GRADIENT_COMPRESSION_TYPES,
help='Type of gradient compression to use. Default: %(default)s.')
train_params.add_argument("--gradient-compression-threshold",
type=float,
default=0.5,
help="Threshold for gradient compression if --gctype is '2bit'. Default: %(default)s.")
train_params.add_argument('--weight-init',
type=str,
default=C.INIT_XAVIER,
choices=C.INIT_TYPES,
help='Type of base weight initialization. Default: %(default)s.')
train_params.add_argument('--weight-init-scale',
type=float,
default=3.0,
help='Weight initialization scale. Applies to uniform (scale) and xavier (magnitude). '
'Default: %(default)s.')
train_params.add_argument('--weight-init-xavier-factor-type',
type=str,
default=C.INIT_XAVIER_FACTOR_TYPE_AVG,
choices=C.INIT_XAVIER_FACTOR_TYPES,
help='Xavier factor type. Default: %(default)s.')
train_params.add_argument('--weight-init-xavier-rand-type',
type=str,
default=C.RAND_TYPE_UNIFORM,
choices=[C.RAND_TYPE_UNIFORM, C.RAND_TYPE_GAUSSIAN],
help='Xavier random number generator type. Default: %(default)s.')
train_params.add_argument('--embed-weight-init',
type=str,
default=C.EMBED_INIT_DEFAULT,
choices=C.EMBED_INIT_TYPES,
help='Type of embedding matrix weight initialization. If normal, initializes embedding '
'weights using a normal distribution with std=1/srqt(vocab_size). '
'Default: %(default)s.')
train_params.add_argument('--initial-learning-rate',
type=float,
default=0.0002,
help='Initial learning rate. Default: %(default)s.')
train_params.add_argument('--weight-decay',
type=float,
default=0.0,
help='Weight decay constant. Default: %(default)s.')
train_params.add_argument('--momentum',
type=float,
default=None,
help='Momentum constant. Default: %(default)s.')
train_params.add_argument('--gradient-clipping-threshold',
type=float,
default=1.0,
help='Clip absolute gradients values greater than this value. '
'Set to negative to disable. Default: %(default)s.')
train_params.add_argument('--gradient-clipping-type',
choices=C.GRADIENT_CLIPPING_TYPES,
default=C.GRADIENT_CLIPPING_TYPE_NONE,
help='The type of gradient clipping. Default: %(default)s.')
train_params.add_argument('--learning-rate-scheduler-type',
default=C.LR_SCHEDULER_PLATEAU_REDUCE,
choices=C.LR_SCHEDULERS,
help='Learning rate scheduler type. Default: %(default)s.')
train_params.add_argument('--learning-rate-reduce-factor',
type=float,
default=0.7,
help="Factor to multiply learning rate with "
"(for 'plateau-reduce' learning rate scheduler). Default: %(default)s.")
train_params.add_argument('--learning-rate-reduce-num-not-improved',
type=int,
default=8,
help="For 'plateau-reduce' learning rate scheduler. Adjust learning rate "
"if <optimized-metric> did not improve for x checkpoints. Default: %(default)s.")
train_params.add_argument('--learning-rate-schedule',
type=learning_schedule(),
default=None,
help="For 'fixed-step' scheduler. Fully specified learning schedule in the form"
" \"rate1:num_updates1[,rate2:num_updates2,...]\". Overrides all other args related"
" to learning rate and stopping conditions. Default: %(default)s.")
train_params.add_argument('--learning-rate-half-life',
type=float,
default=10,
help="Half-life of learning rate in checkpoints. For 'fixed-rate-*' "
"learning rate schedulers. Default: %(default)s.")
train_params.add_argument('--learning-rate-warmup',
type=int,
default=0,
help="Number of warmup steps. If set to x, linearly increases learning rate from 10%% "
"to 100%% of the initial learning rate. Default: %(default)s.")
train_params.add_argument('--learning-rate-decay-param-reset',
action='store_true',
help='Resets model parameters to current best when learning rate is reduced due to the '
'value of --learning-rate-reduce-num-not-improved. Default: %(default)s.')
train_params.add_argument('--learning-rate-decay-optimizer-states-reset',
choices=C.LR_DECAY_OPT_STATES_RESET_CHOICES,
default=C.LR_DECAY_OPT_STATES_RESET_OFF,
help="Action to take on optimizer states (e.g. Adam states) when learning rate is "
"reduced due to the value of --learning-rate-reduce-num-not-improved. "
"Default: %(default)s.")
train_params.add_argument('--rnn-forget-bias',
default=0.0,
type=float,
help='Initial value of RNN forget biases.')
train_params.add_argument('--rnn-h2h-init', type=str, default=C.RNN_INIT_ORTHOGONAL,
choices=[C.RNN_INIT_ORTHOGONAL, C.RNN_INIT_ORTHOGONAL_STACKED, C.RNN_INIT_DEFAULT],
help="Initialization method for RNN parameters. Default: %(default)s.")
train_params.add_argument('--fixed-param-names',
default=[],
nargs='*',
help="Names of parameters to fix at training time. Default: %(default)s.")
train_params.add_argument(C.TRAIN_ARGS_MONITOR_BLEU,
default=500,
type=int,
help='x>0: decode x sampled sentences from validation data and '
'compute evaluation metrics. x==-1: use full validation data. Default: %(default)s.')
train_params.add_argument('--decode-and-evaluate-use-cpu',
action='store_true',
help='Use CPU for decoding validation data. Overrides --decode-and-evaluate-device-id. '
'Default: %(default)s.')
train_params.add_argument('--decode-and-evaluate-device-id',
default=None,
type=int,
help='Separate device for decoding validation data. '
'Use a negative number to automatically acquire a GPU. '
'Use a positive number to acquire a specific GPU. Default: %(default)s.')
train_params.add_argument('--seed',
type=int,
default=13,
help='Random seed. Default: %(default)s.')
train_params.add_argument('--keep-last-params',
type=int,
default=-1,
help='Keep only the last n params files, use -1 to keep all files. Default: %(default)s')
train_params.add_argument('--keep-initializations',
action="store_true",
help='In addition to keeping the last n params files, also keep params from checkpoint 0.')
train_params.add_argument('--dry-run',
action='store_true',
help="Do not perform any actual training, but print statistics about the model"
" and mode of operation.")
def add_train_cli_args(params):
add_training_io_args(params)
add_model_parameters(params)
add_training_args(params)
add_device_args(params)
add_logging_args(params)
def add_translate_cli_args(params):
add_inference_args(params)
add_device_args(params)
add_logging_args(params)
def add_score_cli_args(params):
add_training_data_args(params, required=False)
add_vocab_args(params)
add_device_args(params)
add_logging_args(params)
add_batch_args(params, default_batch_size=500)
params = params.add_argument_group("Scoring parameters")
params.add_argument("--model", "-m", required=True,
help="Model directory containing trained model.")
params.add_argument('--max-seq-len',
type=multiple_values(num_values=2, greater_or_equal=1),
default=None,
help='Maximum sequence length in tokens.'
'Use "x:x" to specify separate values for src&tgt. Default: Read from model.')
params.add_argument('--length-penalty-alpha',
default=1.0,
type=float,
help='Alpha factor for the length penalty used in scoring: '
'(beta + len(Y))**alpha/(beta + 1)**alpha. A value of 0.0 will therefore turn off '
'length normalization. Default: %(default)s')
params.add_argument('--length-penalty-beta',
default=0.0,
type=float,
help='Beta factor for the length penalty used in scoring: '
'(beta + len(Y))**alpha/(beta + 1)**alpha. Default: %(default)s')
params.add_argument('--softmax-temperature',
type=float,
default=None,
help='Controls peakiness of model predictions. Values < 1.0 produce '
'peaked predictions, values > 1.0 produce smoothed distributions.')
params.add_argument("--output", "-o", default=None,
help="File to write output to. Default: STDOUT.")
params.add_argument('--output-type',
default=C.OUTPUT_HANDLER_SCORE,
choices=C.OUTPUT_HANDLERS_SCORING,
help='Output type. Default: %(default)s.')
params.add_argument('--score-type',
choices=C.SCORING_TYPE_CHOICES,
default=C.SCORING_TYPE_DEFAULT,
help='Score type to output. Default: %(default)s')
def add_max_output_cli_args(params):
params.add_argument('--max-output-length',
type=int,
default=None,
help='Maximum number of words to generate during translation. '
'If None, it will be computed automatically. Default: %(default)s.')
def add_inference_args(params):
decode_params = params.add_argument_group("Inference parameters")
decode_params.add_argument(C.INFERENCE_ARG_INPUT_LONG, C.INFERENCE_ARG_INPUT_SHORT,
default=None,
help='Input file to translate. One sentence per line. '
'If not given, will read from stdin.')
decode_params.add_argument(C.INFERENCE_ARG_INPUT_FACTORS_LONG, C.INFERENCE_ARG_INPUT_FACTORS_SHORT,
required=False,
nargs='+',
type=regular_file(),
default=None,
help='List of input files containing additional source factors,'
'each token-parallel to the source. Default: %(default)s.')
decode_params.add_argument('--json-input',
action='store_true',
default=False,
help="If given, the CLI expects string-serialized json objects as input."
"Requires at least the input text field, for example: "
"{'text': 'some input string'} "
"Optionally, a list of factors can be provided: "
"{'text': 'some input string', 'factors': ['C C C', 'X X X']}.")
decode_params.add_argument(C.INFERENCE_ARG_OUTPUT_LONG, C.INFERENCE_ARG_OUTPUT_SHORT,
default=None,
help='Output file to write translations to. '
'If not given, will write to stdout.')
decode_params.add_argument('--models', '-m',
required=True,
nargs='+',
help='Model folder(s). Use multiple for ensemble decoding. '
'Model determines config, best parameters and vocab files.')
decode_params.add_argument('--checkpoints', '-c',
default=None,
type=int,
nargs='+',
help='If not given, chooses best checkpoints for model(s). '
'If specified, must have the same length as --models and be integer')
decode_params.add_argument('--nbest-size',
type=int_greater_or_equal(1),
default=1,
help='Size of the nbest list of translations. Default: %(default)s.')
decode_params.add_argument('--beam-size', '-b',
type=int_greater_or_equal(1),
default=5,
help='Size of the beam. Default: %(default)s.')
decode_params.add_argument('--beam-prune', '-p',
type=float,
default=0,
help='Pruning threshold for beam search. All hypotheses with scores not within '
'this amount of the best finished hypothesis are discarded (0 = off). '
'Default: %(default)s.')
decode_params.add_argument('--beam-search-stop',
choices=[C.BEAM_SEARCH_STOP_ALL, C.BEAM_SEARCH_STOP_FIRST],
default=C.BEAM_SEARCH_STOP_ALL,
help='Stopping criteria. Quit when (all) hypotheses are finished '
'or when a finished hypothesis is in (first) position. Default: %(default)s.')
decode_params.add_argument('--batch-size',
type=int_greater_or_equal(1),
default=1,
help='Batch size during decoding. Determines how many sentences are translated '
'simultaneously. Default: %(default)s.')
decode_params.add_argument('--chunk-size',
type=int_greater_or_equal(1),
default=None,
help='Size of the chunks to be read from input at once. The chunks are sorted and then '
'split into batches. Therefore the larger the chunk size the better the grouping '
'of segments of similar length and therefore the higher the increase in throughput.'
' Default: %d without batching '
'and %d * batch_size with batching.' % (C.CHUNK_SIZE_NO_BATCHING,
C.CHUNK_SIZE_PER_BATCH_SEGMENT))
decode_params.add_argument('--skip-topk',
default=False,
action='store_true',
help='Use argmax instead of topk for greedy decoding (when --beam-size 1).'
'Default: %(default)s.')
decode_params.add_argument('--sample',
type=int_greater_or_equal(0),
default=None,
nargs='?',
const=0,
help='Sample from softmax instead of taking best. Optional argument will restrict '
'sampling to top N vocabulary items at each step. Default: %(default)s.')
decode_params.add_argument('--seed',
type=int,
default=None,
help='Random seed used if sampling. Default: %(default)s.')
decode_params.add_argument('--ensemble-mode',
type=str,
default='linear',
choices=['linear', 'log_linear'],
help='Ensemble mode. Default: %(default)s.')
decode_params.add_argument('--bucket-width',
type=int_greater_or_equal(0),
default=10,
help='Bucket width for encoder steps. 0 means no bucketing. Default: %(default)s.')
decode_params.add_argument('--max-input-len', '-n',
type=int,
default=None,
help='Maximum input sequence length. Default: value from model(s).')
decode_params.add_argument('--softmax-temperature',
type=float,
default=None,
help='Controls peakiness of model predictions. Values < 1.0 produce '
'peaked predictions, values > 1.0 produce smoothed distributions.')
decode_params.add_argument('--max-output-length-num-stds',
type=int,
default=C.DEFAULT_NUM_STD_MAX_OUTPUT_LENGTH,
help='Number of target-to-source length ratio standard deviations from training to add '
'to calculate maximum output length for beam search for each sentence. '
'Default: %(default)s.')
decode_params.add_argument('--restrict-lexicon',
type=str,
default=None,
help="Specify top-k lexicon to restrict output vocabulary based on source. See lexicon "
"module. Default: %(default)s.")
decode_params.add_argument('--restrict-lexicon-topk',
type=int,
default=None,
help="Specify the number of translations to load for each source word from the lexicon "
"given with --restrict-lexicon. Default: Load all entries from the lexicon.")
decode_params.add_argument('--avoid-list',
type=str,
default=None,
help="Specify a file containing phrases (pre-processed, one per line) to block "
"from the output. Default: %(default)s.")
decode_params.add_argument('--strip-unknown-words',
action='store_true',
default=False,
help='Remove any <unk> symbols from outputs. Default: %(default)s.')
decode_params.add_argument('--output-type',
default='translation',
choices=C.OUTPUT_HANDLERS,
help='Output type. Default: %(default)s.')
decode_params.add_argument('--sure-align-threshold',
default=0.9,
type=float,
help='Threshold to consider a soft alignment a sure alignment. Default: %(default)s')
decode_params.add_argument('--length-penalty-alpha',
default=1.0,
type=float,
help='Alpha factor for the length penalty used in beam search: '
'(beta + len(Y))**alpha/(beta + 1)**alpha. A value of 0.0 will therefore turn off '
'length normalization. Default: %(default)s')
decode_params.add_argument('--length-penalty-beta',
default=0.0,
type=float,
help='Beta factor for the length penalty used in beam search: '
'(beta + len(Y))**alpha/(beta + 1)**alpha. Default: %(default)s')
decode_params.add_argument('--override-dtype',
default=None,
type=str,
help='EXPERIMENTAL: may be changed or removed in future. Overrides training dtype of '
'encoders and decoders during inference. Default: %(default)s')
def add_evaluate_args(params):
eval_params = params.add_argument_group("Evaluate parameters")
eval_params.add_argument('--references', '-r',
required=True,
type=str,
help="File with references.")
eval_params.add_argument('--hypotheses', '-i',
type=file_or_stdin(),
default=[sys.stdin],
nargs='+',
help="File(s) with hypotheses. If none will read from stdin. Default: stdin.")
eval_params.add_argument('--metrics',
nargs='+',
choices=C.EVALUATE_METRICS,
default=[C.BLEU, C.CHRF],
help='List of metrics to compute. Default: %(default)s.')
eval_params.add_argument('--sentence', '-s',
action="store_true",
help="Show sentence-level metrics. Default: %(default)s.")
eval_params.add_argument('--offset',
type=float,
default=0.01,
help="Numerical value of the offset of zero n-gram counts for BLEU. Default: %(default)s.")
eval_params.add_argument('--not-strict', '-n',
action="store_true",
help="Do not fail if number of hypotheses does not match number of references. "
"Default: %(default)s.")
def add_build_vocab_args(params):
params.add_argument('-i', '--inputs', required=True, nargs='+', help='List of text files to build vocabulary from.')
params.add_argument('-o', '--output', required=True, type=str, help="Output filename to write vocabulary to.")
add_vocab_args(params)
def add_init_embedding_args(params):
params.add_argument('--weight-files', '-w', required=True, nargs='+',
help='List of input weight files in .npy, .npz or Sockeye parameter format.')
params.add_argument('--vocabularies-in', '-i', required=True, nargs='+',
help='List of input vocabularies as token-index dictionaries in .json format.')
params.add_argument('--vocabularies-out', '-o', required=True, nargs='+',
help='List of output vocabularies as token-index dictionaries in .json format.')
params.add_argument('--names', '-n', nargs='+',
help='List of Sockeye parameter names for (embedding) weights. Default: %(default)s.',
default=[n + "weight" for n in [C.SOURCE_EMBEDDING_PREFIX, C.TARGET_EMBEDDING_PREFIX]])
params.add_argument('--file', '-f', required=True,
help='File to write initialized parameters to.')
params.add_argument('--encoding', '-c', type=str, default=C.VOCAB_ENCODING,
help='Open input vocabularies with specified encoding. Default: %(default)s.')
| _parse |
easy.rs | //! Stream wrapper which provides an informative and easy to use error type.
//!
//! Unless you have specific constraints preventing you from using this error type (such as being
//! a `no_std` environment) you probably want to use this stream type. It can easily be used
//! through the [`Parser::easy_parse`][] method.
//!
//! The provided `Errors` type is roughly the same as `ParseError` in combine 1.x and 2.x.
//!
//! ```
//! #[macro_use]
//! extern crate combine;
//! use combine::{easy, Parser, Stream, many1};
//! use combine::parser::char::letter;
//! use combine::stream::StreamErrorFor;
//! use combine::error::{ParseError, StreamError};
//!
//! fn main() {
//! parser!{
//! fn parser[I]()(I) -> String
//! where [
//! I: Stream<Item=char, Error = easy::ParseError<I>>,
//! // If we want to use the error type explicitly we need to help rustc infer
//! // `StreamError` to `easy::Error` (rust-lang/rust#24159)
//! I::Error: ParseError<
//! I::Item,
//! I::Range,
//! I::Position,
//! StreamError = easy::Error<I::Item, I::Range>
//! >
//! ]
//! {
//! many1(letter()).and_then(|word: String| {
//! if word == "combine" {
//! Ok(word)
//! } else {
//! Err(easy::Error::Expected(easy::Info::Borrowed("combine")))
//! }
//! })
//! }
//! }
//!
//! parser!{
//! fn parser2[I]()(I) -> String
//! where [
//! I: Stream<Item=char>,
//! ]
//! {
//! many1(letter()).and_then(|word: String| {
//! if word == "combine" {
//! Ok(word)
//! } else {
//! // Alternatively it is possible to only use the methods provided by the
//! // `StreamError` trait.
//! // In that case the extra bound is not necessary (and this method will work
//! // for other errors than `easy::Errors`)
//! Err(StreamErrorFor::<I>::expected_static_message("combine"))
//! }
//! })
//! }
//! }
//!
//! let input = "combin";
//! let expected_error = Err(easy::Errors {
//! errors: vec![
//! easy::Error::Expected("combine".into())
//! ],
//! position: 0,
//! });
//! assert_eq!(
//! parser().easy_parse(input).map_err(|err| err.map_position(|p| p.translate_position(input))),
//! expected_error
//! );
//! assert_eq!(
//! parser2().easy_parse(input).map_err(|err| err.map_position(|p| p.translate_position(input))),
//! expected_error
//! );
//! }
//!
//! ```
//!
//! [`Parser::easy_parse`]: ../parser/trait.Parser.html#method.easy_parse
use std::any::Any;
use std::error::Error as StdError;
use std::fmt;
use error::{FastResult, Info as PrimitiveInfo, StreamError, Tracked};
use stream::{FullRangeStream, Positioned, RangeStream, RangeStreamOnce, Resetable, StreamErrorFor,
StreamOnce};
/// Enum holding error information. Variants are defined for `Stream::Item` and `Stream::Range` as
/// well as string variants holding easy descriptions.
///
/// As there is implementations of `From` for `String` and `&'static str` the
/// constructor need not be used directly as calling `msg.into()` should turn a message into the
/// correct `Info` variant.
#[derive(Clone, Debug)]
pub enum Info<T, R> {
Token(T),
Range(R),
Owned(String),
Borrowed(&'static str),
}
impl<T, R> From<PrimitiveInfo<T, R>> for Info<T, R> {
fn from(info: PrimitiveInfo<T, R>) -> Self {
match info {
PrimitiveInfo::Token(b) => Info::Token(b),
PrimitiveInfo::Range(b) => Info::Range(b),
PrimitiveInfo::Borrowed(b) => Info::Borrowed(b),
}
}
}
impl<T, R> Info<T, R> {
pub fn map_token<F, U>(self, f: F) -> Info<U, R>
where
F: FnOnce(T) -> U,
{
use self::Info::*;
match self {
Token(t) => Token(f(t)),
Range(r) => Range(r),
Owned(s) => Owned(s),
Borrowed(x) => Borrowed(x),
}
}
pub fn map_range<F, S>(self, f: F) -> Info<T, S>
where
F: FnOnce(R) -> S,
{
use self::Info::*;
match self {
Token(t) => Token(t),
Range(r) => Range(f(r)),
Owned(s) => Owned(s),
Borrowed(x) => Borrowed(x),
}
}
}
impl<T: PartialEq, R: PartialEq> PartialEq for Info<T, R> {
fn eq(&self, other: &Info<T, R>) -> bool {
match (self, other) {
(&Info::Token(ref l), &Info::Token(ref r)) => l == r,
(&Info::Range(ref l), &Info::Range(ref r)) => l == r,
(&Info::Owned(ref l), &Info::Owned(ref r)) => l == r,
(&Info::Borrowed(l), &Info::Owned(ref r)) => l == r,
(&Info::Owned(ref l), &Info::Borrowed(r)) => l == r,
(&Info::Borrowed(l), &Info::Borrowed(r)) => l == r,
_ => false,
}
}
}
impl<T: fmt::Display, R: fmt::Display> fmt::Display for Info<T, R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Info::Token(ref c) => write!(f, "{}", c),
Info::Range(ref c) => write!(f, "{}", c),
Info::Owned(ref s) => write!(f, "{}", s),
Info::Borrowed(s) => write!(f, "{}", s),
}
}
}
impl<R> From<char> for Info<char, R> {
fn from(s: char) -> Info<char, R> {
Info::Token(s)
}
}
impl<T, R> From<String> for Info<T, R> {
fn from(s: String) -> Info<T, R> {
Info::Owned(s)
}
}
impl<T, R> From<&'static str> for Info<T, R> {
fn from(s: &'static str) -> Info<T, R> {
Info::Borrowed(s)
}
}
impl<R> From<u8> for Info<u8, R> {
fn from(s: u8) -> Info<u8, R> {
Info::Token(s)
}
}
/// Enum used to store information about an error that has occurred during parsing.
#[derive(Debug)]
pub enum Error<T, R> {
/// Error indicating an unexpected token has been encountered in the stream
Unexpected(Info<T, R>),
/// Error indicating that the parser expected something else
Expected(Info<T, R>),
/// Generic message
Message(Info<T, R>),
/// Variant for containing other types of errors
Other(Box<StdError + Send + Sync>),
}
impl<Item, Range> StreamError<Item, Range> for Error<Item, Range>
where
Item: PartialEq,
Range: PartialEq,
{
#[inline]
fn unexpected_token(token: Item) -> Self {
Error::Unexpected(Info::Token(token))
}
#[inline]
fn unexpected_range(token: Range) -> Self {
Error::Unexpected(Info::Range(token))
}
#[inline]
fn unexpected_message<T>(msg: T) -> Self
where
T: fmt::Display,
{
Error::Unexpected(Info::Owned(msg.to_string()))
}
#[inline]
fn unexpected_static_message(msg: &'static str) -> Self {
Error::Unexpected(Info::Borrowed(msg))
}
#[inline]
fn expected_token(token: Item) -> Self {
Error::Expected(Info::Token(token))
}
#[inline]
fn expected_range(token: Range) -> Self {
Error::Expected(Info::Range(token))
}
#[inline]
fn expected_message<T>(msg: T) -> Self
where
T: fmt::Display,
{
Error::Expected(Info::Owned(msg.to_string()))
}
#[inline]
fn expected_static_message(msg: &'static str) -> Self {
Error::Expected(Info::Borrowed(msg))
}
#[inline]
fn message_message<T>(msg: T) -> Self
where
T: fmt::Display,
{
Error::Message(Info::Owned(msg.to_string()))
}
#[inline]
fn message_static_message(msg: &'static str) -> Self {
Error::Message(Info::Borrowed(msg))
}
#[inline]
fn message_token(token: Item) -> Self {
Error::Message(Info::Token(token))
}
#[inline]
fn message_range(token: Range) -> Self {
Error::Message(Info::Range(token))
}
#[inline]
fn other<E>(err: E) -> Self
where
E: StdError + Send + Sync + 'static,
{
err.into()
}
#[inline]
fn into_other<T>(self) -> T
where
T: StreamError<Item, Range>,
{
match self {
Error::Unexpected(info) => match info {
Info::Token(x) => T::unexpected_token(x),
Info::Range(x) => T::unexpected_range(x),
Info::Borrowed(x) => T::unexpected_static_message(x),
Info::Owned(x) => T::unexpected_message(x),
},
Error::Expected(info) => match info {
Info::Token(x) => T::expected_token(x),
Info::Range(x) => T::expected_range(x),
Info::Borrowed(x) => T::expected_static_message(x),
Info::Owned(x) => T::expected_message(x),
},
Error::Message(info) => match info {
Info::Token(x) => T::expected_token(x),
Info::Range(x) => T::expected_range(x),
Info::Borrowed(x) => T::expected_static_message(x),
Info::Owned(x) => T::expected_message(x),
},
Error::Other(err) => T::message_message(err),
}
}
}
impl<Item, Range, Position> ::error::ParseError<Item, Range, Position> for Error<Item, Range>
where
Item: PartialEq,
Range: PartialEq,
Position: Default,
{
type StreamError = Self;
#[inline]
fn empty(_: Position) -> Self {
Self::message_static_message("")
}
#[inline]
fn from_error(_: Position, err: Self::StreamError) -> Self {
err
}
#[inline]
fn set_position(&mut self, _position: Position) {}
#[inline]
fn add(&mut self, err: Self::StreamError) {
*self = err;
}
#[inline]
fn set_expected<F>(self_: &mut Tracked<Self>, info: Self::StreamError, f: F)
where
F: FnOnce(&mut Tracked<Self>),
{
f(self_);
self_.error = info;
}
fn is_unexpected_end_of_input(&self) -> bool {
*self == Self::end_of_input()
}
#[inline]
fn into_other<T>(self) -> T
where
T: ::error::ParseError<Item, Range, Position>,
{
T::from_error(Position::default(), StreamError::into_other(self))
}
}
impl<Item, Range, Position> ::error::ParseError<Item, Range, Position>
for Errors<Item, Range, Position>
where
Item: PartialEq,
Range: PartialEq,
Position: Ord,
{
type StreamError = Error<Item, Range>;
#[inline]
fn empty(pos: Position) -> Self {
Errors::empty(pos)
}
#[inline]
fn from_error(position: Position, err: Self::StreamError) -> Self {
Self::new(position, Error::from(err))
}
#[inline]
fn set_position(&mut self, position: Position) {
self.position = position;
}
#[inline]
fn merge(self, other: Self) -> Self {
Errors::merge(self, other)
}
#[inline]
fn add(&mut self, err: Self::StreamError) {
self.add_error(err);
}
#[inline]
fn set_expected<F>(self_: &mut Tracked<Self>, info: Self::StreamError, f: F)
where
F: FnOnce(&mut Tracked<Self>),
{
let start = self_.error.errors.len();
f(self_);
// Replace all expected errors that were added from the previous add_error
// with this expected error
let mut i = 0;
self_.error.errors.retain(|e| {
if i < start {
i += 1;
true
} else {
match *e {
Error::Expected(_) => false,
_ => true,
}
}
});
self_.error.add(info);
}
fn is_unexpected_end_of_input(&self) -> bool {
self.errors.iter().any(|err| *err == Error::end_of_input())
}
#[inline]
fn into_other<T>(mut self) -> T
where
T: ::error::ParseError<Item, Range, Position>,
{
match self.errors.pop() {
Some(err) => T::from_error(self.position, StreamError::into_other(err)),
None => T::empty(self.position),
}
}
}
impl<T, R> Error<T, R> {
pub fn map_token<F, U>(self, f: F) -> Error<U, R>
where
F: FnOnce(T) -> U,
{
use self::Error::*;
match self {
Unexpected(x) => Unexpected(x.map_token(f)),
Expected(x) => Expected(x.map_token(f)),
Message(x) => Message(x.map_token(f)),
Other(x) => Other(x),
}
}
pub fn map_range<F, S>(self, f: F) -> Error<T, S>
where
F: FnOnce(R) -> S,
{
use self::Error::*;
match self {
Unexpected(x) => Unexpected(x.map_range(f)),
Expected(x) => Expected(x.map_range(f)),
Message(x) => Message(x.map_range(f)),
Other(x) => Other(x),
}
}
}
impl<T: PartialEq, R: PartialEq> PartialEq for Error<T, R> {
fn eq(&self, other: &Error<T, R>) -> bool {
match (self, other) {
(&Error::Unexpected(ref l), &Error::Unexpected(ref r))
| (&Error::Expected(ref l), &Error::Expected(ref r))
| (&Error::Message(ref l), &Error::Message(ref r)) => l == r,
_ => false,
}
}
}
impl<T, R, E> From<E> for Error<T, R>
where
E: StdError + 'static + Send + Sync,
{
fn from(e: E) -> Error<T, R> {
Error::Other(Box::new(e))
}
}
impl<T, R> Error<T, R> {
/// Returns the `end_of_input` error.
pub fn end_of_input() -> Error<T, R> {
Error::Unexpected("end of input".into())
}
/// Formats a slice of errors in a human readable way.
///
/// ```rust
/// # extern crate combine;
/// # use combine::*;
/// # use combine::parser::char::*;
/// # use combine::stream::state::{State, SourcePosition};
///
/// # fn main() {
/// let input = r"
/// ,123
/// ";
/// let result = spaces().with(char('.').or(char('a')).or(digit()))
/// .easy_parse(State::new(input));
/// let m = format!("{}", result.unwrap_err());
/// let expected = r"Parse error at line: 2, column: 3
/// Unexpected `,`
/// Expected `.`, `a` or `digit`
/// ";
/// assert_eq!(m, expected);
/// # }
/// ```
pub fn fmt_errors(errors: &[Error<T, R>], f: &mut fmt::Formatter) -> fmt::Result
where
T: fmt::Display,
R: fmt::Display,
{
// First print the token that we did not expect
// There should really just be one unexpected message at this point though we print them
// all to be safe
let unexpected = errors.iter().filter(|e| match **e {
Error::Unexpected(_) => true,
_ => false,
});
for error in unexpected {
try!(writeln!(f, "{}", error));
}
// Then we print out all the things that were expected in a comma separated list
// 'Expected 'a', 'expression' or 'let'
let iter = || {
errors.iter().filter_map(|e| match *e {
Error::Expected(ref err) => Some(err),
_ => None,
})
};
let expected_count = iter().count();
for (i, message) in iter().enumerate() {
let s = match i {
0 => "Expected",
_ if i < expected_count - 1 => ",",
// Last expected message to be written
_ => " or",
};
try!(write!(f, "{} `{}`", s, message));
}
if expected_count != 0 {
try!(writeln!(f, ""));
}
// If there are any generic messages we print them out last
let messages = errors.iter().filter(|e| match **e {
Error::Message(_) | Error::Other(_) => true,
_ => false,
});
for error in messages {
try!(writeln!(f, "{}", error));
}
Ok(())
}
}
/// Convenience alias over `Errors` for `StreamOnce` types which makes it possible to specify the
/// `Errors` type from a `StreamOnce` by writing `ParseError<I>` instead of `Errors<I::Item,
/// I::Range, I::Position>`
pub type ParseError<S> =
Errors<<S as StreamOnce>::Item, <S as StreamOnce>::Range, <S as StreamOnce>::Position>;
/// Struct which hold information about an error that occurred at a specific position.
/// Can hold multiple instances of `Error` if more that one error occurred in the same position.
#[derive(Debug, PartialEq)]
pub struct Errors<I, R, P> {
/// The position where the error occurred
pub position: P,
/// A vector containing specific information on what errors occurred at `position`. Usually
/// a fully formed message contains one `Unexpected` error and one or more `Expected` errors.
/// `Message` and `Other` may also appear (`combine` never generates these errors on its own)
/// and may warrant custom handling.
pub errors: Vec<Error<I, R>>,
}
impl<I, R, P> Errors<I, R, P> {
/// Constructs a new `ParseError` which occurred at `position`.
#[inline]
pub fn new(position: P, error: Error<I, R>) -> Errors<I, R, P> {
Self::from_errors(position, vec![error])
}
/// Constructs an error with no other information than the position it occurred at.
#[inline]
pub fn empty(position: P) -> Errors<I, R, P> {
Self::from_errors(position, vec![])
}
/// Constructs a `ParseError` with multiple causes.
#[inline]
pub fn from_errors(position: P, errors: Vec<Error<I, R>>) -> Errors<I, R, P> {
Errors {
position: position,
errors: errors,
}
}
/// Constructs an end of input error. Should be returned by parsers which encounter end of
/// input unexpectedly.
#[inline]
pub fn end_of_input(position: P) -> Errors<I, R, P> {
Self::new(position, Error::end_of_input())
}
/// Adds an error if `error` does not exist in this `ParseError` already (as determined byte
/// `PartialEq`).
pub fn add_error(&mut self, error: Error<I, R>)
where
I: PartialEq,
R: PartialEq,
{
// Don't add duplicate errors
if self.errors.iter().all(|err| *err != error) {
self.errors.push(error);
}
}
/// Removes all `Expected` errors in `self` and adds `info` instead.
pub fn set_expected(&mut self, info: Info<I, R>) {
// Remove all other expected messages
self.errors.retain(|e| match *e {
Error::Expected(_) => false,
_ => true,
});
self.errors.push(Error::Expected(info));
}
/// Merges two `ParseError`s. If they exist at the same position the errors of `other` are
/// added to `self` (using `add_error` to skip duplicates). If they are not at the same
/// position the error furthest ahead are returned, ignoring the other `ParseError`.
pub fn merge(mut self, mut other: Errors<I, R, P>) -> Errors<I, R, P>
where
P: Ord,
I: PartialEq,
R: PartialEq,
{
use std::cmp::Ordering;
// Only keep the errors which occurred after consuming the most amount of data
match self.position.cmp(&other.position) {
Ordering::Less => other,
Ordering::Greater => self,
Ordering::Equal => {
for message in other.errors.drain(..) {
self.add_error(message);
}
self
}
}
}
/// Maps the position to a new value
pub fn map_position<F, Q>(self, f: F) -> Errors<I, R, Q>
where
F: FnOnce(P) -> Q,
{
Errors::from_errors(f(self.position), self.errors)
}
/// Maps all token variants to a new value
pub fn map_token<F, U>(self, mut f: F) -> Errors<U, R, P>
where
F: FnMut(I) -> U,
{
Errors::from_errors(
self.position,
self.errors
.into_iter()
.map(|error| error.map_token(&mut f))
.collect(),
)
}
/// Maps all range variants to a new value.
///
/// ```
/// use combine::Parser;
/// use combine::parser::range::range;
/// println!(
/// "{}",
/// range(&"HTTP"[..])
/// .easy_parse("HTT")
/// .unwrap_err()
/// .map_range(|bytes| format!("{:?}", bytes))
/// );
/// ```
pub fn map_range<F, S>(self, mut f: F) -> Errors<I, S, P>
where
F: FnMut(R) -> S,
{
Errors::from_errors(
self.position,
self.errors
.into_iter()
.map(|error| error.map_range(&mut f))
.collect(),
)
}
}
impl<I, R, P> StdError for Errors<I, R, P>
where
P: fmt::Display + fmt::Debug + Any,
I: fmt::Display + fmt::Debug + Any,
R: fmt::Display + fmt::Debug + Any,
{
fn description(&self) -> &str {
"parse error"
}
}
impl<I, R, P> fmt::Display for Errors<I, R, P>
where
P: fmt::Display,
I: fmt::Display,
R: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "Parse error at {}", self.position));
Error::fmt_errors(&self.errors, f)
}
}
impl<T: fmt::Display, R: fmt::Display> fmt::Display for Error<T, R> {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Unexpected(ref c) => write!(f, "Unexpected `{}`", c),
Error::Expected(ref s) => write!(f, "Expected `{}`", s),
Error::Message(ref msg) => msg.fmt(f),
Error::Other(ref err) => err.fmt(f),
}
}
}
#[derive(Copy, Clone, Debug)]
pub struct Stream<S>(pub S);
impl<S> Resetable for Stream<S>
where
S: Resetable,
{
type Checkpoint = S::Checkpoint;
fn checkpoint(&self) -> Self::Checkpoint {
self.0.checkpoint()
}
fn reset(&mut self, checkpoint: Self::Checkpoint) {
self.0.reset(checkpoint);
}
}
impl<S> StreamOnce for Stream<S>
where
S: StreamOnce + Positioned,
{
type Item = S::Item;
type Range = S::Range;
type Position = S::Position;
type Error = ParseError<S>;
#[inline]
fn uncons(&mut self) -> Result<Self::Item, StreamErrorFor<Self>> {
self.0.uncons().map_err(StreamError::into_other)
}
fn is_partial(&self) -> bool {
self.0.is_partial()
}
}
impl<S> RangeStreamOnce for Stream<S>
where
S: RangeStream,
{
#[inline]
fn uncons_range(&mut self, size: usize) -> Result<Self::Range, StreamErrorFor<Self>> {
self.0.uncons_range(size).map_err(StreamError::into_other)
}
#[inline]
fn uncons_while<F>(&mut self, f: F) -> Result<Self::Range, StreamErrorFor<Self>>
where
F: FnMut(Self::Item) -> bool,
{
self.0.uncons_while(f).map_err(StreamError::into_other)
}
#[inline]
fn uncons_while1<F>(&mut self, f: F) -> FastResult<Self::Range, StreamErrorFor<Self>>
where
F: FnMut(Self::Item) -> bool,
{
self.0.uncons_while1(f).map_err(StreamError::into_other)
}
#[inline]
fn distance(&self, end: &Self::Checkpoint) -> usize {
self.0.distance(end)
}
}
impl<S> Positioned for Stream<S>
where
S: StreamOnce + Positioned,
{
fn position(&self) -> S::Position {
self.0.position()
}
}
impl<S> FullRangeStream for Stream<S>
where
S: FullRangeStream,
{
fn range(&self) -> Self::Range {
self.0.range()
}
}
| fmt |
lib.rs | use hdk::prelude::*;
#[hdk_entry(id = "thing")]
struct Thing;
entry_defs![Thing::entry_def()];
#[hdk_extern]
fn create(_: ()) -> ExternResult<HeaderHash> {
create_entry(&Thing)
}
/// `read` seems to be a reserved worked that causes SIGSEGV invalid memory reference when used as `#[hdk_extern]`
#[hdk_extern]
fn | (header_hash: HeaderHash) -> ExternResult<Option<Element>> {
get(header_hash, GetOptions::latest())
}
#[hdk_extern]
fn delete(header_hash: HeaderHash) -> ExternResult<HeaderHash> {
delete_entry(header_hash)
}
#[cfg(test)]
pub mod test {
use hdk::prelude::*;
use ::fixt::prelude::*;
#[test]
fn create_smoke() {
let mut mock_hdk = hdk::prelude::MockHdkT::new();
let header_hash = fixt!(HeaderHash);
let closure_header_hash = header_hash.clone();
mock_hdk.expect_create()
.with(hdk::prelude::mockall::predicate::eq(
EntryWithDefId::try_from(&super::Thing).unwrap()
))
.times(1)
.return_once(move |_| Ok(closure_header_hash));
hdk::prelude::set_hdk(mock_hdk);
let result = super::create(());
assert_eq!(
result,
Ok(
header_hash
)
)
}
#[test]
fn get_smoke() {
let mut mock_hdk = hdk::prelude::MockHdkT::new();
let input_header_hash = fixt!(HeaderHash);
mock_hdk.expect_get()
.with(hdk::prelude::mockall::predicate::eq(
GetInput::new(input_header_hash.clone().into(), GetOptions::latest())
))
.times(1)
.return_once(move |_| Ok(None));
hdk::prelude::set_hdk(mock_hdk);
let result = super::reed(input_header_hash);
assert_eq!(
result,
Ok(
None
)
)
}
#[test]
fn delete_smoke() {
let mut mock_hdk = hdk::prelude::MockHdkT::new();
let input_header_hash = fixt!(HeaderHash);
let output_header_hash = fixt!(HeaderHash);
let output_header_hash_closure = output_header_hash.clone();
mock_hdk.expect_delete()
.with(hdk::prelude::mockall::predicate::eq(
input_header_hash.clone()
))
.times(1)
.return_once(move |_| Ok(output_header_hash_closure));
hdk::prelude::set_hdk(mock_hdk);
let result = super::delete(input_header_hash);
assert_eq!(
result,
Ok(
output_header_hash
)
)
}
} | reed |
elaborate_drops.rs | use crate::MirPass;
use rustc_data_structures::fx::FxHashMap;
use rustc_index::bit_set::BitSet;
use rustc_middle::mir::patch::MirPatch;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt};
use rustc_mir_dataflow::elaborate_drops::{elaborate_drop, DropFlagState, Unwind};
use rustc_mir_dataflow::elaborate_drops::{DropElaborator, DropFlagMode, DropStyle};
use rustc_mir_dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
use rustc_mir_dataflow::on_lookup_result_bits;
use rustc_mir_dataflow::MoveDataParamEnv;
use rustc_mir_dataflow::{on_all_children_bits, on_all_drop_children_bits};
use rustc_mir_dataflow::{Analysis, ResultsCursor};
use rustc_span::Span;
use rustc_target::abi::VariantIdx;
use std::fmt;
pub struct ElaborateDrops;
impl<'tcx> MirPass<'tcx> for ElaborateDrops {
fn phase_change(&self) -> Option<MirPhase> {
Some(MirPhase::DropsLowered)
}
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
debug!("elaborate_drops({:?} @ {:?})", body.source, body.span);
let def_id = body.source.def_id();
let param_env = tcx.param_env_reveal_all_normalized(def_id);
let move_data = match MoveData::gather_moves(body, tcx, param_env) {
Ok(move_data) => move_data,
Err((move_data, _)) => {
tcx.sess.delay_span_bug(
body.span,
"No `move_errors` should be allowed in MIR borrowck",
);
move_data
}
};
let elaborate_patch = {
let body = &*body;
let env = MoveDataParamEnv { move_data, param_env };
let dead_unwinds = find_dead_unwinds(tcx, body, &env);
let inits = MaybeInitializedPlaces::new(tcx, body, &env)
.into_engine(tcx, body)
.dead_unwinds(&dead_unwinds)
.pass_name("elaborate_drops")
.iterate_to_fixpoint()
.into_results_cursor(body);
let uninits = MaybeUninitializedPlaces::new(tcx, body, &env)
.mark_inactive_variants_as_uninit()
.into_engine(tcx, body)
.dead_unwinds(&dead_unwinds)
.pass_name("elaborate_drops")
.iterate_to_fixpoint()
.into_results_cursor(body);
ElaborateDropsCtxt {
tcx,
body,
env: &env,
init_data: InitializationData { inits, uninits },
drop_flags: Default::default(),
patch: MirPatch::new(body),
}
.elaborate()
};
elaborate_patch.apply(body);
}
}
/// Returns the set of basic blocks whose unwind edges are known
/// to not be reachable, because they are `drop` terminators
/// that can't drop anything.
fn find_dead_unwinds<'tcx>(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
env: &MoveDataParamEnv<'tcx>,
) -> BitSet<BasicBlock> {
debug!("find_dead_unwinds({:?})", body.span);
// We only need to do this pass once, because unwind edges can only
// reach cleanup blocks, which can't have unwind edges themselves.
let mut dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
let mut flow_inits = MaybeInitializedPlaces::new(tcx, body, &env)
.into_engine(tcx, body)
.pass_name("find_dead_unwinds")
.iterate_to_fixpoint()
.into_results_cursor(body);
for (bb, bb_data) in body.basic_blocks().iter_enumerated() {
let place = match bb_data.terminator().kind {
TerminatorKind::Drop { ref place, unwind: Some(_), .. }
| TerminatorKind::DropAndReplace { ref place, unwind: Some(_), .. } => place,
_ => continue,
};
debug!("find_dead_unwinds @ {:?}: {:?}", bb, bb_data);
let LookupResult::Exact(path) = env.move_data.rev_lookup.find(place.as_ref()) else {
debug!("find_dead_unwinds: has parent; skipping");
continue;
};
flow_inits.seek_before_primary_effect(body.terminator_loc(bb));
debug!(
"find_dead_unwinds @ {:?}: path({:?})={:?}; init_data={:?}",
bb,
place,
path,
flow_inits.get()
);
let mut maybe_live = false;
on_all_drop_children_bits(tcx, body, &env, path, |child| {
maybe_live |= flow_inits.contains(child);
});
debug!("find_dead_unwinds @ {:?}: maybe_live={}", bb, maybe_live);
if !maybe_live {
dead_unwinds.insert(bb);
}
}
dead_unwinds
}
struct InitializationData<'mir, 'tcx> {
inits: ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
uninits: ResultsCursor<'mir, 'tcx, MaybeUninitializedPlaces<'mir, 'tcx>>,
}
impl InitializationData<'_, '_> {
fn seek_before(&mut self, loc: Location) {
self.inits.seek_before_primary_effect(loc);
self.uninits.seek_before_primary_effect(loc);
}
fn maybe_live_dead(&self, path: MovePathIndex) -> (bool, bool) {
(self.inits.contains(path), self.uninits.contains(path))
}
}
struct Elaborator<'a, 'b, 'tcx> {
ctxt: &'a mut ElaborateDropsCtxt<'b, 'tcx>,
}
impl fmt::Debug for Elaborator<'_, '_, '_> {
fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
impl<'a, 'tcx> DropElaborator<'a, 'tcx> for Elaborator<'a, '_, 'tcx> {
type Path = MovePathIndex;
fn patch(&mut self) -> &mut MirPatch<'tcx> {
&mut self.ctxt.patch
}
fn body(&self) -> &'a Body<'tcx> {
self.ctxt.body
}
fn tcx(&self) -> TyCtxt<'tcx> {
self.ctxt.tcx
}
fn param_env(&self) -> ty::ParamEnv<'tcx> {
self.ctxt.param_env()
}
fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle {
let ((maybe_live, maybe_dead), multipart) = match mode {
DropFlagMode::Shallow => (self.ctxt.init_data.maybe_live_dead(path), false),
DropFlagMode::Deep => {
let mut some_live = false;
let mut some_dead = false;
let mut children_count = 0;
on_all_drop_children_bits(self.tcx(), self.body(), self.ctxt.env, path, |child| {
let (live, dead) = self.ctxt.init_data.maybe_live_dead(child);
debug!("elaborate_drop: state({:?}) = {:?}", child, (live, dead));
some_live |= live;
some_dead |= dead;
children_count += 1;
});
((some_live, some_dead), children_count != 1)
}
};
match (maybe_live, maybe_dead, multipart) {
(false, _, _) => DropStyle::Dead,
(true, false, _) => DropStyle::Static,
(true, true, false) => DropStyle::Conditional,
(true, true, true) => DropStyle::Open,
}
}
fn clear_drop_flag(&mut self, loc: Location, path: Self::Path, mode: DropFlagMode) |
fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path> {
rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
ProjectionElem::Field(idx, _) => idx == field,
_ => false,
})
}
fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path> {
rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
debug_assert!(size == min_length, "min_length should be exact for arrays");
assert!(!from_end, "from_end should not be used for array element ConstantIndex");
offset == index
}
_ => false,
})
}
fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path> {
rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| {
e == ProjectionElem::Deref
})
}
fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path> {
rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
ProjectionElem::Downcast(_, idx) => idx == variant,
_ => false,
})
}
fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>> {
self.ctxt.drop_flag(path).map(Operand::Copy)
}
}
struct ElaborateDropsCtxt<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
body: &'a Body<'tcx>,
env: &'a MoveDataParamEnv<'tcx>,
init_data: InitializationData<'a, 'tcx>,
drop_flags: FxHashMap<MovePathIndex, Local>,
patch: MirPatch<'tcx>,
}
impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
fn move_data(&self) -> &'b MoveData<'tcx> {
&self.env.move_data
}
fn param_env(&self) -> ty::ParamEnv<'tcx> {
self.env.param_env
}
fn create_drop_flag(&mut self, index: MovePathIndex, span: Span) {
let tcx = self.tcx;
let patch = &mut self.patch;
debug!("create_drop_flag({:?})", self.body.span);
self.drop_flags.entry(index).or_insert_with(|| patch.new_internal(tcx.types.bool, span));
}
fn drop_flag(&mut self, index: MovePathIndex) -> Option<Place<'tcx>> {
self.drop_flags.get(&index).map(|t| Place::from(*t))
}
/// create a patch that elaborates all drops in the input
/// MIR.
fn elaborate(mut self) -> MirPatch<'tcx> {
self.collect_drop_flags();
self.elaborate_drops();
self.drop_flags_on_init();
self.drop_flags_for_fn_rets();
self.drop_flags_for_args();
self.drop_flags_for_locs();
self.patch
}
fn collect_drop_flags(&mut self) {
for (bb, data) in self.body.basic_blocks().iter_enumerated() {
let terminator = data.terminator();
let place = match terminator.kind {
TerminatorKind::Drop { ref place, .. }
| TerminatorKind::DropAndReplace { ref place, .. } => place,
_ => continue,
};
self.init_data.seek_before(self.body.terminator_loc(bb));
let path = self.move_data().rev_lookup.find(place.as_ref());
debug!("collect_drop_flags: {:?}, place {:?} ({:?})", bb, place, path);
let path = match path {
LookupResult::Exact(e) => e,
LookupResult::Parent(None) => continue,
LookupResult::Parent(Some(parent)) => {
let (_maybe_live, maybe_dead) = self.init_data.maybe_live_dead(parent);
if maybe_dead {
self.tcx.sess.delay_span_bug(
terminator.source_info.span,
&format!(
"drop of untracked, uninitialized value {:?}, place {:?} ({:?})",
bb, place, path,
),
);
}
continue;
}
};
on_all_drop_children_bits(self.tcx, self.body, self.env, path, |child| {
let (maybe_live, maybe_dead) = self.init_data.maybe_live_dead(child);
debug!(
"collect_drop_flags: collecting {:?} from {:?}@{:?} - {:?}",
child,
place,
path,
(maybe_live, maybe_dead)
);
if maybe_live && maybe_dead {
self.create_drop_flag(child, terminator.source_info.span)
}
});
}
}
fn elaborate_drops(&mut self) {
for (bb, data) in self.body.basic_blocks().iter_enumerated() {
let loc = Location { block: bb, statement_index: data.statements.len() };
let terminator = data.terminator();
let resume_block = self.patch.resume_block();
match terminator.kind {
TerminatorKind::Drop { place, target, unwind } => {
self.init_data.seek_before(loc);
match self.move_data().rev_lookup.find(place.as_ref()) {
LookupResult::Exact(path) => elaborate_drop(
&mut Elaborator { ctxt: self },
terminator.source_info,
place,
path,
target,
if data.is_cleanup {
Unwind::InCleanup
} else {
Unwind::To(Option::unwrap_or(unwind, resume_block))
},
bb,
),
LookupResult::Parent(..) => {
self.tcx.sess.delay_span_bug(
terminator.source_info.span,
&format!("drop of untracked value {:?}", bb),
);
}
}
}
TerminatorKind::DropAndReplace { place, ref value, target, unwind } => {
assert!(!data.is_cleanup);
self.elaborate_replace(loc, place, value, target, unwind);
}
_ => continue,
}
}
}
/// Elaborate a MIR `replace` terminator. This instruction
/// is not directly handled by codegen, and therefore
/// must be desugared.
///
/// The desugaring drops the location if needed, and then writes
/// the value (including setting the drop flag) over it in *both* arms.
///
/// The `replace` terminator can also be called on places that
/// are not tracked by elaboration (for example,
/// `replace x[i] <- tmp0`). The borrow checker requires that
/// these locations are initialized before the assignment,
/// so we just generate an unconditional drop.
fn elaborate_replace(
&mut self,
loc: Location,
place: Place<'tcx>,
value: &Operand<'tcx>,
target: BasicBlock,
unwind: Option<BasicBlock>,
) {
let bb = loc.block;
let data = &self.body[bb];
let terminator = data.terminator();
assert!(!data.is_cleanup, "DropAndReplace in unwind path not supported");
let assign = Statement {
kind: StatementKind::Assign(Box::new((place, Rvalue::Use(value.clone())))),
source_info: terminator.source_info,
};
let unwind = unwind.unwrap_or_else(|| self.patch.resume_block());
let unwind = self.patch.new_block(BasicBlockData {
statements: vec![assign.clone()],
terminator: Some(Terminator {
kind: TerminatorKind::Goto { target: unwind },
..*terminator
}),
is_cleanup: true,
});
let target = self.patch.new_block(BasicBlockData {
statements: vec![assign],
terminator: Some(Terminator { kind: TerminatorKind::Goto { target }, ..*terminator }),
is_cleanup: false,
});
match self.move_data().rev_lookup.find(place.as_ref()) {
LookupResult::Exact(path) => {
debug!("elaborate_drop_and_replace({:?}) - tracked {:?}", terminator, path);
self.init_data.seek_before(loc);
elaborate_drop(
&mut Elaborator { ctxt: self },
terminator.source_info,
place,
path,
target,
Unwind::To(unwind),
bb,
);
on_all_children_bits(self.tcx, self.body, self.move_data(), path, |child| {
self.set_drop_flag(
Location { block: target, statement_index: 0 },
child,
DropFlagState::Present,
);
self.set_drop_flag(
Location { block: unwind, statement_index: 0 },
child,
DropFlagState::Present,
);
});
}
LookupResult::Parent(parent) => {
// drop and replace behind a pointer/array/whatever. The location
// must be initialized.
debug!("elaborate_drop_and_replace({:?}) - untracked {:?}", terminator, parent);
self.patch.patch_terminator(
bb,
TerminatorKind::Drop { place, target, unwind: Some(unwind) },
);
}
}
}
fn constant_bool(&self, span: Span, val: bool) -> Rvalue<'tcx> {
Rvalue::Use(Operand::Constant(Box::new(Constant {
span,
user_ty: None,
literal: ty::Const::from_bool(self.tcx, val).into(),
})))
}
fn set_drop_flag(&mut self, loc: Location, path: MovePathIndex, val: DropFlagState) {
if let Some(&flag) = self.drop_flags.get(&path) {
let span = self.patch.source_info_for_location(self.body, loc).span;
let val = self.constant_bool(span, val.value());
self.patch.add_assign(loc, Place::from(flag), val);
}
}
fn drop_flags_on_init(&mut self) {
let loc = Location::START;
let span = self.patch.source_info_for_location(self.body, loc).span;
let false_ = self.constant_bool(span, false);
for flag in self.drop_flags.values() {
self.patch.add_assign(loc, Place::from(*flag), false_.clone());
}
}
fn drop_flags_for_fn_rets(&mut self) {
for (bb, data) in self.body.basic_blocks().iter_enumerated() {
if let TerminatorKind::Call {
destination: Some((ref place, tgt)),
cleanup: Some(_),
..
} = data.terminator().kind
{
assert!(!self.patch.is_patched(bb));
let loc = Location { block: tgt, statement_index: 0 };
let path = self.move_data().rev_lookup.find(place.as_ref());
on_lookup_result_bits(self.tcx, self.body, self.move_data(), path, |child| {
self.set_drop_flag(loc, child, DropFlagState::Present)
});
}
}
}
fn drop_flags_for_args(&mut self) {
let loc = Location::START;
rustc_mir_dataflow::drop_flag_effects_for_function_entry(
self.tcx,
self.body,
self.env,
|path, ds| {
self.set_drop_flag(loc, path, ds);
},
)
}
fn drop_flags_for_locs(&mut self) {
// We intentionally iterate only over the *old* basic blocks.
//
// Basic blocks created by drop elaboration update their
// drop flags by themselves, to avoid the drop flags being
// clobbered before they are read.
for (bb, data) in self.body.basic_blocks().iter_enumerated() {
debug!("drop_flags_for_locs({:?})", data);
for i in 0..(data.statements.len() + 1) {
debug!("drop_flag_for_locs: stmt {}", i);
let mut allow_initializations = true;
if i == data.statements.len() {
match data.terminator().kind {
TerminatorKind::Drop { .. } => {
// drop elaboration should handle that by itself
continue;
}
TerminatorKind::DropAndReplace { .. } => {
// this contains the move of the source and
// the initialization of the destination. We
// only want the former - the latter is handled
// by the elaboration code and must be done
// *after* the destination is dropped.
assert!(self.patch.is_patched(bb));
allow_initializations = false;
}
TerminatorKind::Resume => {
// It is possible for `Resume` to be patched
// (in particular it can be patched to be replaced with
// a Goto; see `MirPatch::new`).
}
_ => {
assert!(!self.patch.is_patched(bb));
}
}
}
let loc = Location { block: bb, statement_index: i };
rustc_mir_dataflow::drop_flag_effects_for_location(
self.tcx,
self.body,
self.env,
loc,
|path, ds| {
if ds == DropFlagState::Absent || allow_initializations {
self.set_drop_flag(loc, path, ds)
}
},
)
}
// There may be a critical edge after this call,
// so mark the return as initialized *before* the
// call.
if let TerminatorKind::Call {
destination: Some((ref place, _)), cleanup: None, ..
} = data.terminator().kind
{
assert!(!self.patch.is_patched(bb));
let loc = Location { block: bb, statement_index: data.statements.len() };
let path = self.move_data().rev_lookup.find(place.as_ref());
on_lookup_result_bits(self.tcx, self.body, self.move_data(), path, |child| {
self.set_drop_flag(loc, child, DropFlagState::Present)
});
}
}
}
}
| {
match mode {
DropFlagMode::Shallow => {
self.ctxt.set_drop_flag(loc, path, DropFlagState::Absent);
}
DropFlagMode::Deep => {
on_all_children_bits(
self.tcx(),
self.body(),
self.ctxt.move_data(),
path,
|child| self.ctxt.set_drop_flag(loc, child, DropFlagState::Absent),
);
}
}
} |
mock_test.go | // Copyright (C) 2019-2020 Zilliz. 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.
package datanode
import (
"bytes"
"context"
"encoding/binary"
"errors"
"math"
"math/rand"
"path"
"strconv"
"sync"
"time"
"go.uber.org/zap"
etcdkv "github.com/milvus-io/milvus/internal/kv/etcd"
"github.com/milvus-io/milvus/internal/log"
"github.com/milvus-io/milvus/internal/msgstream"
"github.com/milvus-io/milvus/internal/types"
"github.com/milvus-io/milvus/internal/proto/commonpb"
"github.com/milvus-io/milvus/internal/proto/datapb"
"github.com/milvus-io/milvus/internal/proto/etcdpb"
"github.com/milvus-io/milvus/internal/proto/internalpb"
"github.com/milvus-io/milvus/internal/proto/milvuspb"
"github.com/milvus-io/milvus/internal/proto/rootcoordpb"
"github.com/milvus-io/milvus/internal/proto/schemapb"
)
const ctxTimeInMillisecond = 5000
const debug = false
func newIDLEDataNodeMock(ctx context.Context) *DataNode {
msFactory := msgstream.NewPmsFactory()
node := NewDataNode(ctx, msFactory)
rc := &RootCoordFactory{
ID: 0,
collectionID: 1,
collectionName: "collection-1",
}
node.SetRootCoordInterface(rc)
ds := &DataCoordFactory{}
node.SetDataCoordInterface(ds)
return node
}
func newHEALTHDataNodeMock(dmChannelName string) *DataNode {
var ctx context.Context
if debug {
ctx = context.Background()
} else {
var cancel context.CancelFunc
d := time.Now().Add(ctxTimeInMillisecond * time.Millisecond)
ctx, cancel = context.WithDeadline(context.Background(), d)
go func() {
<-ctx.Done()
cancel()
}()
}
msFactory := msgstream.NewPmsFactory()
node := NewDataNode(ctx, msFactory)
ms := &RootCoordFactory{
ID: 0,
collectionID: 1,
collectionName: "collection-1",
}
node.SetRootCoordInterface(ms)
ds := &DataCoordFactory{}
node.SetDataCoordInterface(ds)
return node
}
func makeNewChannelNames(names []string, suffix string) []string {
var ret []string
for _, name := range names {
ret = append(ret, name+suffix)
}
return ret
}
func clearEtcd(rootPath string) error {
etcdKV, err := etcdkv.NewEtcdKV(Params.EtcdEndpoints, rootPath)
if err != nil {
return err
}
err = etcdKV.RemoveWithPrefix("writer/segment")
if err != nil {
return err
}
_, _, err = etcdKV.LoadWithPrefix("writer/segment")
if err != nil {
return err
}
log.Debug("Clear ETCD with prefix writer/segment ")
err = etcdKV.RemoveWithPrefix("writer/ddl")
if err != nil {
return err
}
_, _, err = etcdKV.LoadWithPrefix("writer/ddl")
if err != nil {
return err
}
log.Debug("Clear ETCD with prefix writer/ddl")
return nil
}
type MetaFactory struct {
}
type DataFactory struct {
rawData []byte
}
type RootCoordFactory struct {
types.RootCoord
ID UniqueID
collectionName string
collectionID UniqueID
}
type DataCoordFactory struct {
types.DataCoord
SaveBinlogPathError bool
SaveBinlogPathNotSucess bool
}
func (ds *DataCoordFactory) SaveBinlogPaths(ctx context.Context, req *datapb.SaveBinlogPathsRequest) (*commonpb.Status, error) {
if ds.SaveBinlogPathError {
return nil, errors.New("Error")
}
if ds.SaveBinlogPathNotSucess {
return &commonpb.Status{ErrorCode: commonpb.ErrorCode_UnexpectedError}, nil
}
return &commonpb.Status{ErrorCode: commonpb.ErrorCode_Success}, nil
}
func (mf *MetaFactory) CollectionMetaFactory(collectionID UniqueID, collectionName string) *etcdpb.CollectionMeta {
sch := schemapb.CollectionSchema{
Name: collectionName,
Description: "test collection by meta factory",
AutoID: true,
Fields: []*schemapb.FieldSchema{
{
FieldID: 0,
Name: "RowID",
Description: "RowID field",
DataType: schemapb.DataType_Int64,
TypeParams: []*commonpb.KeyValuePair{
{
Key: "f0_tk1",
Value: "f0_tv1",
},
},
},
{
FieldID: 1,
Name: "Timestamp",
Description: "Timestamp field",
DataType: schemapb.DataType_Int64,
TypeParams: []*commonpb.KeyValuePair{
{
Key: "f1_tk1",
Value: "f1_tv1",
},
},
},
{
FieldID: 100,
Name: "float_vector_field",
Description: "field 100",
DataType: schemapb.DataType_FloatVector,
TypeParams: []*commonpb.KeyValuePair{
{
Key: "dim",
Value: "2",
},
},
IndexParams: []*commonpb.KeyValuePair{
{
Key: "indexkey",
Value: "indexvalue",
},
},
},
{
FieldID: 101,
Name: "binary_vector_field",
Description: "field 101",
DataType: schemapb.DataType_BinaryVector,
TypeParams: []*commonpb.KeyValuePair{
{
Key: "dim",
Value: "32",
},
},
IndexParams: []*commonpb.KeyValuePair{
{
Key: "indexkey",
Value: "indexvalue",
},
},
},
{
FieldID: 102,
Name: "bool_field",
Description: "field 102",
DataType: schemapb.DataType_Bool,
TypeParams: []*commonpb.KeyValuePair{},
IndexParams: []*commonpb.KeyValuePair{},
},
{
FieldID: 103,
Name: "int8_field",
Description: "field 103",
DataType: schemapb.DataType_Int8,
TypeParams: []*commonpb.KeyValuePair{},
IndexParams: []*commonpb.KeyValuePair{},
},
{
FieldID: 104,
Name: "int16_field",
Description: "field 104",
DataType: schemapb.DataType_Int16,
TypeParams: []*commonpb.KeyValuePair{},
IndexParams: []*commonpb.KeyValuePair{},
},
{
FieldID: 105,
Name: "int32_field",
Description: "field 105",
DataType: schemapb.DataType_Int32,
TypeParams: []*commonpb.KeyValuePair{},
IndexParams: []*commonpb.KeyValuePair{},
},
{
FieldID: 106,
Name: "int64_field",
Description: "field 106",
DataType: schemapb.DataType_Int64,
TypeParams: []*commonpb.KeyValuePair{},
IndexParams: []*commonpb.KeyValuePair{},
},
{
FieldID: 107,
Name: "float32_field",
Description: "field 107",
DataType: schemapb.DataType_Float,
TypeParams: []*commonpb.KeyValuePair{},
IndexParams: []*commonpb.KeyValuePair{},
},
{
FieldID: 108,
Name: "float64_field",
Description: "field 108",
DataType: schemapb.DataType_Double,
TypeParams: []*commonpb.KeyValuePair{},
IndexParams: []*commonpb.KeyValuePair{},
},
},
}
collection := etcdpb.CollectionMeta{
ID: collectionID,
Schema: &sch,
CreateTime: Timestamp(1),
SegmentIDs: make([]UniqueID, 0),
PartitionIDs: []UniqueID{0},
}
return &collection
}
func NewDataFactory() *DataFactory {
return &DataFactory{rawData: GenRowData()}
}
func GenRowData() (rawData []byte) |
func (df *DataFactory) GenMsgStreamInsertMsg(idx int, chanName string) *msgstream.InsertMsg {
var msg = &msgstream.InsertMsg{
BaseMsg: msgstream.BaseMsg{
HashValues: []uint32{uint32(idx)},
},
InsertRequest: internalpb.InsertRequest{
Base: &commonpb.MsgBase{
MsgType: commonpb.MsgType_Insert,
MsgID: 0,
Timestamp: Timestamp(idx + 1000),
SourceID: 0,
},
CollectionName: "col1",
PartitionName: "default",
SegmentID: 1,
ShardName: chanName,
Timestamps: []Timestamp{Timestamp(idx + 1000)},
RowIDs: []UniqueID{UniqueID(idx)},
RowData: []*commonpb.Blob{{Value: df.rawData}},
},
}
return msg
}
func (df *DataFactory) GetMsgStreamTsInsertMsgs(n int, chanName string) (inMsgs []msgstream.TsMsg) {
for i := 0; i < n; i++ {
var msg = df.GenMsgStreamInsertMsg(i, chanName)
var tsMsg msgstream.TsMsg = msg
inMsgs = append(inMsgs, tsMsg)
}
return
}
func (df *DataFactory) GetMsgStreamInsertMsgs(n int) (inMsgs []*msgstream.InsertMsg) {
for i := 0; i < n; i++ {
var msg = df.GenMsgStreamInsertMsg(i, "")
inMsgs = append(inMsgs, msg)
}
return
}
type AllocatorFactory struct {
sync.Mutex
r *rand.Rand
}
var _ allocatorInterface = &AllocatorFactory{}
func NewAllocatorFactory(id ...UniqueID) *AllocatorFactory {
f := &AllocatorFactory{
r: rand.New(rand.NewSource(time.Now().UnixNano())),
}
return f
}
func (alloc *AllocatorFactory) allocID() (UniqueID, error) {
alloc.Lock()
defer alloc.Unlock()
return alloc.r.Int63n(10000), nil
}
func (alloc *AllocatorFactory) genKey(isalloc bool, ids ...UniqueID) (key string, err error) {
if isalloc {
idx, err := alloc.allocID()
if err != nil {
return "", err
}
ids = append(ids, idx)
}
idStr := make([]string, len(ids))
for _, id := range ids {
idStr = append(idStr, strconv.FormatInt(id, 10))
}
key = path.Join(idStr...)
return
}
// If id == 0, AllocID will return not successful status
// If id == -1, AllocID will return err
func (m *RootCoordFactory) setID(id UniqueID) {
m.ID = id // GOOSE TODO: random ID generator
}
func (m *RootCoordFactory) setCollectionID(id UniqueID) {
m.collectionID = id
}
func (m *RootCoordFactory) setCollectionName(name string) {
m.collectionName = name
}
func (m *RootCoordFactory) AllocID(ctx context.Context, in *rootcoordpb.AllocIDRequest) (*rootcoordpb.AllocIDResponse, error) {
resp := &rootcoordpb.AllocIDResponse{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
}}
if m.ID == 0 {
resp.Status.Reason = "Zero ID"
return resp, nil
}
if m.ID == -1 {
resp.Status.ErrorCode = commonpb.ErrorCode_Success
return resp, errors.New(resp.Status.GetReason())
}
resp.ID = m.ID
resp.Status.ErrorCode = commonpb.ErrorCode_Success
return resp, nil
}
func (m *RootCoordFactory) AllocTimestamp(ctx context.Context, in *rootcoordpb.AllocTimestampRequest) (*rootcoordpb.AllocTimestampResponse, error) {
resp := &rootcoordpb.AllocTimestampResponse{
Status: &commonpb.Status{},
Timestamp: 1000,
}
return resp, nil
}
func (m *RootCoordFactory) ShowCollections(ctx context.Context, in *milvuspb.ShowCollectionsRequest) (*milvuspb.ShowCollectionsResponse, error) {
resp := &milvuspb.ShowCollectionsResponse{
Status: &commonpb.Status{},
CollectionNames: []string{m.collectionName},
}
return resp, nil
}
func (m *RootCoordFactory) DescribeCollection(ctx context.Context, in *milvuspb.DescribeCollectionRequest) (*milvuspb.DescribeCollectionResponse, error) {
f := MetaFactory{}
meta := f.CollectionMetaFactory(m.collectionID, m.collectionName)
resp := &milvuspb.DescribeCollectionResponse{
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
},
}
if m.collectionID == -2 {
resp.Status.Reason = "Status not success"
return resp, nil
}
if m.collectionID == -1 {
resp.Status.ErrorCode = commonpb.ErrorCode_Success
return resp, errors.New(resp.Status.GetReason())
}
resp.CollectionID = m.collectionID
resp.Schema = meta.Schema
resp.Status.ErrorCode = commonpb.ErrorCode_Success
return resp, nil
}
func (m *RootCoordFactory) GetComponentStates(ctx context.Context) (*internalpb.ComponentStates, error) {
return &internalpb.ComponentStates{
State: &internalpb.ComponentInfo{},
SubcomponentStates: make([]*internalpb.ComponentInfo, 0),
Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_Success,
},
}, nil
}
// FailMessageStreamFactory mock MessageStreamFactory failure
type FailMessageStreamFactory struct {
msgstream.Factory
}
func (f *FailMessageStreamFactory) NewMsgStream(ctx context.Context) (msgstream.MsgStream, error) {
return nil, errors.New("mocked failure")
}
func (f *FailMessageStreamFactory) NewTtMsgStream(ctx context.Context) (msgstream.MsgStream, error) {
return nil, errors.New("mocked failure")
}
| {
const DIM = 2
const N = 1
// Float vector
var fvector = [DIM]float32{1, 2}
for _, ele := range fvector {
buf := make([]byte, 4)
binary.LittleEndian.PutUint32(buf, math.Float32bits(ele))
rawData = append(rawData, buf...)
}
// Binary vector
// Dimension of binary vector is 32
// size := 4, = 32 / 8
var bvector = []byte{255, 255, 255, 0}
rawData = append(rawData, bvector...)
// Bool
var fieldBool = true
buf := new(bytes.Buffer)
if err := binary.Write(buf, binary.LittleEndian, fieldBool); err != nil {
panic(err)
}
rawData = append(rawData, buf.Bytes()...)
// int8
var dataInt8 int8 = 100
bint8 := new(bytes.Buffer)
if err := binary.Write(bint8, binary.LittleEndian, dataInt8); err != nil {
panic(err)
}
rawData = append(rawData, bint8.Bytes()...)
// int16
var dataInt16 int16 = 200
bint16 := new(bytes.Buffer)
if err := binary.Write(bint16, binary.LittleEndian, dataInt16); err != nil {
panic(err)
}
rawData = append(rawData, bint16.Bytes()...)
// int32
var dataInt32 int32 = 300
bint32 := new(bytes.Buffer)
if err := binary.Write(bint32, binary.LittleEndian, dataInt32); err != nil {
panic(err)
}
rawData = append(rawData, bint32.Bytes()...)
// int64
var dataInt64 int64 = 400
bint64 := new(bytes.Buffer)
if err := binary.Write(bint64, binary.LittleEndian, dataInt64); err != nil {
panic(err)
}
rawData = append(rawData, bint64.Bytes()...)
// float32
var datafloat float32 = 1.1
bfloat32 := new(bytes.Buffer)
if err := binary.Write(bfloat32, binary.LittleEndian, datafloat); err != nil {
panic(err)
}
rawData = append(rawData, bfloat32.Bytes()...)
// float64
var datafloat64 = 2.2
bfloat64 := new(bytes.Buffer)
if err := binary.Write(bfloat64, binary.LittleEndian, datafloat64); err != nil {
panic(err)
}
rawData = append(rawData, bfloat64.Bytes()...)
log.Debug("Rawdata length:", zap.Int("Length of rawData", len(rawData)))
return
} |
cfn-resource-policy.ts | /**
* Associate the CreationPolicy attribute with a resource to prevent its status from reaching create complete until
* AWS CloudFormation receives a specified number of success signals or the timeout period is exceeded. To signal a
* resource, you can use the cfn-signal helper script or SignalResource API. AWS CloudFormation publishes valid signals
* to the stack events so that you track the number of signals sent.
*
* The creation policy is invoked only when AWS CloudFormation creates the associated resource. Currently, the only
* AWS CloudFormation resources that support creation policies are AWS::AutoScaling::AutoScalingGroup, AWS::EC2::Instance,
* and AWS::CloudFormation::WaitCondition.
*
* Use the CreationPolicy attribute when you want to wait on resource configuration actions before stack creation proceeds.
* For example, if you install and configure software applications on an EC2 instance, you might want those applications to
* be running before proceeding. In such cases, you can add a CreationPolicy attribute to the instance, and then send a success
* signal to the instance after the applications are installed and configured. For a detailed example, see Deploying Applications
* on Amazon EC2 with AWS CloudFormation.
*/
export interface CfnCreationPolicy {
/**
* For an Auto Scaling group replacement update, specifies how many instances must signal success for the
* update to succeed.
*/
readonly autoScalingCreationPolicy?: CfnResourceAutoScalingCreationPolicy;
/**
* When AWS CloudFormation creates the associated resource, configures the number of required success signals and
* the length of time that AWS CloudFormation waits for those signals.
*/
readonly resourceSignal?: CfnResourceSignal;
}
/**
* For an Auto Scaling group replacement update, specifies how many instances must signal success for the
* update to succeed.
*/
export interface CfnResourceAutoScalingCreationPolicy {
/**
* Specifies the percentage of instances in an Auto Scaling replacement update that must signal success for the
* update to succeed. You can specify a value from 0 to 100. AWS CloudFormation rounds to the nearest tenth of a percent.
* For example, if you update five instances with a minimum successful percentage of 50, three instances must signal success.
* If an instance doesn't send a signal within the time specified by the Timeout property, AWS CloudFormation assumes that the
* instance wasn't created.
*/
readonly minSuccessfulInstancesPercent?: number;
}
/**
* When AWS CloudFormation creates the associated resource, configures the number of required success signals and
* the length of time that AWS CloudFormation waits for those signals.
*/
export interface CfnResourceSignal {
/**
* The number of success signals AWS CloudFormation must receive before it sets the resource status as CREATE_COMPLETE.
* If the resource receives a failure signal or doesn't receive the specified number of signals before the timeout period
* expires, the resource creation fails and AWS CloudFormation rolls the stack back.
*/
readonly count?: number;
/**
* The length of time that AWS CloudFormation waits for the number of signals that was specified in the Count property.
* The timeout period starts after AWS CloudFormation starts creating the resource, and the timeout expires no sooner
* than the time you specify but can occur shortly thereafter. The maximum time that you can specify is 12 hours.
*/
readonly timeout?: string;
}
/**
* With the DeletionPolicy attribute you can preserve or (in some cases) backup a resource when its stack is deleted.
* You specify a DeletionPolicy attribute for each resource that you want to control. If a resource has no DeletionPolicy
* attribute, AWS CloudFormation deletes the resource by default. Note that this capability also applies to update operations
* that lead to resources being removed.
*/
export enum CfnDeletionPolicy {
/**
* AWS CloudFormation deletes the resource and all its content if applicable during stack deletion. You can add this
* deletion policy to any resource type. By default, if you don't specify a DeletionPolicy, AWS CloudFormation deletes
* your resources. However, be aware of the following considerations:
*/
DELETE = 'Delete',
/**
* AWS CloudFormation keeps the resource without deleting the resource or its contents when its stack is deleted.
* You can add this deletion policy to any resource type. Note that when AWS CloudFormation completes the stack deletion,
* the stack will be in Delete_Complete state; however, resources that are retained continue to exist and continue to incur
* applicable charges until you delete those resources.
*/
RETAIN = 'Retain',
/**
* For resources that support snapshots (AWS::EC2::Volume, AWS::ElastiCache::CacheCluster, AWS::ElastiCache::ReplicationGroup,
* AWS::RDS::DBInstance, AWS::RDS::DBCluster, and AWS::Redshift::Cluster), AWS CloudFormation creates a snapshot for the
* resource before deleting it. Note that when AWS CloudFormation completes the stack deletion, the stack will be in the
* Delete_Complete state; however, the snapshots that are created with this policy continue to exist and continue to
* incur applicable charges until you delete those snapshots.
*/
SNAPSHOT = 'Snapshot',
}
/**
* Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the AWS::AutoScaling::AutoScalingGroup
* resource. AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a
* scheduled action is associated with the Auto Scaling group.
*/
export interface CfnUpdatePolicy {
/**
* Specifies whether an Auto Scaling group and the instances it contains are replaced during an update. During replacement,
* AWS CloudFormation retains the old group until it finishes creating the new one. If the update fails, AWS CloudFormation
* can roll back to the old Auto Scaling group and delete the new Auto Scaling group.
*/
readonly autoScalingReplacingUpdate?: CfnAutoScalingReplacingUpdate;
/**
* To specify how AWS CloudFormation handles rolling updates for an Auto Scaling group, use the AutoScalingRollingUpdate
* policy. Rolling updates enable you to specify whether AWS CloudFormation updates instances that are in an Auto Scaling
* group in batches or all at once.
*/
readonly autoScalingRollingUpdate?: CfnAutoScalingRollingUpdate;
/**
* To specify how AWS CloudFormation handles updates for the MinSize, MaxSize, and DesiredCapacity properties when
* the AWS::AutoScaling::AutoScalingGroup resource has an associated scheduled action, use the AutoScalingScheduledAction
* policy.
*/
readonly autoScalingScheduledAction?: CfnAutoScalingScheduledAction;
/**
* To perform an AWS CodeDeploy deployment when the version changes on an AWS::Lambda::Alias resource,
* use the CodeDeployLambdaAliasUpdate update policy.
*/
readonly codeDeployLambdaAliasUpdate?: CfnCodeDeployLambdaAliasUpdate;
/**
* To modify a replication group's shards by adding or removing shards, rather than replacing the entire
* AWS::ElastiCache::ReplicationGroup resource, use the UseOnlineResharding update policy.
*/
readonly useOnlineResharding?: boolean;
/**
* To upgrade an Amazon ES domain to a new version of Elasticsearch rather than replacing the entire
* AWS::Elasticsearch::Domain resource, use the EnableVersionUpgrade update policy.
*/
readonly enableVersionUpgrade?: boolean;
}
/**
* To specify how AWS CloudFormation handles rolling updates for an Auto Scaling group, use the AutoScalingRollingUpdate
* policy. Rolling updates enable you to specify whether AWS CloudFormation updates instances that are in an Auto Scaling
* group in batches or all at once.
*/
export interface CfnAutoScalingRollingUpdate {
/**
* Specifies the maximum number of instances that AWS CloudFormation updates.
*/
readonly maxBatchSize?: number;
/**
* Specifies the minimum number of instances that must be in service within the Auto Scaling group while AWS
* CloudFormation updates old instances.
*/
readonly minInstancesInService?: number;
/**
* Specifies the percentage of instances in an Auto Scaling rolling update that must signal success for an update to succeed.
* You can specify a value from 0 to 100. AWS CloudFormation rounds to the nearest tenth of a percent. For example, if you
* update five instances with a minimum successful percentage of 50, three instances must signal success.
*
* If an instance doesn't send a signal within the time specified in the PauseTime property, AWS CloudFormation assumes
* that the instance wasn't updated.
*
* If you specify this property, you must also enable the WaitOnResourceSignals and PauseTime properties.
*/
readonly minSuccessfulInstancesPercent?: number;
/**
* The amount of time that AWS CloudFormation pauses after making a change to a batch of instances to give those instances
* time to start software applications. For example, you might need to specify PauseTime when scaling up the number of
* instances in an Auto Scaling group.
*
* If you enable the WaitOnResourceSignals property, PauseTime is the amount of time that AWS CloudFormation should wait
* for the Auto Scaling group to receive the required number of valid signals from added or replaced instances. If the
* PauseTime is exceeded before the Auto Scaling group receives the required number of signals, the update fails. For best
* results, specify a time period that gives your applications sufficient time to get started. If the update needs to be
* rolled back, a short PauseTime can cause the rollback to fail.
*
* Specify PauseTime in the ISO8601 duration format (in the format PT#H#M#S, where each # is the number of hours, minutes,
* and seconds, respectively). The maximum PauseTime is one hour (PT1H).
*/
readonly pauseTime?: string;
/**
* Specifies the Auto Scaling processes to suspend during a stack update. Suspending processes prevents Auto Scaling from
* interfering with a stack update. For example, you can suspend alarming so that Auto Scaling doesn't execute scaling
* policies associated with an alarm. For valid values, see the ScalingProcesses.member.N parameter for the SuspendProcesses
* action in the Auto Scaling API Reference.
*/
readonly suspendProcesses?: string[];
/**
* Specifies whether the Auto Scaling group waits on signals from new instances during an update. Use this property to
* ensure that instances have completed installing and configuring applications before the Auto Scaling group update proceeds.
* AWS CloudFormation suspends the update of an Auto Scaling group after new EC2 instances are launched into the group.
* AWS CloudFormation must receive a signal from each new instance within the specified PauseTime before continuing the update.
* To signal the Auto Scaling group, use the cfn-signal helper script or SignalResource API.
*
* To have instances wait for an Elastic Load Balancing health check before they signal success, add a health-check
* verification by using the cfn-init helper script. For an example, see the verify_instance_health command in the Auto Scaling
* rolling updates sample template.
*/
readonly waitOnResourceSignals?: boolean;
}
/**
* Specifies whether an Auto Scaling group and the instances it contains are replaced during an update. During replacement,
* AWS CloudFormation retains the old group until it finishes creating the new one. If the update fails, AWS CloudFormation
* can roll back to the old Auto Scaling group and delete the new Auto Scaling group.
*
* While AWS CloudFormation creates the new group, it doesn't detach or attach any instances. After successfully creating
* the new Auto Scaling group, AWS CloudFormation deletes the old Auto Scaling group during the cleanup process.
*
* When you set the WillReplace parameter, remember to specify a matching CreationPolicy. If the minimum number of
* instances (specified by the MinSuccessfulInstancesPercent property) don't signal success within the Timeout period
* (specified in the CreationPolicy policy), the replacement update fails and AWS CloudFormation rolls back to the old
* Auto Scaling group.
*/
export interface CfnAutoScalingReplacingUpdate {
readonly willReplace?: boolean;
}
/**
* With scheduled actions, the group size properties of an Auto Scaling group can change at any time. When you update a
* stack with an Auto Scaling group and scheduled action, AWS CloudFormation always sets the group size property values of
* your Auto Scaling group to the values that are defined in the AWS::AutoScaling::AutoScalingGroup resource of your template,
* even if a scheduled action is in effect.
*
* If you do not want AWS CloudFormation to change any of the group size property values when you have a scheduled action in
* effect, use the AutoScalingScheduledAction update policy to prevent AWS CloudFormation from changing the MinSize, MaxSize,
* or DesiredCapacity properties unless you have modified these values in your template.\
*/
export interface CfnAutoScalingScheduledAction {
/*
* Specifies whether AWS CloudFormation ignores differences in group size properties between your current Auto Scaling
* group and the Auto Scaling group described in the AWS::AutoScaling::AutoScalingGroup resource of your template during
* a stack update. If you modify any of the group size property values in your template, AWS CloudFormation uses the modified
* values and updates your Auto Scaling group.
*/
readonly ignoreUnmodifiedGroupSizeProperties?: boolean;
}
| export interface CfnCodeDeployLambdaAliasUpdate {
/**
* The name of the AWS CodeDeploy application.
*/
readonly applicationName: string;
/**
* The name of the AWS CodeDeploy deployment group. This is where the traffic-shifting policy is set.
*/
readonly deploymentGroupName: string;
/**
* The name of the Lambda function to run before traffic routing starts.
*/
readonly beforeAllowTrafficHook?: string;
/**
* The name of the Lambda function to run after traffic routing completes.
*/
readonly afterAllowTrafficHook?: string;
} | /**
* To perform an AWS CodeDeploy deployment when the version changes on an AWS::Lambda::Alias resource,
* use the CodeDeployLambdaAliasUpdate update policy.
*/ |
peer.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package peer
import (
"fmt"
"net"
"runtime"
"sync"
"github.com/hyperledger/fabric/common/channelconfig"
cc "github.com/hyperledger/fabric/common/config"
"github.com/hyperledger/fabric/common/configtx"
"github.com/hyperledger/fabric/common/deliver"
"github.com/hyperledger/fabric/common/flogging"
commonledger "github.com/hyperledger/fabric/common/ledger"
"github.com/hyperledger/fabric/common/ledger/blockledger"
fileledger "github.com/hyperledger/fabric/common/ledger/blockledger/file"
"github.com/hyperledger/fabric/common/metrics"
"github.com/hyperledger/fabric/common/policies"
"github.com/hyperledger/fabric/core/chaincode/platforms"
"github.com/hyperledger/fabric/core/comm"
"github.com/hyperledger/fabric/core/committer"
"github.com/hyperledger/fabric/core/committer/txvalidator"
"github.com/hyperledger/fabric/core/common/ccprovider"
"github.com/hyperledger/fabric/core/common/privdata"
"github.com/hyperledger/fabric/core/common/sysccprovider"
"github.com/hyperledger/fabric/core/ledger"
"github.com/hyperledger/fabric/core/ledger/customtx"
"github.com/hyperledger/fabric/core/ledger/ledgermgmt"
"github.com/hyperledger/fabric/core/transientstore"
"github.com/hyperledger/fabric/gossip/api"
"github.com/hyperledger/fabric/gossip/service"
"github.com/hyperledger/fabric/msp"
mspmgmt "github.com/hyperledger/fabric/msp/mgmt"
"github.com/hyperledger/fabric/protos/common"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/hyperledger/fabric/protos/utils"
"github.com/hyperledger/fabric/token/tms/manager"
"github.com/hyperledger/fabric/token/transaction"
"github.com/pkg/errors"
"github.com/spf13/viper"
"golang.org/x/sync/semaphore"
)
var peerLogger = flogging.MustGetLogger("peer")
var peerServer *comm.GRPCServer
var configTxProcessor = newConfigTxProcessor()
var tokenTxProcessor = &transaction.Processor{
TMSManager: &manager.Manager{
IdentityDeserializerManager: &manager.FabricIdentityDeserializerManager{}}}
var ConfigTxProcessors = customtx.Processors{
common.HeaderType_CONFIG: configTxProcessor,
common.HeaderType_TOKEN_TRANSACTION: tokenTxProcessor,
}
// singleton instance to manage credentials for the peer across channel config changes
var credSupport = comm.GetCredentialSupport()
type gossipSupport struct {
channelconfig.Application
configtx.Validator
channelconfig.Channel
}
type chainSupport struct {
bundleSource *channelconfig.BundleSource
channelconfig.Resources
channelconfig.Application
ledger ledger.PeerLedger
}
var TransientStoreFactory = &storeProvider{stores: make(map[string]transientstore.Store)}
type storeProvider struct {
stores map[string]transientstore.Store
transientstore.StoreProvider
sync.RWMutex
}
func (sp *storeProvider) StoreForChannel(channel string) transientstore.Store {
sp.RLock()
defer sp.RUnlock()
return sp.stores[channel]
}
func (sp *storeProvider) OpenStore(ledgerID string) (transientstore.Store, error) {
sp.Lock()
defer sp.Unlock()
if sp.StoreProvider == nil {
sp.StoreProvider = transientstore.NewStoreProvider()
}
store, err := sp.StoreProvider.OpenStore(ledgerID)
if err == nil {
sp.stores[ledgerID] = store
}
return store, err
}
func (cs *chainSupport) Apply(configtx *common.ConfigEnvelope) error {
err := cs.ConfigtxValidator().Validate(configtx)
if err != nil {
return err
}
// If the chainSupport is being mocked, this field will be nil
if cs.bundleSource != nil {
bundle, err := channelconfig.NewBundle(cs.ConfigtxValidator().ChainID(), configtx.Config)
if err != nil {
return err
}
channelconfig.LogSanityChecks(bundle)
err = cs.bundleSource.ValidateNew(bundle)
if err != nil {
return err
}
capabilitiesSupportedOrPanic(bundle)
cs.bundleSource.Update(bundle)
}
return nil
}
func capabilitiesSupportedOrPanic(res channelconfig.Resources) {
ac, ok := res.ApplicationConfig()
if !ok {
peerLogger.Panicf("[channel %s] does not have application config so is incompatible", res.ConfigtxValidator().ChainID())
}
if err := ac.Capabilities().Supported(); err != nil {
peerLogger.Panicf("[channel %s] incompatible: %s", res.ConfigtxValidator().ChainID(), err)
}
if err := res.ChannelConfig().Capabilities().Supported(); err != nil {
peerLogger.Panicf("[channel %s] incompatible: %s", res.ConfigtxValidator().ChainID(), err)
}
}
func (cs *chainSupport) Ledger() ledger.PeerLedger {
return cs.ledger
}
func (cs *chainSupport) GetMSPIDs(cid string) []string {
return GetMSPIDs(cid)
}
// Sequence passes through to the underlying configtx.Validator
func (cs *chainSupport) Sequence() uint64 {
sb := cs.bundleSource.StableBundle()
return sb.ConfigtxValidator().Sequence()
}
// Reader returns an iterator to read from the ledger
func (cs *chainSupport) Reader() blockledger.Reader {
return fileledger.NewFileLedger(fileLedgerBlockStore{cs.ledger})
}
// Errored returns a channel that can be used to determine
// if a backing resource has errored. At this point in time,
// the peer does not have any error conditions that lead to
// this function signaling that an error has occurred.
func (cs *chainSupport) Errored() <-chan struct{} {
return nil
}
// chain is a local struct to manage objects in a chain
type chain struct {
cs *chainSupport
cb *common.Block
committer committer.Committer
}
// chains is a local map of chainID->chainObject
var chains = struct {
sync.RWMutex
list map[string]*chain
}{list: make(map[string]*chain)}
var chainInitializer func(string)
var pluginMapper txvalidator.PluginMapper
var mockMSPIDGetter func(string) []string
func MockSetMSPIDGetter(mspIDGetter func(string) []string) {
mockMSPIDGetter = mspIDGetter
}
// validationWorkersSemaphore is the semaphore used to ensure that
// there are not too many concurrent tx validation goroutines
var validationWorkersSemaphore *semaphore.Weighted
// Initialize sets up any chains that the peer has from the persistence. This
// function should be called at the start up when the ledger and gossip
// ready
func Initialize(init func(string), ccp ccprovider.ChaincodeProvider, sccp sysccprovider.SystemChaincodeProvider,
pm txvalidator.PluginMapper, pr *platforms.Registry, deployedCCInfoProvider ledger.DeployedChaincodeInfoProvider,
membershipProvider ledger.MembershipInfoProvider, metricsProvider metrics.Provider) {
nWorkers := viper.GetInt("peer.validatorPoolSize")
if nWorkers <= 0 {
nWorkers = runtime.NumCPU()
}
validationWorkersSemaphore = semaphore.NewWeighted(int64(nWorkers))
pluginMapper = pm
chainInitializer = init
var cb *common.Block
var ledger ledger.PeerLedger
ledgermgmt.Initialize(&ledgermgmt.Initializer{
CustomTxProcessors: ConfigTxProcessors,
PlatformRegistry: pr,
DeployedChaincodeInfoProvider: deployedCCInfoProvider,
MembershipInfoProvider: membershipProvider,
MetricsProvider: metricsProvider,
})
ledgerIds, err := ledgermgmt.GetLedgerIDs()
if err != nil {
panic(fmt.Errorf("Error in initializing ledgermgmt: %s", err))
}
for _, cid := range ledgerIds {
peerLogger.Infof("Loading chain %s", cid)
if ledger, err = ledgermgmt.OpenLedger(cid); err != nil {
<<<<<<< HEAD
peerLogger.Errorf("Failed to load ledger %s(%+v)", cid, err)
=======
peerLogger.Warningf("Failed to load ledger %s(%s)", cid, err)
>>>>>>> tag-v1.4.0
peerLogger.Debugf("Error while loading ledger %s with message %s. We continue to the next ledger rather than abort.", cid, err)
continue
}
if cb, err = getCurrConfigBlockFromLedger(ledger); err != nil {
peerLogger.Warningf("Failed to find config block on ledger %s(%s)", cid, err)
peerLogger.Debugf("Error while looking for config block on ledger %s with message %s. We continue to the next ledger rather than abort.", cid, err)
continue
}
// Create a chain if we get a valid ledger with config block
if err = createChain(cid, ledger, cb, ccp, sccp, pm); err != nil {
peerLogger.Warningf("Failed to load chain %s(%s)", cid, err)
peerLogger.Debugf("Error reloading chain %s with message %s. We continue to the next chain rather than abort.", cid, err)
continue
}
InitChain(cid)
}
}
// InitChain takes care to initialize chain after peer joined, for example deploys system CCs
func InitChain(cid string) {
if chainInitializer != nil {
// Initialize chaincode, namely deploy system CC
peerLogger.Debugf("Initializing channel %s", cid)
chainInitializer(cid) |
func getCurrConfigBlockFromLedger(ledger ledger.PeerLedger) (*common.Block, error) {
peerLogger.Debugf("Getting config block")
// get last block. Last block number is Height-1
blockchainInfo, err := ledger.GetBlockchainInfo()
if err != nil {
return nil, err
}
lastBlock, err := ledger.GetBlockByNumber(blockchainInfo.Height - 1)
if err != nil {
return nil, err
}
// get most recent config block location from last block metadata
configBlockIndex, err := utils.GetLastConfigIndexFromBlock(lastBlock)
if err != nil {
return nil, err
}
// get most recent config block
configBlock, err := ledger.GetBlockByNumber(configBlockIndex)
if err != nil {
return nil, err
}
peerLogger.Debugf("Got config block[%d]", configBlockIndex)
return configBlock, nil
}
// createChain creates a new chain object and insert it into the chains
func createChain(cid string, ledger ledger.PeerLedger, cb *common.Block, ccp ccprovider.ChaincodeProvider, sccp sysccprovider.SystemChaincodeProvider, pm txvalidator.PluginMapper) error {
chanConf, err := retrievePersistedChannelConfig(ledger)
if err != nil {
return err
}
var bundle *channelconfig.Bundle
if chanConf != nil {
bundle, err = channelconfig.NewBundle(cid, chanConf)
if err != nil {
return err
}
} else {
// Config was only stored in the statedb starting with v1.1 binaries
// so if the config is not found there, extract it manually from the config block
envelopeConfig, err := utils.ExtractEnvelope(cb, 0)
if err != nil {
return err
}
bundle, err = channelconfig.NewBundleFromEnvelope(envelopeConfig)
if err != nil {
return err
}
}
capabilitiesSupportedOrPanic(bundle)
channelconfig.LogSanityChecks(bundle)
gossipEventer := service.GetGossipService().NewConfigEventer()
gossipCallbackWrapper := func(bundle *channelconfig.Bundle) {
ac, ok := bundle.ApplicationConfig()
if !ok {
// TODO, handle a missing ApplicationConfig more gracefully
ac = nil
}
gossipEventer.ProcessConfigUpdate(&gossipSupport{
Validator: bundle.ConfigtxValidator(),
Application: ac,
Channel: bundle.ChannelConfig(),
})
service.GetGossipService().SuspectPeers(func(identity api.PeerIdentityType) bool {
// TODO: this is a place-holder that would somehow make the MSP layer suspect
// that a given certificate is revoked, or its intermediate CA is revoked.
// In the meantime, before we have such an ability, we return true in order
// to suspect ALL identities in order to validate all of them.
return true
})
}
trustedRootsCallbackWrapper := func(bundle *channelconfig.Bundle) {
updateTrustedRoots(bundle)
}
mspCallback := func(bundle *channelconfig.Bundle) {
// TODO remove once all references to mspmgmt are gone from peer code
mspmgmt.XXXSetMSPManager(cid, bundle.MSPManager())
}
ac, ok := bundle.ApplicationConfig()
if !ok {
ac = nil
}
cs := &chainSupport{
Application: ac, // TODO, refactor as this is accessible through Manager
ledger: ledger,
}
peerSingletonCallback := func(bundle *channelconfig.Bundle) {
ac, ok := bundle.ApplicationConfig()
if !ok {
ac = nil
}
cs.Application = ac
cs.Resources = bundle
}
cs.bundleSource = channelconfig.NewBundleSource(
bundle,
gossipCallbackWrapper,
trustedRootsCallbackWrapper,
mspCallback,
peerSingletonCallback,
)
vcs := struct {
*chainSupport
*semaphore.Weighted
}{cs, validationWorkersSemaphore}
validator := txvalidator.NewTxValidator(cid, vcs, sccp, pm)
c := committer.NewLedgerCommitterReactive(ledger, func(block *common.Block) error {
chainID, err := utils.GetChainIDFromBlock(block)
if err != nil {
return err
}
return SetCurrConfigBlock(block, chainID)
})
ordererAddresses := bundle.ChannelConfig().OrdererAddresses()
if len(ordererAddresses) == 0 {
return errors.New("no ordering service endpoint provided in configuration block")
}
// TODO: does someone need to call Close() on the transientStoreFactory at shutdown of the peer?
store, err := TransientStoreFactory.OpenStore(bundle.ConfigtxValidator().ChainID())
if err != nil {
return errors.Wrapf(err, "[channel %s] failed opening transient store", bundle.ConfigtxValidator().ChainID())
}
csStoreSupport := &CollectionSupport{
PeerLedger: ledger,
}
simpleCollectionStore := privdata.NewSimpleCollectionStore(csStoreSupport)
service.GetGossipService().InitializeChannel(bundle.ConfigtxValidator().ChainID(), ordererAddresses, service.Support{
Validator: validator,
Committer: c,
Store: store,
Cs: simpleCollectionStore,
IdDeserializeFactory: csStoreSupport,
})
chains.Lock()
defer chains.Unlock()
chains.list[cid] = &chain{
cs: cs,
cb: cb,
committer: c,
}
return nil
}
// CreateChainFromBlock creates a new chain from config block
func CreateChainFromBlock(cb *common.Block, ccp ccprovider.ChaincodeProvider, sccp sysccprovider.SystemChaincodeProvider) error {
cid, err := utils.GetChainIDFromBlock(cb)
if err != nil {
return err
}
var l ledger.PeerLedger
if l, err = ledgermgmt.CreateLedger(cb); err != nil {
return errors.WithMessage(err, "cannot create ledger from genesis block")
}
return createChain(cid, l, cb, ccp, sccp, pluginMapper)
}
// GetLedger returns the ledger of the chain with chain ID. Note that this
// call returns nil if chain cid has not been created.
func GetLedger(cid string) ledger.PeerLedger {
chains.RLock()
defer chains.RUnlock()
if c, ok := chains.list[cid]; ok {
return c.cs.ledger
}
return nil
}
// GetStableChannelConfig returns the stable channel configuration of the chain with channel ID.
// Note that this call returns nil if chain cid has not been created.
func GetStableChannelConfig(cid string) channelconfig.Resources {
chains.RLock()
defer chains.RUnlock()
if c, ok := chains.list[cid]; ok {
return c.cs.bundleSource.StableBundle()
}
return nil
}
// GetChannelConfig returns the channel configuration of the chain with channel ID. Note that this
// call returns nil if chain cid has not been created.
func GetChannelConfig(cid string) channelconfig.Resources {
chains.RLock()
defer chains.RUnlock()
if c, ok := chains.list[cid]; ok {
return c.cs
}
return nil
}
// GetPolicyManager returns the policy manager of the chain with chain ID. Note that this
// call returns nil if chain cid has not been created.
func GetPolicyManager(cid string) policies.Manager {
chains.RLock()
defer chains.RUnlock()
if c, ok := chains.list[cid]; ok {
return c.cs.PolicyManager()
}
return nil
}
// GetCurrConfigBlock returns the cached config block of the specified chain.
// Note that this call returns nil if chain cid has not been created.
func GetCurrConfigBlock(cid string) *common.Block {
chains.RLock()
defer chains.RUnlock()
if c, ok := chains.list[cid]; ok {
return c.cb
}
return nil
}
// updates the trusted roots for the peer based on updates to channels
func updateTrustedRoots(cm channelconfig.Resources) {
// this is triggered on per channel basis so first update the roots for the channel
peerLogger.Debugf("Updating trusted root authorities for channel %s", cm.ConfigtxValidator().ChainID())
var serverConfig comm.ServerConfig
var err error
// only run is TLS is enabled
serverConfig, err = GetServerConfig()
if err == nil && serverConfig.SecOpts.UseTLS {
buildTrustedRootsForChain(cm)
// now iterate over all roots for all app and orderer chains
trustedRoots := [][]byte{}
credSupport.RLock()
defer credSupport.RUnlock()
for _, roots := range credSupport.AppRootCAsByChain {
trustedRoots = append(trustedRoots, roots...)
}
// also need to append statically configured root certs
if len(serverConfig.SecOpts.ClientRootCAs) > 0 {
trustedRoots = append(trustedRoots, serverConfig.SecOpts.ClientRootCAs...)
}
if len(serverConfig.SecOpts.ServerRootCAs) > 0 {
trustedRoots = append(trustedRoots, serverConfig.SecOpts.ServerRootCAs...)
}
server := peerServer
// now update the client roots for the peerServer
if server != nil {
err := server.SetClientRootCAs(trustedRoots)
if err != nil {
msg := "Failed to update trusted roots for peer from latest config " +
"block. This peer may not be able to communicate " +
"with members of channel %s (%s)"
peerLogger.Warningf(msg, cm.ConfigtxValidator().ChainID(), err)
}
}
}
}
// populates the appRootCAs and orderRootCAs maps by getting the
// root and intermediate certs for all msps associated with the MSPManager
func buildTrustedRootsForChain(cm channelconfig.Resources) {
credSupport.Lock()
defer credSupport.Unlock()
appRootCAs := [][]byte{}
ordererRootCAs := [][]byte{}
appOrgMSPs := make(map[string]struct{})
ordOrgMSPs := make(map[string]struct{})
if ac, ok := cm.ApplicationConfig(); ok {
//loop through app orgs and build map of MSPIDs
for _, appOrg := range ac.Organizations() {
appOrgMSPs[appOrg.MSPID()] = struct{}{}
}
}
if ac, ok := cm.OrdererConfig(); ok {
//loop through orderer orgs and build map of MSPIDs
for _, ordOrg := range ac.Organizations() {
ordOrgMSPs[ordOrg.MSPID()] = struct{}{}
}
}
cid := cm.ConfigtxValidator().ChainID()
peerLogger.Debugf("updating root CAs for channel [%s]", cid)
msps, err := cm.MSPManager().GetMSPs()
if err != nil {
peerLogger.Errorf("Error getting root CAs for channel %s (%s)", cid, err)
}
if err == nil {
for k, v := range msps {
// check to see if this is a FABRIC MSP
if v.GetType() == msp.FABRIC {
for _, root := range v.GetTLSRootCerts() {
// check to see of this is an app org MSP
if _, ok := appOrgMSPs[k]; ok {
peerLogger.Debugf("adding app root CAs for MSP [%s]", k)
appRootCAs = append(appRootCAs, root)
}
// check to see of this is an orderer org MSP
if _, ok := ordOrgMSPs[k]; ok {
peerLogger.Debugf("adding orderer root CAs for MSP [%s]", k)
ordererRootCAs = append(ordererRootCAs, root)
}
}
for _, intermediate := range v.GetTLSIntermediateCerts() {
// check to see of this is an app org MSP
if _, ok := appOrgMSPs[k]; ok {
peerLogger.Debugf("adding app root CAs for MSP [%s]", k)
appRootCAs = append(appRootCAs, intermediate)
}
// check to see of this is an orderer org MSP
if _, ok := ordOrgMSPs[k]; ok {
peerLogger.Debugf("adding orderer root CAs for MSP [%s]", k)
ordererRootCAs = append(ordererRootCAs, intermediate)
}
}
}
}
credSupport.AppRootCAsByChain[cid] = appRootCAs
credSupport.OrdererRootCAsByChain[cid] = ordererRootCAs
}
}
// GetMSPIDs returns the ID of each application MSP defined on this chain
func GetMSPIDs(cid string) []string {
chains.RLock()
defer chains.RUnlock()
//if mock is set, use it to return MSPIDs
//used for tests without a proper join
if mockMSPIDGetter != nil {
return mockMSPIDGetter(cid)
}
if c, ok := chains.list[cid]; ok {
if c == nil || c.cs == nil {
return nil
}
ac, ok := c.cs.ApplicationConfig()
if !ok || ac.Organizations() == nil {
return nil
}
orgs := ac.Organizations()
toret := make([]string, len(orgs))
i := 0
for _, org := range orgs {
toret[i] = org.MSPID()
i++
}
return toret
}
return nil
}
// SetCurrConfigBlock sets the current config block of the specified channel
func SetCurrConfigBlock(block *common.Block, cid string) error {
chains.Lock()
defer chains.Unlock()
if c, ok := chains.list[cid]; ok {
c.cb = block
return nil
}
return errors.Errorf("[channel %s] channel not associated with this peer", cid)
}
// GetLocalIP returns the non loopback local IP of the host
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// check the address type and if it is not a loopback then display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
// GetChannelsInfo returns an array with information about all channels for
// this peer
func GetChannelsInfo() []*pb.ChannelInfo {
// array to store metadata for all channels
var channelInfoArray []*pb.ChannelInfo
chains.RLock()
defer chains.RUnlock()
for key := range chains.list {
channelInfo := &pb.ChannelInfo{ChannelId: key}
// add this specific chaincode's metadata to the array of all chaincodes
channelInfoArray = append(channelInfoArray, channelInfo)
}
return channelInfoArray
}
// NewChannelPolicyManagerGetter returns a new instance of ChannelPolicyManagerGetter
func NewChannelPolicyManagerGetter() policies.ChannelPolicyManagerGetter {
return &channelPolicyManagerGetter{}
}
type channelPolicyManagerGetter struct{}
func (c *channelPolicyManagerGetter) Manager(channelID string) (policies.Manager, bool) {
policyManager := GetPolicyManager(channelID)
return policyManager, policyManager != nil
}
// NewPeerServer creates an instance of comm.GRPCServer
// This server is used for peer communications
func NewPeerServer(listenAddress string, serverConfig comm.ServerConfig) (*comm.GRPCServer, error) {
var err error
peerServer, err = comm.NewGRPCServer(listenAddress, serverConfig)
if err != nil {
peerLogger.Errorf("Failed to create peer server (%s)", err)
return nil, err
}
return peerServer, nil
}
// TODO: Remove CollectionSupport and respective methonds on them.
// CollectionSupport is created per chain and is passed to the simple
// collection store and the gossip. As it is created per chain, there
// is no need to pass the channelID for both GetQueryExecutorForLedger()
// and GetIdentityDeserializer(). Note that the cid passed to
// GetQueryExecutorForLedger is never used. Instead, we can directly
// pass the ledger.PeerLedger and msp.IdentityDeserializer to the
// simpleCollectionStore and pass only the msp.IdentityDeserializer to
// the gossip in createChain() -- FAB-13037
type CollectionSupport struct {
ledger.PeerLedger
}
func (cs *CollectionSupport) GetQueryExecutorForLedger(cid string) (ledger.QueryExecutor, error) {
return cs.NewQueryExecutor()
}
func (*CollectionSupport) GetIdentityDeserializer(chainID string) msp.IdentityDeserializer {
return mspmgmt.GetManagerForChain(chainID)
}
//
// Deliver service support structs for the peer
//
// DeliverChainManager provides access to a channel for performing deliver
type DeliverChainManager struct {
}
func (DeliverChainManager) GetChain(chainID string) deliver.Chain {
channel, ok := chains.list[chainID]
if !ok {
return nil
}
return channel.cs
}
// fileLedgerBlockStore implements the interface expected by
// common/ledger/blockledger/file to interact with a file ledger for deliver
type fileLedgerBlockStore struct {
ledger.PeerLedger
}
func (flbs fileLedgerBlockStore) AddBlock(*common.Block) error {
return nil
}
func (flbs fileLedgerBlockStore) RetrieveBlocks(startBlockNumber uint64) (commonledger.ResultsIterator, error) {
return flbs.GetBlocksIterator(startBlockNumber)
}
// NewConfigSupport returns
func NewConfigSupport() cc.Manager {
return &configSupport{}
}
type configSupport struct {
}
// GetChannelConfig returns an instance of a object that represents
// current channel configuration tree of the specified channel. The
// ConfigProto method of the returned object can be used to get the
// proto representing the channel configuration.
func (*configSupport) GetChannelConfig(channel string) cc.Config {
chains.RLock()
defer chains.RUnlock()
chain := chains.list[channel]
if chain == nil {
peerLogger.Errorf("[channel %s] channel not associated with this peer", channel)
return nil
}
return chain.cs.bundleSource.ConfigtxValidator()
} | }
} |
Tests.tsx | import React, {
ReactElement, useContext, useMemo, useState,
} from 'react';
import { FaRegSmileWink } from 'react-icons/all';
import { Link } from 'react-router-dom';
import { EmptyContent, Table } from '../components';
import { CellProps, ColumnsProps } from '../components/Table';
import {
ITestSchema, OverviewData,
ReDataModelDetails, RedataOverviewContext,
} from '../contexts/redataOverviewContext';
import colors from '../utils/colors.js';
export interface TP {
showRunAt: boolean;
showModel: boolean;
modelName?: string | null;
showFilter?: boolean;
showSearch?: boolean;
}
type RightComponentProps = {
options: string[];
value: string;
handleChange: (event: React.ChangeEvent<HTMLSelectElement>) => void;
}
| const ModelCell = ({ value }: CellProps) => (
<Link
to={`/graph?model=${value.toLowerCase()}`}
className="text-sm text-blue-700 font-semibold"
>
{value}
</Link>
);
const StatusCell = ({ value }: CellProps) => (
<div
className={`${value?.toLowerCase()} text-xs font-medium text-center py-1 rounded-full`}
>
{value}
</div>
);
const RightComponent = ({ options, value, handleChange }: RightComponentProps) => (
<select
className="px-2 py-1 rounded-md w-1/4 right-component border border-gray-300"
onChange={handleChange}
value={value}
>
<option value="">All sorted by run time (new firsts)</option>
{options.map((option: string) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
);
type generateTestsDataProps = {
tests: ITestSchema[]
modelName?: string | null
aggregatedModels: Map<string, ReDataModelDetails>;
runAtsData?: Record<string, ITestSchema[]>;
}
const generateTestsData = (props: generateTestsDataProps) => {
const {
tests, aggregatedModels, runAtsData, modelName,
} = props;
const result: Array<ITestSchema> = [];
const runAts = new Set<string>();
if (modelName) {
if (aggregatedModels.has(modelName) && runAtsData) {
const aggregate = aggregatedModels.get(modelName);
const x = Object.keys(runAtsData).sort().pop();
const aggregateTests = aggregate?.tests || [];
if (x) {
for (let index = 0; index < aggregateTests.length; index++) {
const test = aggregateTests[index];
if (x === test.run_at) {
result.push({ ...test });
}
}
}
}
} else {
for (let index = 0; index < tests.length; index++) {
const test = tests[index];
runAts.add(test.run_at);
result.push({ ...test });
}
}
return { result, runAts };
};
function TestsPartial(params: TP): ReactElement {
const {
showModel, showFilter = true,
showRunAt, modelName = null,
showSearch = true,
} = params;
const overview: OverviewData = useContext(RedataOverviewContext);
const { tests, aggregated_models: aggregatedModels, runAts: runAtsData } = overview;
const [backUpData, setBackUpData] = useState([]);
const [data, setData] = useState([]);
const [options, setOptions] = useState([]);
const [selectedOption, setSelectedOption] = useState('');
const columns = useMemo(() => {
const cols: ColumnsProps[] = [{
Header: 'Test Name',
accessor: 'test_name',
},
{
Header: 'Status',
accessor: 'status',
Cell: StatusCell,
},
{
Header: 'Column',
accessor: 'column_name',
}];
if (showModel) {
cols.push({
Header: 'Model',
accessor: 'model',
Cell: ModelCell,
type: 'type',
});
}
if (showRunAt) {
cols.push({
Header: 'Run At',
accessor: 'run_at',
});
}
return cols;
}, [showModel, showModel]);
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const option = e.target.value;
setSelectedOption(option);
if (option) {
setData(backUpData.filter((row: ITestSchema) => row.run_at === option));
} else {
setData(backUpData);
}
};
useMemo(() => {
const initialTests = generateTestsData({
tests,
modelName,
aggregatedModels,
runAtsData,
});
const { result, runAts } = initialTests;
setOptions(Array.from(runAts) as []);
setBackUpData(result as []);
setData(result as []);
}, [tests, modelName]);
const check = !showFilter ? null : () => (
<RightComponent
options={options}
value={selectedOption}
handleChange={handleChange}
/>
);
return (
<>
{(data.length)
? (
<Table
columns={columns}
data={data}
showSearch={showSearch}
RightComponent={check}
/>
) : (
<EmptyContent text={modelName ? `No test for '${modelName}' model` : 'No Test'}>
<FaRegSmileWink size={80} color={colors.primary} />
</EmptyContent>
)}
</>
);
}
export default TestsPartial; | |
feature_name.rs | use cargo_metadata::Metadata;
use clippy_utils::diagnostics::span_lint_and_help;
use rustc_lint::LateContext;
use rustc_span::source_map::DUMMY_SP;
use super::{NEGATIVE_FEATURE_NAMES, REDUNDANT_FEATURE_NAMES};
static PREFIXES: [&str; 8] = ["no-", "no_", "not-", "not_", "use-", "use_", "with-", "with_"];
static SUFFIXES: [&str; 2] = ["-support", "_support"];
pub(super) fn check(cx: &LateContext<'_>, metadata: &Metadata) {
for package in &metadata.packages {
let mut features: Vec<&String> = package.features.keys().collect();
features.sort();
for feature in features {
let prefix_opt = {
let i = PREFIXES.partition_point(|prefix| prefix < &feature.as_str());
if i > 0 && feature.starts_with(PREFIXES[i - 1]) {
Some(PREFIXES[i - 1])
} else {
None
}
};
if let Some(prefix) = prefix_opt {
lint(cx, feature, prefix, true);
}
let suffix_opt: Option<&str> = {
let i = SUFFIXES.partition_point(|suffix| { | } else {
None
}
};
if let Some(suffix) = suffix_opt {
lint(cx, feature, suffix, false);
}
}
}
}
fn is_negative_prefix(s: &str) -> bool {
s.starts_with("no")
}
fn lint(cx: &LateContext<'_>, feature: &str, substring: &str, is_prefix: bool) {
let is_negative = is_prefix && is_negative_prefix(substring);
span_lint_and_help(
cx,
if is_negative {
NEGATIVE_FEATURE_NAMES
} else {
REDUNDANT_FEATURE_NAMES
},
DUMMY_SP,
&format!(
"the \"{}\" {} in the feature name \"{}\" is {}",
substring,
if is_prefix { "prefix" } else { "suffix" },
feature,
if is_negative { "negative" } else { "redundant" }
),
None,
&format!(
"consider renaming the feature to \"{}\"{}",
if is_prefix {
feature.strip_prefix(substring)
} else {
feature.strip_suffix(substring)
}
.unwrap(),
if is_negative {
", but make sure the feature adds functionality"
} else {
""
}
),
);
}
#[test]
fn test_prefixes_sorted() {
let mut sorted_prefixes = PREFIXES;
sorted_prefixes.sort_unstable();
assert_eq!(PREFIXES, sorted_prefixes);
let mut sorted_suffixes = SUFFIXES;
sorted_suffixes.sort_by(|a, b| a.bytes().rev().cmp(b.bytes().rev()));
assert_eq!(SUFFIXES, sorted_suffixes);
} | suffix.bytes().rev().cmp(feature.bytes().rev()) == std::cmp::Ordering::Less
});
if i > 0 && feature.ends_with(SUFFIXES[i - 1]) {
Some(SUFFIXES[i - 1]) |
inquirer.js | const inquirer = require("inquirer");
class | {
constructor(type, name, message, choices) {
this.type = type;
this.name = name;
this.message = message;
this.choices = choices;
}
ask() {
const askObJ = {
type: this.type,
name: this.name,
message: this.message
}
if (this.choices === "undefined") {
return askObJ
} else {
askObJ.choices = this.choices;
return askObJ;
}
}
}
module.exports = InquirerFunctions; | InquirerFunctions |
load_file_into_mod.py | #!/usr/bin/python3
import os
import sys
from shutil import copyfile
import argparse
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
NUMBERED_FILENAME_SPLIT_CHARACTER = "_"
parser = argparse.ArgumentParser(description='')
parser.add_argument('filepath', help='')
parser.add_argument('--force', '-f', action="store_true", help='Override any existing files')
parser.add_argument('--increment', '-i', action="store_true", help='Increment the version number on the file so 00_X.txt will be copied as 01_X.txt')
args = parser.parse_args()
CRUSADER_KINGS_3_CURRENT_MOD_NAME = "CRUSADER_KINGS_3_CURRENT_MOD_NAME"
CRUSADER_KINGS_3_MAIN_DIR = "CRUSADER_KINGS_3_MAIN_DIR"
CRUSADER_KINGS_3_MOD_DIR = "CRUSADER_KINGS_3_MOD_DIR"
mod_name = os.environ.get(CRUSADER_KINGS_3_CURRENT_MOD_NAME, '')
main_directory_str = os.environ.get(CRUSADER_KINGS_3_MAIN_DIR, '').replace(" ", "\\ ")
base_mod_directory_str = os.environ.get(CRUSADER_KINGS_3_MOD_DIR, '').replace(" ", "\\ ")
if not mod_name:
logging.error(f"The {CRUSADER_KINGS_3_CURRENT_MOD_NAME} environment variable must be set")
sys.exit(1)
if not main_directory_str:
logging.error(f"The {CRUSADER_KINGS_3_MAIN_DIR} environment variable must be set")
sys.exit(1)
| sys.exit(1)
main_path = Path(main_directory_str)
if not main_path.exists() or not main_path.is_dir():
logging.error(f"Please ensure that {main_directory_str} points to a valid directory")
sys.exit(1)
base_mod_path = Path(base_mod_directory_str)
if not base_mod_path.exists() or not base_mod_path.is_dir():
logging.error(f"Please ensure that {base_mod_directory_str} points to a valid directory")
sys.exit(1)
mod_directory_str = f"{base_mod_directory_str}/{mod_name}"
mod_path = Path(mod_directory_str)
if not mod_path.exists() or not mod_path.is_dir():
logging.error(f"Please ensure that {mod_directory_str} points to a valid directory")
sys.exit(1)
filepath_str = f"{main_directory_str}/{args.filepath}"
filepath_path = Path(filepath_str)
if not filepath_path.exists() or not filepath_path.is_file():
logging.error(f"Please ensure that {filepath_str} points to an existing file")
sys.exit(1)
destination_filepath = args.filepath
if args.increment:
filepath = Path(args.filepath)
if NUMBERED_FILENAME_SPLIT_CHARACTER in filepath.name:
(n, tail) = filepath.name.split(NUMBERED_FILENAME_SPLIT_CHARACTER, 1)
n = str(int(n) + 1).zfill(len(n))
destination_filepath = str(filepath.parents[0]) + f"/{n}_{tail}"
destination_filepath_str = f"{mod_directory_str}/{destination_filepath}"
destination_filepath_path = Path(destination_filepath_str)
if destination_filepath_path.exists() and not args.force:
logging.error(f"File exists at {destination_filepath_str} already, please use the --force/-f parameter if you want to write over it")
sys.exit(1)
destination_filepath_path.parents[0].mkdir(parents=True, exist_ok=True)
destination_filepath_path.touch(exist_ok=True)
destination_filepath_path.write_text(filepath_path.read_text())
logging.info(f"Created at {destination_filepath_path}") | if not base_mod_directory_str:
logging.error(f"The {CRUSADER_KINGS_3_MOD_DIR} environment variable must be set") |
MetaService.py | #
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
# @generated
#
from __future__ import absolute_import
import six
import sys
from nebula2.fbthrift.util.Recursive import fix_spec
from nebula2.fbthrift.Thrift import TType, TMessageType, TPriority, TRequestContext, TProcessorEventHandler, TServerInterface, TProcessor, TException, TApplicationException, UnimplementedTypedef
from nebula2.fbthrift.protocol.TProtocol import TProtocolException
from .ttypes import UTF8STRINGS, AlterSchemaOp, RoleType, PropertyType, IsolationLevel, HostStatus, SnapshotStatus, AdminJobOp, AdminCmd, JobStatus, ListHostType, HostRole, TaskResult, ConfigModule, ConfigMode, ListenerType, FTServiceType, QueryStatus, ID, ColumnTypeDef, ColumnDef, SchemaProp, Schema, IdName, SpaceDesc, SpaceItem, TagItem, AlterSchemaItem, EdgeItem, SchemaID, IndexItem, HostItem, UserItem, RoleItem, ExecResp, AdminJobReq, JobDesc, TaskDesc, AdminJobResult, AdminJobResp, Correlativity, StatisItem, CreateSpaceReq, DropSpaceReq, ListSpacesReq, ListSpacesResp, GetSpaceReq, GetSpaceResp, CreateTagReq, AlterTagReq, DropTagReq, ListTagsReq, ListTagsResp, GetTagReq, GetTagResp, CreateEdgeReq, AlterEdgeReq, GetEdgeReq, GetEdgeResp, DropEdgeReq, ListEdgesReq, ListEdgesResp, ListHostsReq, ListHostsResp, PartItem, ListPartsReq, ListPartsResp, GetPartsAllocReq, GetPartsAllocResp, MultiPutReq, GetReq, GetResp, MultiGetReq, MultiGetResp, RemoveReq, RemoveRangeReq, ScanReq, ScanResp, HBResp, LeaderInfo, HBReq, IndexFieldDef, CreateTagIndexReq, DropTagIndexReq, GetTagIndexReq, GetTagIndexResp, ListTagIndexesReq, ListTagIndexesResp, CreateEdgeIndexReq, DropEdgeIndexReq, GetEdgeIndexReq, GetEdgeIndexResp, ListEdgeIndexesReq, ListEdgeIndexesResp, RebuildIndexReq, CreateUserReq, DropUserReq, AlterUserReq, GrantRoleReq, RevokeRoleReq, ListUsersReq, ListUsersResp, ListRolesReq, ListRolesResp, GetUserRolesReq, ChangePasswordReq, BalanceReq, BalanceTask, BalanceResp, LeaderBalanceReq, ConfigItem, RegConfigReq, GetConfigReq, GetConfigResp, SetConfigReq, ListConfigsReq, ListConfigsResp, CreateSnapshotReq, DropSnapshotReq, ListSnapshotsReq, Snapshot, ListSnapshotsResp, ListIndexStatusReq, IndexStatus, ListIndexStatusResp, AddZoneReq, DropZoneReq, AddHostIntoZoneReq, DropHostFromZoneReq, GetZoneReq, GetZoneResp, ListZonesReq, Zone, ListZonesResp, AddGroupReq, DropGroupReq, AddZoneIntoGroupReq, DropZoneFromGroupReq, GetGroupReq, GetGroupResp, ListGroupsReq, Group, ListGroupsResp, AddListenerReq, RemoveListenerReq, ListListenerReq, ListenerInfo, ListListenerResp, GetStatisReq, GetStatisResp, BackupInfo, SpaceBackupInfo, BackupMeta, CreateBackupReq, CreateBackupResp, HostPair, RestoreMetaReq, FTClient, SignInFTServiceReq, SignOutFTServiceReq, ListFTClientsReq, ListFTClientsResp, FTIndex, CreateFTIndexReq, DropFTIndexReq, ListFTIndexesReq, ListFTIndexesResp, QueryDesc, Session, CreateSessionReq, CreateSessionResp, UpdateSessionsReq, UpdateSessionsResp, ListSessionsReq, ListSessionsResp, GetSessionReq, GetSessionResp, RemoveSessionReq, KillQueryReq, ReportTaskReq, ListClusterInfoResp, ListClusterInfoReq, GetMetaDirInfoResp, GetMetaDirInfoReq, SchemaVer, ClusterID
import nebula2.common.ttypes
from nebula2.fbthrift.Thrift import TProcessor
import pprint
import warnings
from nebula2.fbthrift import Thrift
from nebula2.fbthrift.transport import TTransport
from nebula2.fbthrift.protocol import TBinaryProtocol
from nebula2.fbthrift.protocol import TCompactProtocol
from nebula2.fbthrift.protocol import THeaderProtocol
fastproto = None
try:
from nebula2.fbthrift.protocol import fastproto
except ImportError:
pass
all_structs = []
UTF8STRINGS = bool(0) or sys.version_info.major >= 3
from nebula2.fbthrift.util.Decorators import (
future_process_main,
future_process_method,
process_main as thrift_process_main,
process_method as thrift_process_method,
should_run_on_thread,
write_results_after_future,
)
class Iface:
def createSpace(self, req=None):
"""
Parameters:
- req
"""
pass
def dropSpace(self, req=None):
"""
Parameters:
- req
"""
pass
def getSpace(self, req=None):
"""
Parameters:
- req
"""
pass
def listSpaces(self, req=None):
"""
Parameters:
- req
"""
pass
def createTag(self, req=None):
"""
Parameters:
- req
"""
pass
def alterTag(self, req=None):
"""
Parameters:
- req
"""
pass
def dropTag(self, req=None):
"""
Parameters:
- req
"""
pass
def getTag(self, req=None):
"""
Parameters:
- req
"""
pass
def listTags(self, req=None):
"""
Parameters:
- req
"""
pass
def createEdge(self, req=None):
"""
Parameters:
- req
"""
pass
def alterEdge(self, req=None):
"""
Parameters:
- req
"""
pass
def dropEdge(self, req=None):
"""
Parameters:
- req
"""
pass
def getEdge(self, req=None):
"""
Parameters:
- req
"""
pass
def listEdges(self, req=None):
"""
Parameters:
- req
"""
pass
def listHosts(self, req=None):
"""
Parameters:
- req
"""
pass
def getPartsAlloc(self, req=None):
"""
Parameters:
- req
"""
pass
def listParts(self, req=None):
"""
Parameters:
- req
"""
pass
def multiPut(self, req=None):
"""
Parameters:
- req
"""
pass
def get(self, req=None):
"""
Parameters:
- req
"""
pass
def multiGet(self, req=None):
"""
Parameters:
- req
"""
pass
def remove(self, req=None):
"""
Parameters:
- req
"""
pass
def removeRange(self, req=None):
"""
Parameters:
- req
"""
pass
def scan(self, req=None):
"""
Parameters:
- req
"""
pass
def createTagIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def dropTagIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def getTagIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def listTagIndexes(self, req=None):
"""
Parameters:
- req
"""
pass
def rebuildTagIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def listTagIndexStatus(self, req=None):
"""
Parameters:
- req
"""
pass
def createEdgeIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def dropEdgeIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def getEdgeIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def listEdgeIndexes(self, req=None):
"""
Parameters:
- req
"""
pass
def rebuildEdgeIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def listEdgeIndexStatus(self, req=None):
"""
Parameters:
- req
"""
pass
def createUser(self, req=None):
"""
Parameters:
- req
"""
pass
def dropUser(self, req=None):
"""
Parameters:
- req
"""
pass
def alterUser(self, req=None):
"""
Parameters:
- req
"""
pass
def grantRole(self, req=None):
"""
Parameters:
- req
"""
pass
def revokeRole(self, req=None):
"""
Parameters:
- req
"""
pass
def listUsers(self, req=None):
"""
Parameters:
- req
"""
pass
def listRoles(self, req=None):
"""
Parameters:
- req
"""
pass
def getUserRoles(self, req=None):
"""
Parameters:
- req
"""
pass
def changePassword(self, req=None):
"""
Parameters:
- req
"""
pass
def heartBeat(self, req=None):
"""
Parameters:
- req
"""
pass
def balance(self, req=None):
"""
Parameters:
- req
"""
pass
def leaderBalance(self, req=None):
"""
Parameters:
- req
"""
pass
def regConfig(self, req=None):
"""
Parameters:
- req
"""
pass
def getConfig(self, req=None):
"""
Parameters:
- req
"""
pass
def setConfig(self, req=None):
"""
Parameters:
- req
"""
pass
def listConfigs(self, req=None):
"""
Parameters:
- req
"""
pass
def createSnapshot(self, req=None):
"""
Parameters:
- req
"""
pass
def dropSnapshot(self, req=None):
"""
Parameters:
- req
"""
pass
def listSnapshots(self, req=None):
"""
Parameters:
- req
"""
pass
def runAdminJob(self, req=None):
"""
Parameters:
- req
"""
pass
def addZone(self, req=None):
"""
Parameters:
- req
"""
pass
def dropZone(self, req=None):
"""
Parameters:
- req
"""
pass
def addHostIntoZone(self, req=None):
"""
Parameters:
- req
"""
pass
def dropHostFromZone(self, req=None):
"""
Parameters:
- req
"""
pass
def getZone(self, req=None):
"""
Parameters:
- req
"""
pass
def listZones(self, req=None):
"""
Parameters:
- req
"""
pass
def addGroup(self, req=None):
"""
Parameters:
- req
"""
pass
def dropGroup(self, req=None):
"""
Parameters:
- req
"""
pass
def addZoneIntoGroup(self, req=None):
"""
Parameters:
- req
"""
pass
def dropZoneFromGroup(self, req=None):
"""
Parameters:
- req
"""
pass
def getGroup(self, req=None):
"""
Parameters:
- req
"""
pass
def listGroups(self, req=None):
"""
Parameters:
- req
"""
pass
def createBackup(self, req=None):
"""
Parameters:
- req
"""
pass
def restoreMeta(self, req=None):
"""
Parameters:
- req
"""
pass
def addListener(self, req=None):
"""
Parameters:
- req
"""
pass
def removeListener(self, req=None):
"""
Parameters:
- req
"""
pass
def listListener(self, req=None):
"""
Parameters:
- req
"""
pass
def getStatis(self, req=None):
"""
Parameters:
- req
"""
pass
def signInFTService(self, req=None):
"""
Parameters:
- req
"""
pass
def signOutFTService(self, req=None):
"""
Parameters:
- req
"""
pass
def listFTClients(self, req=None):
"""
Parameters:
- req
"""
pass
def createFTIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def dropFTIndex(self, req=None):
"""
Parameters:
- req
"""
pass
def listFTIndexes(self, req=None):
"""
Parameters:
- req
"""
pass
def createSession(self, req=None):
"""
Parameters:
- req
"""
pass
def updateSessions(self, req=None):
"""
Parameters:
- req
"""
pass
def listSessions(self, req=None):
"""
Parameters:
- req
"""
pass
def getSession(self, req=None):
"""
Parameters:
- req
"""
pass
def removeSession(self, req=None):
"""
Parameters:
- req
"""
pass
def killQuery(self, req=None):
"""
Parameters:
- req
"""
pass
def reportTaskFinish(self, req=None):
"""
Parameters:
- req
"""
pass
def listCluster(self, req=None):
"""
Parameters:
- req
"""
pass
def getMetaDirInfo(self, req=None):
"""
Parameters:
- req
"""
pass
class ContextIface:
def createSpace(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropSpace(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getSpace(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listSpaces(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createTag(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def alterTag(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropTag(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getTag(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listTags(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createEdge(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def alterEdge(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropEdge(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getEdge(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listEdges(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listHosts(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getPartsAlloc(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listParts(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def multiPut(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def get(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def multiGet(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def remove(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def removeRange(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def scan(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createTagIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropTagIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getTagIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listTagIndexes(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def rebuildTagIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listTagIndexStatus(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createEdgeIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropEdgeIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getEdgeIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listEdgeIndexes(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def rebuildEdgeIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listEdgeIndexStatus(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createUser(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropUser(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def alterUser(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def grantRole(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def revokeRole(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listUsers(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listRoles(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getUserRoles(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def changePassword(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def heartBeat(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def balance(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def leaderBalance(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def regConfig(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getConfig(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def setConfig(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listConfigs(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createSnapshot(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropSnapshot(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listSnapshots(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def runAdminJob(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def addZone(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropZone(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def addHostIntoZone(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropHostFromZone(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getZone(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listZones(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def addGroup(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropGroup(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def addZoneIntoGroup(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropZoneFromGroup(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getGroup(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listGroups(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createBackup(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def restoreMeta(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def addListener(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def removeListener(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listListener(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getStatis(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def signInFTService(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def signOutFTService(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listFTClients(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createFTIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def dropFTIndex(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listFTIndexes(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def createSession(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def updateSessions(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listSessions(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getSession(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def removeSession(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def killQuery(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def reportTaskFinish(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def listCluster(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
def getMetaDirInfo(self, handler_ctx, req=None):
"""
Parameters:
- req
"""
pass
# HELPER FUNCTIONS AND STRUCTURES
class createSpace_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateSpaceReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createSpace_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createSpace_args)
createSpace_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateSpaceReq, CreateSpaceReq.thrift_spec, False], None, 2, ), # 1
)
createSpace_args.thrift_struct_annotations = {
}
createSpace_args.thrift_field_annotations = {
}
def createSpace_args__init__(self, req=None,):
self.req = req
createSpace_args.__init__ = createSpace_args__init__
def createSpace_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createSpace_args.__getstate__ = lambda self: self.__dict__.copy()
createSpace_args.__setstate__ = createSpace_args__setstate__
class createSpace_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createSpace_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createSpace_result)
createSpace_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
createSpace_result.thrift_struct_annotations = {
}
createSpace_result.thrift_field_annotations = {
}
def createSpace_result__init__(self, success=None,):
self.success = success
createSpace_result.__init__ = createSpace_result__init__
def createSpace_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createSpace_result.__getstate__ = lambda self: self.__dict__.copy()
createSpace_result.__setstate__ = createSpace_result__setstate__
class dropSpace_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropSpaceReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropSpace_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropSpace_args)
dropSpace_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropSpaceReq, DropSpaceReq.thrift_spec, False], None, 2, ), # 1
)
dropSpace_args.thrift_struct_annotations = {
}
dropSpace_args.thrift_field_annotations = {
}
def dropSpace_args__init__(self, req=None,):
self.req = req
dropSpace_args.__init__ = dropSpace_args__init__
def dropSpace_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropSpace_args.__getstate__ = lambda self: self.__dict__.copy()
dropSpace_args.__setstate__ = dropSpace_args__setstate__
class dropSpace_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropSpace_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropSpace_result)
dropSpace_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropSpace_result.thrift_struct_annotations = {
}
dropSpace_result.thrift_field_annotations = {
}
def dropSpace_result__init__(self, success=None,):
self.success = success
dropSpace_result.__init__ = dropSpace_result__init__
def dropSpace_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropSpace_result.__getstate__ = lambda self: self.__dict__.copy()
dropSpace_result.__setstate__ = dropSpace_result__setstate__
class getSpace_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetSpaceReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getSpace_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getSpace_args)
getSpace_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetSpaceReq, GetSpaceReq.thrift_spec, False], None, 2, ), # 1
)
getSpace_args.thrift_struct_annotations = {
}
getSpace_args.thrift_field_annotations = {
}
def getSpace_args__init__(self, req=None,):
self.req = req
getSpace_args.__init__ = getSpace_args__init__
def getSpace_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getSpace_args.__getstate__ = lambda self: self.__dict__.copy()
getSpace_args.__setstate__ = getSpace_args__setstate__
class getSpace_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetSpaceResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getSpace_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getSpace_result)
getSpace_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetSpaceResp, GetSpaceResp.thrift_spec, False], None, 2, ), # 0
)
getSpace_result.thrift_struct_annotations = {
}
getSpace_result.thrift_field_annotations = {
}
def getSpace_result__init__(self, success=None,):
self.success = success
getSpace_result.__init__ = getSpace_result__init__
def getSpace_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getSpace_result.__getstate__ = lambda self: self.__dict__.copy()
getSpace_result.__setstate__ = getSpace_result__setstate__
class listSpaces_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListSpacesReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listSpaces_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listSpaces_args)
listSpaces_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListSpacesReq, ListSpacesReq.thrift_spec, False], None, 2, ), # 1
)
listSpaces_args.thrift_struct_annotations = {
}
listSpaces_args.thrift_field_annotations = {
}
def listSpaces_args__init__(self, req=None,):
self.req = req
listSpaces_args.__init__ = listSpaces_args__init__
def listSpaces_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listSpaces_args.__getstate__ = lambda self: self.__dict__.copy()
listSpaces_args.__setstate__ = listSpaces_args__setstate__
class listSpaces_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListSpacesResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listSpaces_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listSpaces_result)
listSpaces_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListSpacesResp, ListSpacesResp.thrift_spec, False], None, 2, ), # 0
)
listSpaces_result.thrift_struct_annotations = {
}
listSpaces_result.thrift_field_annotations = {
}
def listSpaces_result__init__(self, success=None,):
self.success = success
listSpaces_result.__init__ = listSpaces_result__init__
def listSpaces_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listSpaces_result.__getstate__ = lambda self: self.__dict__.copy()
listSpaces_result.__setstate__ = listSpaces_result__setstate__
class createTag_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateTagReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createTag_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createTag_args)
createTag_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateTagReq, CreateTagReq.thrift_spec, False], None, 2, ), # 1
)
createTag_args.thrift_struct_annotations = {
}
createTag_args.thrift_field_annotations = {
}
def createTag_args__init__(self, req=None,):
self.req = req
createTag_args.__init__ = createTag_args__init__
def createTag_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createTag_args.__getstate__ = lambda self: self.__dict__.copy()
createTag_args.__setstate__ = createTag_args__setstate__
class createTag_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createTag_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createTag_result)
createTag_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
createTag_result.thrift_struct_annotations = {
}
createTag_result.thrift_field_annotations = {
}
def createTag_result__init__(self, success=None,):
self.success = success
createTag_result.__init__ = createTag_result__init__
def createTag_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createTag_result.__getstate__ = lambda self: self.__dict__.copy()
createTag_result.__setstate__ = createTag_result__setstate__
class alterTag_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AlterTagReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('alterTag_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(alterTag_args)
alterTag_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AlterTagReq, AlterTagReq.thrift_spec, False], None, 2, ), # 1
)
alterTag_args.thrift_struct_annotations = {
}
alterTag_args.thrift_field_annotations = {
}
def alterTag_args__init__(self, req=None,):
self.req = req
alterTag_args.__init__ = alterTag_args__init__
def alterTag_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
alterTag_args.__getstate__ = lambda self: self.__dict__.copy()
alterTag_args.__setstate__ = alterTag_args__setstate__
class alterTag_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('alterTag_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(alterTag_result)
alterTag_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
alterTag_result.thrift_struct_annotations = {
}
alterTag_result.thrift_field_annotations = {
}
def alterTag_result__init__(self, success=None,):
self.success = success
alterTag_result.__init__ = alterTag_result__init__
def alterTag_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
alterTag_result.__getstate__ = lambda self: self.__dict__.copy()
alterTag_result.__setstate__ = alterTag_result__setstate__
class dropTag_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropTagReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropTag_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropTag_args)
dropTag_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropTagReq, DropTagReq.thrift_spec, False], None, 2, ), # 1
)
dropTag_args.thrift_struct_annotations = {
}
dropTag_args.thrift_field_annotations = {
}
def dropTag_args__init__(self, req=None,):
self.req = req
dropTag_args.__init__ = dropTag_args__init__
def dropTag_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropTag_args.__getstate__ = lambda self: self.__dict__.copy()
dropTag_args.__setstate__ = dropTag_args__setstate__
class dropTag_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropTag_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropTag_result)
dropTag_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropTag_result.thrift_struct_annotations = {
}
dropTag_result.thrift_field_annotations = {
}
def dropTag_result__init__(self, success=None,):
self.success = success
dropTag_result.__init__ = dropTag_result__init__
def dropTag_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropTag_result.__getstate__ = lambda self: self.__dict__.copy()
dropTag_result.__setstate__ = dropTag_result__setstate__
class getTag_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetTagReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getTag_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getTag_args)
getTag_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetTagReq, GetTagReq.thrift_spec, False], None, 2, ), # 1
)
getTag_args.thrift_struct_annotations = {
}
getTag_args.thrift_field_annotations = {
}
def getTag_args__init__(self, req=None,):
self.req = req
getTag_args.__init__ = getTag_args__init__
def getTag_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getTag_args.__getstate__ = lambda self: self.__dict__.copy()
getTag_args.__setstate__ = getTag_args__setstate__
class getTag_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetTagResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getTag_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getTag_result)
getTag_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetTagResp, GetTagResp.thrift_spec, False], None, 2, ), # 0
)
getTag_result.thrift_struct_annotations = {
}
getTag_result.thrift_field_annotations = {
}
def getTag_result__init__(self, success=None,):
self.success = success
getTag_result.__init__ = getTag_result__init__
def getTag_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getTag_result.__getstate__ = lambda self: self.__dict__.copy()
getTag_result.__setstate__ = getTag_result__setstate__
class listTags_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListTagsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listTags_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listTags_args)
listTags_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListTagsReq, ListTagsReq.thrift_spec, False], None, 2, ), # 1
)
listTags_args.thrift_struct_annotations = {
}
listTags_args.thrift_field_annotations = {
}
def listTags_args__init__(self, req=None,):
self.req = req
listTags_args.__init__ = listTags_args__init__
def listTags_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listTags_args.__getstate__ = lambda self: self.__dict__.copy()
listTags_args.__setstate__ = listTags_args__setstate__
class listTags_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListTagsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listTags_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listTags_result)
listTags_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListTagsResp, ListTagsResp.thrift_spec, False], None, 2, ), # 0
)
listTags_result.thrift_struct_annotations = {
}
listTags_result.thrift_field_annotations = {
}
def listTags_result__init__(self, success=None,):
self.success = success
listTags_result.__init__ = listTags_result__init__
def listTags_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listTags_result.__getstate__ = lambda self: self.__dict__.copy()
listTags_result.__setstate__ = listTags_result__setstate__
class createEdge_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateEdgeReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createEdge_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createEdge_args)
createEdge_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateEdgeReq, CreateEdgeReq.thrift_spec, False], None, 2, ), # 1
)
createEdge_args.thrift_struct_annotations = {
}
createEdge_args.thrift_field_annotations = {
}
def createEdge_args__init__(self, req=None,):
self.req = req
createEdge_args.__init__ = createEdge_args__init__
def createEdge_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createEdge_args.__getstate__ = lambda self: self.__dict__.copy()
createEdge_args.__setstate__ = createEdge_args__setstate__
class createEdge_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createEdge_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createEdge_result)
createEdge_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
createEdge_result.thrift_struct_annotations = {
}
createEdge_result.thrift_field_annotations = {
}
def createEdge_result__init__(self, success=None,):
self.success = success
createEdge_result.__init__ = createEdge_result__init__
def createEdge_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createEdge_result.__getstate__ = lambda self: self.__dict__.copy()
createEdge_result.__setstate__ = createEdge_result__setstate__
class alterEdge_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AlterEdgeReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('alterEdge_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(alterEdge_args)
alterEdge_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AlterEdgeReq, AlterEdgeReq.thrift_spec, False], None, 2, ), # 1
)
alterEdge_args.thrift_struct_annotations = {
}
alterEdge_args.thrift_field_annotations = {
}
def alterEdge_args__init__(self, req=None,):
self.req = req
alterEdge_args.__init__ = alterEdge_args__init__
def alterEdge_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
alterEdge_args.__getstate__ = lambda self: self.__dict__.copy()
alterEdge_args.__setstate__ = alterEdge_args__setstate__
class alterEdge_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('alterEdge_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(alterEdge_result)
alterEdge_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
alterEdge_result.thrift_struct_annotations = {
}
alterEdge_result.thrift_field_annotations = {
}
def alterEdge_result__init__(self, success=None,):
self.success = success
alterEdge_result.__init__ = alterEdge_result__init__
def alterEdge_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
alterEdge_result.__getstate__ = lambda self: self.__dict__.copy()
alterEdge_result.__setstate__ = alterEdge_result__setstate__
class dropEdge_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropEdgeReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropEdge_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropEdge_args)
dropEdge_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropEdgeReq, DropEdgeReq.thrift_spec, False], None, 2, ), # 1
)
dropEdge_args.thrift_struct_annotations = {
}
dropEdge_args.thrift_field_annotations = {
}
def dropEdge_args__init__(self, req=None,):
self.req = req
dropEdge_args.__init__ = dropEdge_args__init__
def dropEdge_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropEdge_args.__getstate__ = lambda self: self.__dict__.copy()
dropEdge_args.__setstate__ = dropEdge_args__setstate__
class dropEdge_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropEdge_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropEdge_result)
dropEdge_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropEdge_result.thrift_struct_annotations = {
}
dropEdge_result.thrift_field_annotations = {
}
def dropEdge_result__init__(self, success=None,):
self.success = success
dropEdge_result.__init__ = dropEdge_result__init__
def dropEdge_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropEdge_result.__getstate__ = lambda self: self.__dict__.copy()
dropEdge_result.__setstate__ = dropEdge_result__setstate__
class getEdge_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetEdgeReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getEdge_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getEdge_args)
getEdge_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetEdgeReq, GetEdgeReq.thrift_spec, False], None, 2, ), # 1
)
getEdge_args.thrift_struct_annotations = {
}
getEdge_args.thrift_field_annotations = {
}
def getEdge_args__init__(self, req=None,):
self.req = req
getEdge_args.__init__ = getEdge_args__init__
def getEdge_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getEdge_args.__getstate__ = lambda self: self.__dict__.copy()
getEdge_args.__setstate__ = getEdge_args__setstate__
class getEdge_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetEdgeResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getEdge_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getEdge_result)
getEdge_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetEdgeResp, GetEdgeResp.thrift_spec, False], None, 2, ), # 0
)
getEdge_result.thrift_struct_annotations = {
}
getEdge_result.thrift_field_annotations = {
}
def getEdge_result__init__(self, success=None,):
self.success = success
getEdge_result.__init__ = getEdge_result__init__
def getEdge_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getEdge_result.__getstate__ = lambda self: self.__dict__.copy()
getEdge_result.__setstate__ = getEdge_result__setstate__
class listEdges_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListEdgesReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listEdges_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listEdges_args)
listEdges_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListEdgesReq, ListEdgesReq.thrift_spec, False], None, 2, ), # 1
)
listEdges_args.thrift_struct_annotations = {
}
listEdges_args.thrift_field_annotations = {
}
def listEdges_args__init__(self, req=None,):
self.req = req
listEdges_args.__init__ = listEdges_args__init__
def listEdges_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listEdges_args.__getstate__ = lambda self: self.__dict__.copy()
listEdges_args.__setstate__ = listEdges_args__setstate__
class listEdges_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListEdgesResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listEdges_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listEdges_result)
listEdges_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListEdgesResp, ListEdgesResp.thrift_spec, False], None, 2, ), # 0
)
listEdges_result.thrift_struct_annotations = {
}
listEdges_result.thrift_field_annotations = {
}
def listEdges_result__init__(self, success=None,):
self.success = success
listEdges_result.__init__ = listEdges_result__init__
def listEdges_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listEdges_result.__getstate__ = lambda self: self.__dict__.copy()
listEdges_result.__setstate__ = listEdges_result__setstate__
class listHosts_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListHostsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listHosts_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listHosts_args)
listHosts_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListHostsReq, ListHostsReq.thrift_spec, False], None, 2, ), # 1
)
listHosts_args.thrift_struct_annotations = {
}
listHosts_args.thrift_field_annotations = {
}
def listHosts_args__init__(self, req=None,):
self.req = req
listHosts_args.__init__ = listHosts_args__init__
def listHosts_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listHosts_args.__getstate__ = lambda self: self.__dict__.copy()
listHosts_args.__setstate__ = listHosts_args__setstate__
class listHosts_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListHostsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listHosts_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listHosts_result)
listHosts_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListHostsResp, ListHostsResp.thrift_spec, False], None, 2, ), # 0
)
listHosts_result.thrift_struct_annotations = {
}
listHosts_result.thrift_field_annotations = {
}
def listHosts_result__init__(self, success=None,):
self.success = success
listHosts_result.__init__ = listHosts_result__init__
def listHosts_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listHosts_result.__getstate__ = lambda self: self.__dict__.copy()
listHosts_result.__setstate__ = listHosts_result__setstate__
class getPartsAlloc_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetPartsAllocReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getPartsAlloc_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getPartsAlloc_args)
getPartsAlloc_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetPartsAllocReq, GetPartsAllocReq.thrift_spec, False], None, 2, ), # 1
)
getPartsAlloc_args.thrift_struct_annotations = {
}
getPartsAlloc_args.thrift_field_annotations = {
}
def getPartsAlloc_args__init__(self, req=None,):
self.req = req
getPartsAlloc_args.__init__ = getPartsAlloc_args__init__
def getPartsAlloc_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getPartsAlloc_args.__getstate__ = lambda self: self.__dict__.copy()
getPartsAlloc_args.__setstate__ = getPartsAlloc_args__setstate__
class getPartsAlloc_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetPartsAllocResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getPartsAlloc_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getPartsAlloc_result)
getPartsAlloc_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetPartsAllocResp, GetPartsAllocResp.thrift_spec, False], None, 2, ), # 0
)
getPartsAlloc_result.thrift_struct_annotations = {
}
getPartsAlloc_result.thrift_field_annotations = {
}
def getPartsAlloc_result__init__(self, success=None,):
self.success = success
getPartsAlloc_result.__init__ = getPartsAlloc_result__init__
def getPartsAlloc_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getPartsAlloc_result.__getstate__ = lambda self: self.__dict__.copy()
getPartsAlloc_result.__setstate__ = getPartsAlloc_result__setstate__
class listParts_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListPartsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listParts_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listParts_args)
listParts_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListPartsReq, ListPartsReq.thrift_spec, False], None, 2, ), # 1
)
listParts_args.thrift_struct_annotations = {
}
listParts_args.thrift_field_annotations = {
}
def listParts_args__init__(self, req=None,):
self.req = req
listParts_args.__init__ = listParts_args__init__
def listParts_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listParts_args.__getstate__ = lambda self: self.__dict__.copy()
listParts_args.__setstate__ = listParts_args__setstate__
class listParts_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListPartsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listParts_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listParts_result)
listParts_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListPartsResp, ListPartsResp.thrift_spec, False], None, 2, ), # 0
)
listParts_result.thrift_struct_annotations = {
}
listParts_result.thrift_field_annotations = {
}
def listParts_result__init__(self, success=None,):
self.success = success
listParts_result.__init__ = listParts_result__init__
def listParts_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listParts_result.__getstate__ = lambda self: self.__dict__.copy()
listParts_result.__setstate__ = listParts_result__setstate__
class multiPut_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = MultiPutReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('multiPut_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(multiPut_args)
multiPut_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [MultiPutReq, MultiPutReq.thrift_spec, False], None, 2, ), # 1
)
multiPut_args.thrift_struct_annotations = {
}
multiPut_args.thrift_field_annotations = {
}
def multiPut_args__init__(self, req=None,):
self.req = req
multiPut_args.__init__ = multiPut_args__init__
def multiPut_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
multiPut_args.__getstate__ = lambda self: self.__dict__.copy()
multiPut_args.__setstate__ = multiPut_args__setstate__
class multiPut_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('multiPut_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(multiPut_result)
multiPut_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
multiPut_result.thrift_struct_annotations = {
}
multiPut_result.thrift_field_annotations = {
}
def multiPut_result__init__(self, success=None,):
self.success = success
multiPut_result.__init__ = multiPut_result__init__
def multiPut_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
multiPut_result.__getstate__ = lambda self: self.__dict__.copy()
multiPut_result.__setstate__ = multiPut_result__setstate__
class get_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('get_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(get_args)
get_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetReq, GetReq.thrift_spec, False], None, 2, ), # 1
)
get_args.thrift_struct_annotations = {
}
get_args.thrift_field_annotations = {
}
def get_args__init__(self, req=None,):
self.req = req
get_args.__init__ = get_args__init__
def get_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
get_args.__getstate__ = lambda self: self.__dict__.copy()
get_args.__setstate__ = get_args__setstate__
class get_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('get_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(get_result)
get_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetResp, GetResp.thrift_spec, False], None, 2, ), # 0
)
get_result.thrift_struct_annotations = {
}
get_result.thrift_field_annotations = {
}
def get_result__init__(self, success=None,):
self.success = success
get_result.__init__ = get_result__init__
def get_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
get_result.__getstate__ = lambda self: self.__dict__.copy()
get_result.__setstate__ = get_result__setstate__
class multiGet_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = MultiGetReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('multiGet_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(multiGet_args)
multiGet_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [MultiGetReq, MultiGetReq.thrift_spec, False], None, 2, ), # 1
)
multiGet_args.thrift_struct_annotations = {
}
multiGet_args.thrift_field_annotations = {
}
def multiGet_args__init__(self, req=None,):
self.req = req
multiGet_args.__init__ = multiGet_args__init__
def multiGet_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
multiGet_args.__getstate__ = lambda self: self.__dict__.copy()
multiGet_args.__setstate__ = multiGet_args__setstate__
class multiGet_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = MultiGetResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('multiGet_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(multiGet_result)
multiGet_result.thrift_spec = (
(0, TType.STRUCT, 'success', [MultiGetResp, MultiGetResp.thrift_spec, False], None, 2, ), # 0
)
multiGet_result.thrift_struct_annotations = {
}
multiGet_result.thrift_field_annotations = {
}
def multiGet_result__init__(self, success=None,):
self.success = success
multiGet_result.__init__ = multiGet_result__init__
def multiGet_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
multiGet_result.__getstate__ = lambda self: self.__dict__.copy()
multiGet_result.__setstate__ = multiGet_result__setstate__
class remove_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RemoveReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('remove_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(remove_args)
remove_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RemoveReq, RemoveReq.thrift_spec, False], None, 2, ), # 1
)
remove_args.thrift_struct_annotations = {
}
remove_args.thrift_field_annotations = {
}
def remove_args__init__(self, req=None,):
self.req = req
remove_args.__init__ = remove_args__init__
def remove_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
remove_args.__getstate__ = lambda self: self.__dict__.copy()
remove_args.__setstate__ = remove_args__setstate__
class remove_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('remove_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(remove_result)
remove_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
remove_result.thrift_struct_annotations = {
}
remove_result.thrift_field_annotations = {
}
def remove_result__init__(self, success=None,):
self.success = success
remove_result.__init__ = remove_result__init__
def remove_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
remove_result.__getstate__ = lambda self: self.__dict__.copy()
remove_result.__setstate__ = remove_result__setstate__
class removeRange_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RemoveRangeReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('removeRange_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(removeRange_args)
removeRange_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RemoveRangeReq, RemoveRangeReq.thrift_spec, False], None, 2, ), # 1
)
removeRange_args.thrift_struct_annotations = {
}
removeRange_args.thrift_field_annotations = {
}
def removeRange_args__init__(self, req=None,):
self.req = req
removeRange_args.__init__ = removeRange_args__init__
def removeRange_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
removeRange_args.__getstate__ = lambda self: self.__dict__.copy()
removeRange_args.__setstate__ = removeRange_args__setstate__
class removeRange_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('removeRange_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(removeRange_result)
removeRange_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
removeRange_result.thrift_struct_annotations = {
}
removeRange_result.thrift_field_annotations = {
}
def removeRange_result__init__(self, success=None,):
self.success = success
removeRange_result.__init__ = removeRange_result__init__
def removeRange_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
removeRange_result.__getstate__ = lambda self: self.__dict__.copy()
removeRange_result.__setstate__ = removeRange_result__setstate__
class scan_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ScanReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('scan_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(scan_args)
scan_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ScanReq, ScanReq.thrift_spec, False], None, 2, ), # 1
)
scan_args.thrift_struct_annotations = {
}
scan_args.thrift_field_annotations = {
}
def scan_args__init__(self, req=None,):
self.req = req
scan_args.__init__ = scan_args__init__
def scan_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
scan_args.__getstate__ = lambda self: self.__dict__.copy()
scan_args.__setstate__ = scan_args__setstate__
class scan_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ScanResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('scan_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(scan_result)
scan_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ScanResp, ScanResp.thrift_spec, False], None, 2, ), # 0
)
scan_result.thrift_struct_annotations = {
}
scan_result.thrift_field_annotations = {
}
def scan_result__init__(self, success=None,):
self.success = success
scan_result.__init__ = scan_result__init__
def scan_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
scan_result.__getstate__ = lambda self: self.__dict__.copy()
scan_result.__setstate__ = scan_result__setstate__
class createTagIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateTagIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createTagIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createTagIndex_args)
createTagIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateTagIndexReq, CreateTagIndexReq.thrift_spec, False], None, 2, ), # 1
)
createTagIndex_args.thrift_struct_annotations = {
}
createTagIndex_args.thrift_field_annotations = {
}
def createTagIndex_args__init__(self, req=None,):
self.req = req
createTagIndex_args.__init__ = createTagIndex_args__init__
def createTagIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createTagIndex_args.__getstate__ = lambda self: self.__dict__.copy()
createTagIndex_args.__setstate__ = createTagIndex_args__setstate__
class createTagIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createTagIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createTagIndex_result)
createTagIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
createTagIndex_result.thrift_struct_annotations = {
}
createTagIndex_result.thrift_field_annotations = {
}
def createTagIndex_result__init__(self, success=None,):
self.success = success
createTagIndex_result.__init__ = createTagIndex_result__init__
def createTagIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createTagIndex_result.__getstate__ = lambda self: self.__dict__.copy()
createTagIndex_result.__setstate__ = createTagIndex_result__setstate__
class dropTagIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropTagIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropTagIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropTagIndex_args)
dropTagIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropTagIndexReq, DropTagIndexReq.thrift_spec, False], None, 2, ), # 1
)
dropTagIndex_args.thrift_struct_annotations = {
}
dropTagIndex_args.thrift_field_annotations = {
}
def dropTagIndex_args__init__(self, req=None,):
self.req = req
dropTagIndex_args.__init__ = dropTagIndex_args__init__
def dropTagIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropTagIndex_args.__getstate__ = lambda self: self.__dict__.copy()
dropTagIndex_args.__setstate__ = dropTagIndex_args__setstate__
class dropTagIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropTagIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropTagIndex_result)
dropTagIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropTagIndex_result.thrift_struct_annotations = {
}
dropTagIndex_result.thrift_field_annotations = {
}
def dropTagIndex_result__init__(self, success=None,):
self.success = success
dropTagIndex_result.__init__ = dropTagIndex_result__init__
def dropTagIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropTagIndex_result.__getstate__ = lambda self: self.__dict__.copy()
dropTagIndex_result.__setstate__ = dropTagIndex_result__setstate__
class getTagIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetTagIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getTagIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getTagIndex_args)
getTagIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetTagIndexReq, GetTagIndexReq.thrift_spec, False], None, 2, ), # 1
)
getTagIndex_args.thrift_struct_annotations = {
}
getTagIndex_args.thrift_field_annotations = {
}
def getTagIndex_args__init__(self, req=None,):
self.req = req
getTagIndex_args.__init__ = getTagIndex_args__init__
def getTagIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getTagIndex_args.__getstate__ = lambda self: self.__dict__.copy()
getTagIndex_args.__setstate__ = getTagIndex_args__setstate__
class getTagIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetTagIndexResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getTagIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getTagIndex_result)
getTagIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetTagIndexResp, GetTagIndexResp.thrift_spec, False], None, 2, ), # 0
)
getTagIndex_result.thrift_struct_annotations = {
}
getTagIndex_result.thrift_field_annotations = {
}
def getTagIndex_result__init__(self, success=None,):
self.success = success
getTagIndex_result.__init__ = getTagIndex_result__init__
def getTagIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getTagIndex_result.__getstate__ = lambda self: self.__dict__.copy()
getTagIndex_result.__setstate__ = getTagIndex_result__setstate__
class listTagIndexes_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListTagIndexesReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listTagIndexes_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listTagIndexes_args)
listTagIndexes_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListTagIndexesReq, ListTagIndexesReq.thrift_spec, False], None, 2, ), # 1
)
listTagIndexes_args.thrift_struct_annotations = {
}
listTagIndexes_args.thrift_field_annotations = {
}
def listTagIndexes_args__init__(self, req=None,):
self.req = req
listTagIndexes_args.__init__ = listTagIndexes_args__init__
def listTagIndexes_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listTagIndexes_args.__getstate__ = lambda self: self.__dict__.copy()
listTagIndexes_args.__setstate__ = listTagIndexes_args__setstate__
class listTagIndexes_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListTagIndexesResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listTagIndexes_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listTagIndexes_result)
listTagIndexes_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListTagIndexesResp, ListTagIndexesResp.thrift_spec, False], None, 2, ), # 0
)
listTagIndexes_result.thrift_struct_annotations = {
}
listTagIndexes_result.thrift_field_annotations = {
}
def listTagIndexes_result__init__(self, success=None,):
self.success = success
listTagIndexes_result.__init__ = listTagIndexes_result__init__
def listTagIndexes_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listTagIndexes_result.__getstate__ = lambda self: self.__dict__.copy()
listTagIndexes_result.__setstate__ = listTagIndexes_result__setstate__
class rebuildTagIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RebuildIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('rebuildTagIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(rebuildTagIndex_args)
rebuildTagIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RebuildIndexReq, RebuildIndexReq.thrift_spec, False], None, 2, ), # 1
)
rebuildTagIndex_args.thrift_struct_annotations = {
}
rebuildTagIndex_args.thrift_field_annotations = {
}
def rebuildTagIndex_args__init__(self, req=None,):
self.req = req
rebuildTagIndex_args.__init__ = rebuildTagIndex_args__init__
def rebuildTagIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
rebuildTagIndex_args.__getstate__ = lambda self: self.__dict__.copy()
rebuildTagIndex_args.__setstate__ = rebuildTagIndex_args__setstate__
class rebuildTagIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('rebuildTagIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(rebuildTagIndex_result)
rebuildTagIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
rebuildTagIndex_result.thrift_struct_annotations = {
}
rebuildTagIndex_result.thrift_field_annotations = {
}
def rebuildTagIndex_result__init__(self, success=None,):
self.success = success
rebuildTagIndex_result.__init__ = rebuildTagIndex_result__init__
def rebuildTagIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
rebuildTagIndex_result.__getstate__ = lambda self: self.__dict__.copy()
rebuildTagIndex_result.__setstate__ = rebuildTagIndex_result__setstate__
class listTagIndexStatus_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListIndexStatusReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listTagIndexStatus_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listTagIndexStatus_args)
listTagIndexStatus_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListIndexStatusReq, ListIndexStatusReq.thrift_spec, False], None, 2, ), # 1
)
listTagIndexStatus_args.thrift_struct_annotations = {
}
listTagIndexStatus_args.thrift_field_annotations = {
}
def listTagIndexStatus_args__init__(self, req=None,):
self.req = req
listTagIndexStatus_args.__init__ = listTagIndexStatus_args__init__
def listTagIndexStatus_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listTagIndexStatus_args.__getstate__ = lambda self: self.__dict__.copy()
listTagIndexStatus_args.__setstate__ = listTagIndexStatus_args__setstate__
class listTagIndexStatus_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListIndexStatusResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listTagIndexStatus_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listTagIndexStatus_result)
listTagIndexStatus_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListIndexStatusResp, ListIndexStatusResp.thrift_spec, False], None, 2, ), # 0
)
listTagIndexStatus_result.thrift_struct_annotations = {
}
listTagIndexStatus_result.thrift_field_annotations = {
}
def listTagIndexStatus_result__init__(self, success=None,):
self.success = success
listTagIndexStatus_result.__init__ = listTagIndexStatus_result__init__
def listTagIndexStatus_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listTagIndexStatus_result.__getstate__ = lambda self: self.__dict__.copy()
listTagIndexStatus_result.__setstate__ = listTagIndexStatus_result__setstate__
class createEdgeIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateEdgeIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createEdgeIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createEdgeIndex_args)
createEdgeIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateEdgeIndexReq, CreateEdgeIndexReq.thrift_spec, False], None, 2, ), # 1
)
createEdgeIndex_args.thrift_struct_annotations = {
}
createEdgeIndex_args.thrift_field_annotations = {
}
def createEdgeIndex_args__init__(self, req=None,):
self.req = req
createEdgeIndex_args.__init__ = createEdgeIndex_args__init__
def createEdgeIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createEdgeIndex_args.__getstate__ = lambda self: self.__dict__.copy()
createEdgeIndex_args.__setstate__ = createEdgeIndex_args__setstate__
class createEdgeIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createEdgeIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createEdgeIndex_result)
createEdgeIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
createEdgeIndex_result.thrift_struct_annotations = {
}
createEdgeIndex_result.thrift_field_annotations = {
}
def createEdgeIndex_result__init__(self, success=None,):
self.success = success
createEdgeIndex_result.__init__ = createEdgeIndex_result__init__
def createEdgeIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createEdgeIndex_result.__getstate__ = lambda self: self.__dict__.copy()
createEdgeIndex_result.__setstate__ = createEdgeIndex_result__setstate__
class dropEdgeIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropEdgeIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropEdgeIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropEdgeIndex_args)
dropEdgeIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropEdgeIndexReq, DropEdgeIndexReq.thrift_spec, False], None, 2, ), # 1
)
dropEdgeIndex_args.thrift_struct_annotations = {
}
dropEdgeIndex_args.thrift_field_annotations = {
}
def dropEdgeIndex_args__init__(self, req=None,):
self.req = req
dropEdgeIndex_args.__init__ = dropEdgeIndex_args__init__
def dropEdgeIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropEdgeIndex_args.__getstate__ = lambda self: self.__dict__.copy()
dropEdgeIndex_args.__setstate__ = dropEdgeIndex_args__setstate__
class dropEdgeIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropEdgeIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropEdgeIndex_result)
dropEdgeIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropEdgeIndex_result.thrift_struct_annotations = {
}
dropEdgeIndex_result.thrift_field_annotations = {
}
def dropEdgeIndex_result__init__(self, success=None,):
self.success = success
dropEdgeIndex_result.__init__ = dropEdgeIndex_result__init__
def dropEdgeIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropEdgeIndex_result.__getstate__ = lambda self: self.__dict__.copy()
dropEdgeIndex_result.__setstate__ = dropEdgeIndex_result__setstate__
class getEdgeIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetEdgeIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getEdgeIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getEdgeIndex_args)
getEdgeIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetEdgeIndexReq, GetEdgeIndexReq.thrift_spec, False], None, 2, ), # 1
)
getEdgeIndex_args.thrift_struct_annotations = {
}
getEdgeIndex_args.thrift_field_annotations = {
}
def getEdgeIndex_args__init__(self, req=None,):
self.req = req
getEdgeIndex_args.__init__ = getEdgeIndex_args__init__
def getEdgeIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getEdgeIndex_args.__getstate__ = lambda self: self.__dict__.copy()
getEdgeIndex_args.__setstate__ = getEdgeIndex_args__setstate__
class getEdgeIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetEdgeIndexResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getEdgeIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getEdgeIndex_result)
getEdgeIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetEdgeIndexResp, GetEdgeIndexResp.thrift_spec, False], None, 2, ), # 0
)
getEdgeIndex_result.thrift_struct_annotations = {
}
getEdgeIndex_result.thrift_field_annotations = {
}
def getEdgeIndex_result__init__(self, success=None,):
self.success = success
getEdgeIndex_result.__init__ = getEdgeIndex_result__init__
def getEdgeIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getEdgeIndex_result.__getstate__ = lambda self: self.__dict__.copy()
getEdgeIndex_result.__setstate__ = getEdgeIndex_result__setstate__
class listEdgeIndexes_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListEdgeIndexesReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listEdgeIndexes_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listEdgeIndexes_args)
listEdgeIndexes_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListEdgeIndexesReq, ListEdgeIndexesReq.thrift_spec, False], None, 2, ), # 1
)
listEdgeIndexes_args.thrift_struct_annotations = {
}
listEdgeIndexes_args.thrift_field_annotations = {
}
def listEdgeIndexes_args__init__(self, req=None,):
self.req = req
listEdgeIndexes_args.__init__ = listEdgeIndexes_args__init__
def listEdgeIndexes_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listEdgeIndexes_args.__getstate__ = lambda self: self.__dict__.copy()
listEdgeIndexes_args.__setstate__ = listEdgeIndexes_args__setstate__
class listEdgeIndexes_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListEdgeIndexesResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listEdgeIndexes_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listEdgeIndexes_result)
listEdgeIndexes_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListEdgeIndexesResp, ListEdgeIndexesResp.thrift_spec, False], None, 2, ), # 0
)
listEdgeIndexes_result.thrift_struct_annotations = {
}
listEdgeIndexes_result.thrift_field_annotations = {
}
def listEdgeIndexes_result__init__(self, success=None,):
self.success = success
listEdgeIndexes_result.__init__ = listEdgeIndexes_result__init__
def listEdgeIndexes_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listEdgeIndexes_result.__getstate__ = lambda self: self.__dict__.copy()
listEdgeIndexes_result.__setstate__ = listEdgeIndexes_result__setstate__
class rebuildEdgeIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RebuildIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('rebuildEdgeIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(rebuildEdgeIndex_args)
rebuildEdgeIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RebuildIndexReq, RebuildIndexReq.thrift_spec, False], None, 2, ), # 1
)
rebuildEdgeIndex_args.thrift_struct_annotations = {
}
rebuildEdgeIndex_args.thrift_field_annotations = {
}
def rebuildEdgeIndex_args__init__(self, req=None,):
self.req = req
rebuildEdgeIndex_args.__init__ = rebuildEdgeIndex_args__init__
def rebuildEdgeIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
rebuildEdgeIndex_args.__getstate__ = lambda self: self.__dict__.copy()
rebuildEdgeIndex_args.__setstate__ = rebuildEdgeIndex_args__setstate__
class rebuildEdgeIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('rebuildEdgeIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(rebuildEdgeIndex_result)
rebuildEdgeIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
rebuildEdgeIndex_result.thrift_struct_annotations = {
}
rebuildEdgeIndex_result.thrift_field_annotations = {
}
def rebuildEdgeIndex_result__init__(self, success=None,):
self.success = success
rebuildEdgeIndex_result.__init__ = rebuildEdgeIndex_result__init__
def rebuildEdgeIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
rebuildEdgeIndex_result.__getstate__ = lambda self: self.__dict__.copy()
rebuildEdgeIndex_result.__setstate__ = rebuildEdgeIndex_result__setstate__
class listEdgeIndexStatus_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListIndexStatusReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listEdgeIndexStatus_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listEdgeIndexStatus_args)
listEdgeIndexStatus_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListIndexStatusReq, ListIndexStatusReq.thrift_spec, False], None, 2, ), # 1
)
listEdgeIndexStatus_args.thrift_struct_annotations = {
}
listEdgeIndexStatus_args.thrift_field_annotations = {
}
def listEdgeIndexStatus_args__init__(self, req=None,):
self.req = req
listEdgeIndexStatus_args.__init__ = listEdgeIndexStatus_args__init__
def listEdgeIndexStatus_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listEdgeIndexStatus_args.__getstate__ = lambda self: self.__dict__.copy()
listEdgeIndexStatus_args.__setstate__ = listEdgeIndexStatus_args__setstate__
class listEdgeIndexStatus_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListIndexStatusResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listEdgeIndexStatus_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listEdgeIndexStatus_result)
listEdgeIndexStatus_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListIndexStatusResp, ListIndexStatusResp.thrift_spec, False], None, 2, ), # 0
)
listEdgeIndexStatus_result.thrift_struct_annotations = {
}
listEdgeIndexStatus_result.thrift_field_annotations = {
}
def listEdgeIndexStatus_result__init__(self, success=None,):
self.success = success
listEdgeIndexStatus_result.__init__ = listEdgeIndexStatus_result__init__
def listEdgeIndexStatus_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listEdgeIndexStatus_result.__getstate__ = lambda self: self.__dict__.copy()
listEdgeIndexStatus_result.__setstate__ = listEdgeIndexStatus_result__setstate__
class createUser_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateUserReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createUser_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createUser_args)
createUser_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateUserReq, CreateUserReq.thrift_spec, False], None, 2, ), # 1
)
createUser_args.thrift_struct_annotations = {
}
createUser_args.thrift_field_annotations = {
}
def createUser_args__init__(self, req=None,):
self.req = req
createUser_args.__init__ = createUser_args__init__
def createUser_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createUser_args.__getstate__ = lambda self: self.__dict__.copy()
createUser_args.__setstate__ = createUser_args__setstate__
class createUser_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createUser_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createUser_result)
createUser_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
createUser_result.thrift_struct_annotations = {
}
createUser_result.thrift_field_annotations = {
}
def createUser_result__init__(self, success=None,):
self.success = success
createUser_result.__init__ = createUser_result__init__
def createUser_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createUser_result.__getstate__ = lambda self: self.__dict__.copy()
createUser_result.__setstate__ = createUser_result__setstate__
class dropUser_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropUserReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropUser_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropUser_args)
dropUser_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropUserReq, DropUserReq.thrift_spec, False], None, 2, ), # 1
)
dropUser_args.thrift_struct_annotations = {
}
dropUser_args.thrift_field_annotations = {
}
def dropUser_args__init__(self, req=None,):
self.req = req
dropUser_args.__init__ = dropUser_args__init__
def dropUser_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropUser_args.__getstate__ = lambda self: self.__dict__.copy()
dropUser_args.__setstate__ = dropUser_args__setstate__
class dropUser_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropUser_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropUser_result)
dropUser_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropUser_result.thrift_struct_annotations = {
}
dropUser_result.thrift_field_annotations = {
}
def dropUser_result__init__(self, success=None,):
self.success = success
dropUser_result.__init__ = dropUser_result__init__
def dropUser_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropUser_result.__getstate__ = lambda self: self.__dict__.copy()
dropUser_result.__setstate__ = dropUser_result__setstate__
class alterUser_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AlterUserReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('alterUser_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(alterUser_args)
alterUser_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AlterUserReq, AlterUserReq.thrift_spec, False], None, 2, ), # 1
)
alterUser_args.thrift_struct_annotations = {
}
alterUser_args.thrift_field_annotations = {
}
def alterUser_args__init__(self, req=None,):
self.req = req
alterUser_args.__init__ = alterUser_args__init__
def alterUser_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
alterUser_args.__getstate__ = lambda self: self.__dict__.copy()
alterUser_args.__setstate__ = alterUser_args__setstate__
class alterUser_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('alterUser_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(alterUser_result)
alterUser_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
alterUser_result.thrift_struct_annotations = {
}
alterUser_result.thrift_field_annotations = {
}
def alterUser_result__init__(self, success=None,):
self.success = success
alterUser_result.__init__ = alterUser_result__init__
def alterUser_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
alterUser_result.__getstate__ = lambda self: self.__dict__.copy()
alterUser_result.__setstate__ = alterUser_result__setstate__
class grantRole_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GrantRoleReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('grantRole_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(grantRole_args)
grantRole_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GrantRoleReq, GrantRoleReq.thrift_spec, False], None, 2, ), # 1
)
grantRole_args.thrift_struct_annotations = {
}
grantRole_args.thrift_field_annotations = {
}
def grantRole_args__init__(self, req=None,):
self.req = req
grantRole_args.__init__ = grantRole_args__init__
def grantRole_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
grantRole_args.__getstate__ = lambda self: self.__dict__.copy()
grantRole_args.__setstate__ = grantRole_args__setstate__
class grantRole_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('grantRole_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(grantRole_result)
grantRole_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
grantRole_result.thrift_struct_annotations = {
}
grantRole_result.thrift_field_annotations = {
}
def grantRole_result__init__(self, success=None,):
self.success = success
grantRole_result.__init__ = grantRole_result__init__
def grantRole_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
grantRole_result.__getstate__ = lambda self: self.__dict__.copy()
grantRole_result.__setstate__ = grantRole_result__setstate__
class revokeRole_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RevokeRoleReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('revokeRole_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(revokeRole_args)
revokeRole_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RevokeRoleReq, RevokeRoleReq.thrift_spec, False], None, 2, ), # 1
)
revokeRole_args.thrift_struct_annotations = {
}
revokeRole_args.thrift_field_annotations = {
}
def revokeRole_args__init__(self, req=None,):
self.req = req
revokeRole_args.__init__ = revokeRole_args__init__
def revokeRole_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
revokeRole_args.__getstate__ = lambda self: self.__dict__.copy()
revokeRole_args.__setstate__ = revokeRole_args__setstate__
class revokeRole_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('revokeRole_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(revokeRole_result)
revokeRole_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
revokeRole_result.thrift_struct_annotations = {
}
revokeRole_result.thrift_field_annotations = {
}
def revokeRole_result__init__(self, success=None,):
self.success = success
revokeRole_result.__init__ = revokeRole_result__init__
def revokeRole_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
revokeRole_result.__getstate__ = lambda self: self.__dict__.copy()
revokeRole_result.__setstate__ = revokeRole_result__setstate__
class listUsers_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListUsersReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listUsers_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listUsers_args)
listUsers_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListUsersReq, ListUsersReq.thrift_spec, False], None, 2, ), # 1
)
listUsers_args.thrift_struct_annotations = {
}
listUsers_args.thrift_field_annotations = {
}
def listUsers_args__init__(self, req=None,):
self.req = req
listUsers_args.__init__ = listUsers_args__init__
def listUsers_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listUsers_args.__getstate__ = lambda self: self.__dict__.copy()
listUsers_args.__setstate__ = listUsers_args__setstate__
class listUsers_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListUsersResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listUsers_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listUsers_result)
listUsers_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListUsersResp, ListUsersResp.thrift_spec, False], None, 2, ), # 0
)
listUsers_result.thrift_struct_annotations = {
}
listUsers_result.thrift_field_annotations = {
}
def listUsers_result__init__(self, success=None,):
self.success = success
listUsers_result.__init__ = listUsers_result__init__
def listUsers_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listUsers_result.__getstate__ = lambda self: self.__dict__.copy()
listUsers_result.__setstate__ = listUsers_result__setstate__
class listRoles_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListRolesReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listRoles_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listRoles_args)
listRoles_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListRolesReq, ListRolesReq.thrift_spec, False], None, 2, ), # 1
)
listRoles_args.thrift_struct_annotations = {
}
listRoles_args.thrift_field_annotations = {
}
def listRoles_args__init__(self, req=None,):
self.req = req
listRoles_args.__init__ = listRoles_args__init__
def listRoles_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listRoles_args.__getstate__ = lambda self: self.__dict__.copy()
listRoles_args.__setstate__ = listRoles_args__setstate__
class listRoles_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListRolesResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listRoles_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listRoles_result)
listRoles_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListRolesResp, ListRolesResp.thrift_spec, False], None, 2, ), # 0
)
listRoles_result.thrift_struct_annotations = {
}
listRoles_result.thrift_field_annotations = {
}
def listRoles_result__init__(self, success=None,):
self.success = success
listRoles_result.__init__ = listRoles_result__init__
def listRoles_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listRoles_result.__getstate__ = lambda self: self.__dict__.copy()
listRoles_result.__setstate__ = listRoles_result__setstate__
class getUserRoles_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetUserRolesReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getUserRoles_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getUserRoles_args)
getUserRoles_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetUserRolesReq, GetUserRolesReq.thrift_spec, False], None, 2, ), # 1
)
getUserRoles_args.thrift_struct_annotations = {
}
getUserRoles_args.thrift_field_annotations = {
}
def getUserRoles_args__init__(self, req=None,):
self.req = req
getUserRoles_args.__init__ = getUserRoles_args__init__
def getUserRoles_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getUserRoles_args.__getstate__ = lambda self: self.__dict__.copy()
getUserRoles_args.__setstate__ = getUserRoles_args__setstate__
class getUserRoles_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListRolesResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getUserRoles_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getUserRoles_result)
getUserRoles_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListRolesResp, ListRolesResp.thrift_spec, False], None, 2, ), # 0
)
getUserRoles_result.thrift_struct_annotations = {
}
getUserRoles_result.thrift_field_annotations = {
}
def getUserRoles_result__init__(self, success=None,):
self.success = success
getUserRoles_result.__init__ = getUserRoles_result__init__
def getUserRoles_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getUserRoles_result.__getstate__ = lambda self: self.__dict__.copy()
getUserRoles_result.__setstate__ = getUserRoles_result__setstate__
class changePassword_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ChangePasswordReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('changePassword_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(changePassword_args)
changePassword_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ChangePasswordReq, ChangePasswordReq.thrift_spec, False], None, 2, ), # 1
)
changePassword_args.thrift_struct_annotations = {
}
changePassword_args.thrift_field_annotations = {
}
def changePassword_args__init__(self, req=None,):
self.req = req
changePassword_args.__init__ = changePassword_args__init__
def changePassword_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
changePassword_args.__getstate__ = lambda self: self.__dict__.copy()
changePassword_args.__setstate__ = changePassword_args__setstate__
class changePassword_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('changePassword_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(changePassword_result)
changePassword_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
changePassword_result.thrift_struct_annotations = {
}
changePassword_result.thrift_field_annotations = {
}
def changePassword_result__init__(self, success=None,):
self.success = success
changePassword_result.__init__ = changePassword_result__init__
def changePassword_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
changePassword_result.__getstate__ = lambda self: self.__dict__.copy()
changePassword_result.__setstate__ = changePassword_result__setstate__
class heartBeat_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = HBReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('heartBeat_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(heartBeat_args)
heartBeat_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [HBReq, HBReq.thrift_spec, False], None, 2, ), # 1
)
heartBeat_args.thrift_struct_annotations = {
}
heartBeat_args.thrift_field_annotations = {
}
def heartBeat_args__init__(self, req=None,):
self.req = req
heartBeat_args.__init__ = heartBeat_args__init__
def heartBeat_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
heartBeat_args.__getstate__ = lambda self: self.__dict__.copy()
heartBeat_args.__setstate__ = heartBeat_args__setstate__
class heartBeat_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = HBResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('heartBeat_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(heartBeat_result)
heartBeat_result.thrift_spec = (
(0, TType.STRUCT, 'success', [HBResp, HBResp.thrift_spec, False], None, 2, ), # 0
)
heartBeat_result.thrift_struct_annotations = {
}
heartBeat_result.thrift_field_annotations = {
}
def heartBeat_result__init__(self, success=None,):
self.success = success
heartBeat_result.__init__ = heartBeat_result__init__
def heartBeat_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
heartBeat_result.__getstate__ = lambda self: self.__dict__.copy()
heartBeat_result.__setstate__ = heartBeat_result__setstate__
class balance_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = BalanceReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('balance_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(balance_args)
balance_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [BalanceReq, BalanceReq.thrift_spec, False], None, 2, ), # 1
)
balance_args.thrift_struct_annotations = {
}
balance_args.thrift_field_annotations = {
}
def balance_args__init__(self, req=None,):
self.req = req
balance_args.__init__ = balance_args__init__
def balance_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
balance_args.__getstate__ = lambda self: self.__dict__.copy()
balance_args.__setstate__ = balance_args__setstate__
class balance_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = BalanceResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('balance_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(balance_result)
balance_result.thrift_spec = (
(0, TType.STRUCT, 'success', [BalanceResp, BalanceResp.thrift_spec, False], None, 2, ), # 0
)
balance_result.thrift_struct_annotations = {
}
balance_result.thrift_field_annotations = {
}
def balance_result__init__(self, success=None,):
self.success = success
balance_result.__init__ = balance_result__init__
def balance_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
balance_result.__getstate__ = lambda self: self.__dict__.copy()
balance_result.__setstate__ = balance_result__setstate__
class leaderBalance_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = LeaderBalanceReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('leaderBalance_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(leaderBalance_args)
leaderBalance_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [LeaderBalanceReq, LeaderBalanceReq.thrift_spec, False], None, 2, ), # 1
)
leaderBalance_args.thrift_struct_annotations = {
}
leaderBalance_args.thrift_field_annotations = {
}
def leaderBalance_args__init__(self, req=None,):
self.req = req
leaderBalance_args.__init__ = leaderBalance_args__init__
def leaderBalance_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
leaderBalance_args.__getstate__ = lambda self: self.__dict__.copy()
leaderBalance_args.__setstate__ = leaderBalance_args__setstate__
class leaderBalance_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('leaderBalance_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(leaderBalance_result)
leaderBalance_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
leaderBalance_result.thrift_struct_annotations = {
}
leaderBalance_result.thrift_field_annotations = {
}
def leaderBalance_result__init__(self, success=None,):
self.success = success
leaderBalance_result.__init__ = leaderBalance_result__init__
def leaderBalance_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
leaderBalance_result.__getstate__ = lambda self: self.__dict__.copy()
leaderBalance_result.__setstate__ = leaderBalance_result__setstate__
class regConfig_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RegConfigReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('regConfig_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(regConfig_args)
regConfig_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RegConfigReq, RegConfigReq.thrift_spec, False], None, 2, ), # 1
)
regConfig_args.thrift_struct_annotations = {
}
regConfig_args.thrift_field_annotations = {
}
def regConfig_args__init__(self, req=None,):
self.req = req
regConfig_args.__init__ = regConfig_args__init__
def regConfig_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
regConfig_args.__getstate__ = lambda self: self.__dict__.copy()
regConfig_args.__setstate__ = regConfig_args__setstate__
class regConfig_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('regConfig_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(regConfig_result)
regConfig_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
regConfig_result.thrift_struct_annotations = {
}
regConfig_result.thrift_field_annotations = {
}
def regConfig_result__init__(self, success=None,):
self.success = success
regConfig_result.__init__ = regConfig_result__init__
def regConfig_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
regConfig_result.__getstate__ = lambda self: self.__dict__.copy()
regConfig_result.__setstate__ = regConfig_result__setstate__
class getConfig_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetConfigReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getConfig_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getConfig_args)
getConfig_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetConfigReq, GetConfigReq.thrift_spec, False], None, 2, ), # 1
)
getConfig_args.thrift_struct_annotations = {
}
getConfig_args.thrift_field_annotations = {
}
def getConfig_args__init__(self, req=None,):
self.req = req
getConfig_args.__init__ = getConfig_args__init__
def getConfig_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getConfig_args.__getstate__ = lambda self: self.__dict__.copy()
getConfig_args.__setstate__ = getConfig_args__setstate__
class getConfig_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetConfigResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getConfig_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getConfig_result)
getConfig_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetConfigResp, GetConfigResp.thrift_spec, False], None, 2, ), # 0
)
getConfig_result.thrift_struct_annotations = {
}
getConfig_result.thrift_field_annotations = {
}
def getConfig_result__init__(self, success=None,):
self.success = success
getConfig_result.__init__ = getConfig_result__init__
def getConfig_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getConfig_result.__getstate__ = lambda self: self.__dict__.copy()
getConfig_result.__setstate__ = getConfig_result__setstate__
class setConfig_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = SetConfigReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('setConfig_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(setConfig_args)
setConfig_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [SetConfigReq, SetConfigReq.thrift_spec, False], None, 2, ), # 1
)
setConfig_args.thrift_struct_annotations = {
}
setConfig_args.thrift_field_annotations = {
}
def setConfig_args__init__(self, req=None,):
self.req = req
setConfig_args.__init__ = setConfig_args__init__
def setConfig_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
setConfig_args.__getstate__ = lambda self: self.__dict__.copy()
setConfig_args.__setstate__ = setConfig_args__setstate__
class setConfig_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('setConfig_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(setConfig_result)
setConfig_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
setConfig_result.thrift_struct_annotations = {
}
setConfig_result.thrift_field_annotations = {
}
def setConfig_result__init__(self, success=None,):
self.success = success
setConfig_result.__init__ = setConfig_result__init__
def setConfig_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
setConfig_result.__getstate__ = lambda self: self.__dict__.copy()
setConfig_result.__setstate__ = setConfig_result__setstate__
class listConfigs_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListConfigsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listConfigs_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listConfigs_args)
listConfigs_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListConfigsReq, ListConfigsReq.thrift_spec, False], None, 2, ), # 1
)
listConfigs_args.thrift_struct_annotations = {
}
listConfigs_args.thrift_field_annotations = {
}
def listConfigs_args__init__(self, req=None,):
self.req = req
listConfigs_args.__init__ = listConfigs_args__init__
def listConfigs_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listConfigs_args.__getstate__ = lambda self: self.__dict__.copy()
listConfigs_args.__setstate__ = listConfigs_args__setstate__
class listConfigs_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListConfigsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listConfigs_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listConfigs_result)
listConfigs_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListConfigsResp, ListConfigsResp.thrift_spec, False], None, 2, ), # 0
)
listConfigs_result.thrift_struct_annotations = {
}
listConfigs_result.thrift_field_annotations = {
}
def listConfigs_result__init__(self, success=None,):
self.success = success
listConfigs_result.__init__ = listConfigs_result__init__
def listConfigs_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listConfigs_result.__getstate__ = lambda self: self.__dict__.copy()
listConfigs_result.__setstate__ = listConfigs_result__setstate__
class createSnapshot_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateSnapshotReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createSnapshot_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createSnapshot_args)
createSnapshot_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateSnapshotReq, CreateSnapshotReq.thrift_spec, False], None, 2, ), # 1
)
createSnapshot_args.thrift_struct_annotations = {
}
createSnapshot_args.thrift_field_annotations = {
}
def createSnapshot_args__init__(self, req=None,):
self.req = req
createSnapshot_args.__init__ = createSnapshot_args__init__
def createSnapshot_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createSnapshot_args.__getstate__ = lambda self: self.__dict__.copy()
createSnapshot_args.__setstate__ = createSnapshot_args__setstate__
class createSnapshot_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createSnapshot_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createSnapshot_result)
createSnapshot_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
createSnapshot_result.thrift_struct_annotations = {
}
createSnapshot_result.thrift_field_annotations = {
}
def createSnapshot_result__init__(self, success=None,):
self.success = success
createSnapshot_result.__init__ = createSnapshot_result__init__
def createSnapshot_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createSnapshot_result.__getstate__ = lambda self: self.__dict__.copy()
createSnapshot_result.__setstate__ = createSnapshot_result__setstate__
class dropSnapshot_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropSnapshotReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropSnapshot_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropSnapshot_args)
dropSnapshot_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropSnapshotReq, DropSnapshotReq.thrift_spec, False], None, 2, ), # 1
)
dropSnapshot_args.thrift_struct_annotations = {
}
dropSnapshot_args.thrift_field_annotations = {
}
def dropSnapshot_args__init__(self, req=None,):
self.req = req
dropSnapshot_args.__init__ = dropSnapshot_args__init__
def dropSnapshot_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropSnapshot_args.__getstate__ = lambda self: self.__dict__.copy()
dropSnapshot_args.__setstate__ = dropSnapshot_args__setstate__
class dropSnapshot_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropSnapshot_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropSnapshot_result)
dropSnapshot_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropSnapshot_result.thrift_struct_annotations = {
}
dropSnapshot_result.thrift_field_annotations = {
}
def dropSnapshot_result__init__(self, success=None,):
self.success = success
dropSnapshot_result.__init__ = dropSnapshot_result__init__
def dropSnapshot_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropSnapshot_result.__getstate__ = lambda self: self.__dict__.copy()
dropSnapshot_result.__setstate__ = dropSnapshot_result__setstate__
class listSnapshots_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListSnapshotsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listSnapshots_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listSnapshots_args)
listSnapshots_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListSnapshotsReq, ListSnapshotsReq.thrift_spec, False], None, 2, ), # 1
)
listSnapshots_args.thrift_struct_annotations = {
}
listSnapshots_args.thrift_field_annotations = {
}
def listSnapshots_args__init__(self, req=None,):
self.req = req
listSnapshots_args.__init__ = listSnapshots_args__init__
def listSnapshots_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listSnapshots_args.__getstate__ = lambda self: self.__dict__.copy()
listSnapshots_args.__setstate__ = listSnapshots_args__setstate__
class listSnapshots_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListSnapshotsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listSnapshots_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listSnapshots_result)
listSnapshots_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListSnapshotsResp, ListSnapshotsResp.thrift_spec, False], None, 2, ), # 0
)
listSnapshots_result.thrift_struct_annotations = {
}
listSnapshots_result.thrift_field_annotations = {
}
def listSnapshots_result__init__(self, success=None,):
self.success = success
listSnapshots_result.__init__ = listSnapshots_result__init__
def listSnapshots_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listSnapshots_result.__getstate__ = lambda self: self.__dict__.copy()
listSnapshots_result.__setstate__ = listSnapshots_result__setstate__
class runAdminJob_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AdminJobReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('runAdminJob_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(runAdminJob_args)
runAdminJob_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AdminJobReq, AdminJobReq.thrift_spec, False], None, 2, ), # 1
)
runAdminJob_args.thrift_struct_annotations = {
}
runAdminJob_args.thrift_field_annotations = {
}
def runAdminJob_args__init__(self, req=None,):
self.req = req
runAdminJob_args.__init__ = runAdminJob_args__init__
def runAdminJob_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
runAdminJob_args.__getstate__ = lambda self: self.__dict__.copy()
runAdminJob_args.__setstate__ = runAdminJob_args__setstate__
class runAdminJob_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = AdminJobResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('runAdminJob_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(runAdminJob_result)
runAdminJob_result.thrift_spec = (
(0, TType.STRUCT, 'success', [AdminJobResp, AdminJobResp.thrift_spec, False], None, 2, ), # 0
)
runAdminJob_result.thrift_struct_annotations = {
}
runAdminJob_result.thrift_field_annotations = {
}
def runAdminJob_result__init__(self, success=None,):
self.success = success
runAdminJob_result.__init__ = runAdminJob_result__init__
def runAdminJob_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
runAdminJob_result.__getstate__ = lambda self: self.__dict__.copy()
runAdminJob_result.__setstate__ = runAdminJob_result__setstate__
class addZone_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AddZoneReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addZone_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addZone_args)
addZone_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AddZoneReq, AddZoneReq.thrift_spec, False], None, 2, ), # 1
)
addZone_args.thrift_struct_annotations = {
}
addZone_args.thrift_field_annotations = {
}
def addZone_args__init__(self, req=None,):
self.req = req
addZone_args.__init__ = addZone_args__init__
def addZone_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
addZone_args.__getstate__ = lambda self: self.__dict__.copy()
addZone_args.__setstate__ = addZone_args__setstate__
class addZone_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addZone_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addZone_result)
addZone_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
addZone_result.thrift_struct_annotations = {
}
addZone_result.thrift_field_annotations = {
}
def addZone_result__init__(self, success=None,):
self.success = success
addZone_result.__init__ = addZone_result__init__
def addZone_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
addZone_result.__getstate__ = lambda self: self.__dict__.copy()
addZone_result.__setstate__ = addZone_result__setstate__
class dropZone_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropZoneReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropZone_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropZone_args)
dropZone_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropZoneReq, DropZoneReq.thrift_spec, False], None, 2, ), # 1
)
dropZone_args.thrift_struct_annotations = {
}
dropZone_args.thrift_field_annotations = {
}
def dropZone_args__init__(self, req=None,):
self.req = req
dropZone_args.__init__ = dropZone_args__init__
def dropZone_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropZone_args.__getstate__ = lambda self: self.__dict__.copy()
dropZone_args.__setstate__ = dropZone_args__setstate__
class dropZone_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropZone_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropZone_result)
dropZone_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropZone_result.thrift_struct_annotations = {
}
dropZone_result.thrift_field_annotations = {
}
def dropZone_result__init__(self, success=None,):
self.success = success
dropZone_result.__init__ = dropZone_result__init__
def dropZone_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropZone_result.__getstate__ = lambda self: self.__dict__.copy()
dropZone_result.__setstate__ = dropZone_result__setstate__
class addHostIntoZone_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AddHostIntoZoneReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addHostIntoZone_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addHostIntoZone_args)
addHostIntoZone_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AddHostIntoZoneReq, AddHostIntoZoneReq.thrift_spec, False], None, 2, ), # 1
)
addHostIntoZone_args.thrift_struct_annotations = {
}
addHostIntoZone_args.thrift_field_annotations = {
}
def addHostIntoZone_args__init__(self, req=None,):
self.req = req
addHostIntoZone_args.__init__ = addHostIntoZone_args__init__
def addHostIntoZone_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
addHostIntoZone_args.__getstate__ = lambda self: self.__dict__.copy()
addHostIntoZone_args.__setstate__ = addHostIntoZone_args__setstate__
class addHostIntoZone_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addHostIntoZone_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addHostIntoZone_result)
addHostIntoZone_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
addHostIntoZone_result.thrift_struct_annotations = {
}
addHostIntoZone_result.thrift_field_annotations = {
}
def addHostIntoZone_result__init__(self, success=None,):
self.success = success
addHostIntoZone_result.__init__ = addHostIntoZone_result__init__
def addHostIntoZone_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
addHostIntoZone_result.__getstate__ = lambda self: self.__dict__.copy()
addHostIntoZone_result.__setstate__ = addHostIntoZone_result__setstate__
class dropHostFromZone_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropHostFromZoneReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropHostFromZone_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropHostFromZone_args)
dropHostFromZone_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropHostFromZoneReq, DropHostFromZoneReq.thrift_spec, False], None, 2, ), # 1
)
dropHostFromZone_args.thrift_struct_annotations = {
}
dropHostFromZone_args.thrift_field_annotations = {
}
def dropHostFromZone_args__init__(self, req=None,):
self.req = req
dropHostFromZone_args.__init__ = dropHostFromZone_args__init__
def dropHostFromZone_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropHostFromZone_args.__getstate__ = lambda self: self.__dict__.copy()
dropHostFromZone_args.__setstate__ = dropHostFromZone_args__setstate__
class dropHostFromZone_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropHostFromZone_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropHostFromZone_result)
dropHostFromZone_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropHostFromZone_result.thrift_struct_annotations = {
}
dropHostFromZone_result.thrift_field_annotations = {
}
def dropHostFromZone_result__init__(self, success=None,):
self.success = success
dropHostFromZone_result.__init__ = dropHostFromZone_result__init__
def dropHostFromZone_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropHostFromZone_result.__getstate__ = lambda self: self.__dict__.copy()
dropHostFromZone_result.__setstate__ = dropHostFromZone_result__setstate__
class getZone_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetZoneReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getZone_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getZone_args)
getZone_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetZoneReq, GetZoneReq.thrift_spec, False], None, 2, ), # 1
)
getZone_args.thrift_struct_annotations = {
}
getZone_args.thrift_field_annotations = {
}
def getZone_args__init__(self, req=None,):
self.req = req
getZone_args.__init__ = getZone_args__init__
def getZone_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getZone_args.__getstate__ = lambda self: self.__dict__.copy()
getZone_args.__setstate__ = getZone_args__setstate__
class getZone_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetZoneResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getZone_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getZone_result)
getZone_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetZoneResp, GetZoneResp.thrift_spec, False], None, 2, ), # 0
)
getZone_result.thrift_struct_annotations = {
}
getZone_result.thrift_field_annotations = {
}
def getZone_result__init__(self, success=None,):
self.success = success
getZone_result.__init__ = getZone_result__init__
def getZone_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getZone_result.__getstate__ = lambda self: self.__dict__.copy()
getZone_result.__setstate__ = getZone_result__setstate__
class listZones_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListZonesReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listZones_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listZones_args)
listZones_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListZonesReq, ListZonesReq.thrift_spec, False], None, 2, ), # 1
)
listZones_args.thrift_struct_annotations = {
}
listZones_args.thrift_field_annotations = {
}
def listZones_args__init__(self, req=None,):
self.req = req
listZones_args.__init__ = listZones_args__init__
def listZones_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listZones_args.__getstate__ = lambda self: self.__dict__.copy()
listZones_args.__setstate__ = listZones_args__setstate__
class listZones_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListZonesResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listZones_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listZones_result)
listZones_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListZonesResp, ListZonesResp.thrift_spec, False], None, 2, ), # 0
)
listZones_result.thrift_struct_annotations = {
}
listZones_result.thrift_field_annotations = {
}
def listZones_result__init__(self, success=None,):
self.success = success
listZones_result.__init__ = listZones_result__init__
def listZones_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listZones_result.__getstate__ = lambda self: self.__dict__.copy()
listZones_result.__setstate__ = listZones_result__setstate__
class addGroup_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AddGroupReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addGroup_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addGroup_args)
addGroup_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AddGroupReq, AddGroupReq.thrift_spec, False], None, 2, ), # 1
)
addGroup_args.thrift_struct_annotations = {
}
addGroup_args.thrift_field_annotations = {
}
def addGroup_args__init__(self, req=None,):
self.req = req
addGroup_args.__init__ = addGroup_args__init__
def addGroup_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
addGroup_args.__getstate__ = lambda self: self.__dict__.copy()
addGroup_args.__setstate__ = addGroup_args__setstate__
class addGroup_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addGroup_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addGroup_result)
addGroup_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
addGroup_result.thrift_struct_annotations = {
}
addGroup_result.thrift_field_annotations = {
}
def addGroup_result__init__(self, success=None,):
self.success = success
addGroup_result.__init__ = addGroup_result__init__
def addGroup_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
addGroup_result.__getstate__ = lambda self: self.__dict__.copy()
addGroup_result.__setstate__ = addGroup_result__setstate__
class dropGroup_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropGroupReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropGroup_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropGroup_args)
dropGroup_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropGroupReq, DropGroupReq.thrift_spec, False], None, 2, ), # 1
)
dropGroup_args.thrift_struct_annotations = {
}
dropGroup_args.thrift_field_annotations = {
}
def dropGroup_args__init__(self, req=None,):
self.req = req
dropGroup_args.__init__ = dropGroup_args__init__
def dropGroup_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropGroup_args.__getstate__ = lambda self: self.__dict__.copy()
dropGroup_args.__setstate__ = dropGroup_args__setstate__
class dropGroup_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropGroup_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropGroup_result)
dropGroup_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropGroup_result.thrift_struct_annotations = {
}
dropGroup_result.thrift_field_annotations = {
}
def dropGroup_result__init__(self, success=None,):
self.success = success
dropGroup_result.__init__ = dropGroup_result__init__
def dropGroup_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropGroup_result.__getstate__ = lambda self: self.__dict__.copy()
dropGroup_result.__setstate__ = dropGroup_result__setstate__
class addZoneIntoGroup_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AddZoneIntoGroupReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addZoneIntoGroup_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addZoneIntoGroup_args)
addZoneIntoGroup_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AddZoneIntoGroupReq, AddZoneIntoGroupReq.thrift_spec, False], None, 2, ), # 1
)
addZoneIntoGroup_args.thrift_struct_annotations = {
}
addZoneIntoGroup_args.thrift_field_annotations = {
}
def addZoneIntoGroup_args__init__(self, req=None,):
self.req = req
addZoneIntoGroup_args.__init__ = addZoneIntoGroup_args__init__
def addZoneIntoGroup_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
addZoneIntoGroup_args.__getstate__ = lambda self: self.__dict__.copy()
addZoneIntoGroup_args.__setstate__ = addZoneIntoGroup_args__setstate__
class addZoneIntoGroup_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addZoneIntoGroup_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addZoneIntoGroup_result)
addZoneIntoGroup_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
addZoneIntoGroup_result.thrift_struct_annotations = {
}
addZoneIntoGroup_result.thrift_field_annotations = {
}
def addZoneIntoGroup_result__init__(self, success=None,):
self.success = success
addZoneIntoGroup_result.__init__ = addZoneIntoGroup_result__init__
def addZoneIntoGroup_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
addZoneIntoGroup_result.__getstate__ = lambda self: self.__dict__.copy()
addZoneIntoGroup_result.__setstate__ = addZoneIntoGroup_result__setstate__
class dropZoneFromGroup_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropZoneFromGroupReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropZoneFromGroup_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropZoneFromGroup_args)
dropZoneFromGroup_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropZoneFromGroupReq, DropZoneFromGroupReq.thrift_spec, False], None, 2, ), # 1
)
dropZoneFromGroup_args.thrift_struct_annotations = {
}
dropZoneFromGroup_args.thrift_field_annotations = {
}
def dropZoneFromGroup_args__init__(self, req=None,):
self.req = req
dropZoneFromGroup_args.__init__ = dropZoneFromGroup_args__init__
def dropZoneFromGroup_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropZoneFromGroup_args.__getstate__ = lambda self: self.__dict__.copy()
dropZoneFromGroup_args.__setstate__ = dropZoneFromGroup_args__setstate__
class dropZoneFromGroup_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropZoneFromGroup_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropZoneFromGroup_result)
dropZoneFromGroup_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropZoneFromGroup_result.thrift_struct_annotations = {
}
dropZoneFromGroup_result.thrift_field_annotations = {
}
def dropZoneFromGroup_result__init__(self, success=None,):
self.success = success
dropZoneFromGroup_result.__init__ = dropZoneFromGroup_result__init__
def dropZoneFromGroup_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropZoneFromGroup_result.__getstate__ = lambda self: self.__dict__.copy()
dropZoneFromGroup_result.__setstate__ = dropZoneFromGroup_result__setstate__
class getGroup_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetGroupReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getGroup_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getGroup_args)
getGroup_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetGroupReq, GetGroupReq.thrift_spec, False], None, 2, ), # 1
)
getGroup_args.thrift_struct_annotations = {
}
getGroup_args.thrift_field_annotations = {
}
def getGroup_args__init__(self, req=None,):
self.req = req
getGroup_args.__init__ = getGroup_args__init__
def getGroup_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getGroup_args.__getstate__ = lambda self: self.__dict__.copy()
getGroup_args.__setstate__ = getGroup_args__setstate__
class getGroup_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetGroupResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getGroup_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getGroup_result)
getGroup_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetGroupResp, GetGroupResp.thrift_spec, False], None, 2, ), # 0
)
getGroup_result.thrift_struct_annotations = {
}
getGroup_result.thrift_field_annotations = {
}
def getGroup_result__init__(self, success=None,):
self.success = success
getGroup_result.__init__ = getGroup_result__init__
def getGroup_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getGroup_result.__getstate__ = lambda self: self.__dict__.copy()
getGroup_result.__setstate__ = getGroup_result__setstate__
class listGroups_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListGroupsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listGroups_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listGroups_args)
listGroups_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListGroupsReq, ListGroupsReq.thrift_spec, False], None, 2, ), # 1
)
listGroups_args.thrift_struct_annotations = {
}
listGroups_args.thrift_field_annotations = {
}
def listGroups_args__init__(self, req=None,):
self.req = req
listGroups_args.__init__ = listGroups_args__init__
def listGroups_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listGroups_args.__getstate__ = lambda self: self.__dict__.copy()
listGroups_args.__setstate__ = listGroups_args__setstate__
class listGroups_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListGroupsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listGroups_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listGroups_result)
listGroups_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListGroupsResp, ListGroupsResp.thrift_spec, False], None, 2, ), # 0
)
listGroups_result.thrift_struct_annotations = {
}
listGroups_result.thrift_field_annotations = {
}
def listGroups_result__init__(self, success=None,):
self.success = success
listGroups_result.__init__ = listGroups_result__init__
def listGroups_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listGroups_result.__getstate__ = lambda self: self.__dict__.copy()
listGroups_result.__setstate__ = listGroups_result__setstate__
class createBackup_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateBackupReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createBackup_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createBackup_args)
createBackup_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateBackupReq, CreateBackupReq.thrift_spec, False], None, 2, ), # 1
)
createBackup_args.thrift_struct_annotations = {
}
createBackup_args.thrift_field_annotations = {
}
def createBackup_args__init__(self, req=None,):
self.req = req
createBackup_args.__init__ = createBackup_args__init__
def createBackup_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createBackup_args.__getstate__ = lambda self: self.__dict__.copy()
createBackup_args.__setstate__ = createBackup_args__setstate__
class createBackup_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = CreateBackupResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createBackup_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createBackup_result)
createBackup_result.thrift_spec = (
(0, TType.STRUCT, 'success', [CreateBackupResp, CreateBackupResp.thrift_spec, False], None, 2, ), # 0
)
createBackup_result.thrift_struct_annotations = {
}
createBackup_result.thrift_field_annotations = {
}
def createBackup_result__init__(self, success=None,):
self.success = success
createBackup_result.__init__ = createBackup_result__init__
def createBackup_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createBackup_result.__getstate__ = lambda self: self.__dict__.copy()
createBackup_result.__setstate__ = createBackup_result__setstate__
class restoreMeta_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RestoreMetaReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('restoreMeta_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(restoreMeta_args)
restoreMeta_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RestoreMetaReq, RestoreMetaReq.thrift_spec, False], None, 2, ), # 1
)
restoreMeta_args.thrift_struct_annotations = {
}
restoreMeta_args.thrift_field_annotations = {
}
def restoreMeta_args__init__(self, req=None,):
self.req = req
restoreMeta_args.__init__ = restoreMeta_args__init__
def restoreMeta_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
restoreMeta_args.__getstate__ = lambda self: self.__dict__.copy()
restoreMeta_args.__setstate__ = restoreMeta_args__setstate__
class restoreMeta_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('restoreMeta_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(restoreMeta_result)
restoreMeta_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
restoreMeta_result.thrift_struct_annotations = {
}
restoreMeta_result.thrift_field_annotations = {
}
def restoreMeta_result__init__(self, success=None,):
self.success = success
restoreMeta_result.__init__ = restoreMeta_result__init__
def restoreMeta_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
restoreMeta_result.__getstate__ = lambda self: self.__dict__.copy()
restoreMeta_result.__setstate__ = restoreMeta_result__setstate__
class addListener_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = AddListenerReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addListener_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addListener_args)
addListener_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [AddListenerReq, AddListenerReq.thrift_spec, False], None, 2, ), # 1
)
addListener_args.thrift_struct_annotations = {
}
addListener_args.thrift_field_annotations = {
}
def addListener_args__init__(self, req=None,):
self.req = req
addListener_args.__init__ = addListener_args__init__
def addListener_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
addListener_args.__getstate__ = lambda self: self.__dict__.copy()
addListener_args.__setstate__ = addListener_args__setstate__
class addListener_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('addListener_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(addListener_result)
addListener_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
addListener_result.thrift_struct_annotations = {
}
addListener_result.thrift_field_annotations = {
}
def addListener_result__init__(self, success=None,):
self.success = success
addListener_result.__init__ = addListener_result__init__
def addListener_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
addListener_result.__getstate__ = lambda self: self.__dict__.copy()
addListener_result.__setstate__ = addListener_result__setstate__
class removeListener_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RemoveListenerReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('removeListener_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(removeListener_args)
removeListener_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RemoveListenerReq, RemoveListenerReq.thrift_spec, False], None, 2, ), # 1
)
removeListener_args.thrift_struct_annotations = {
}
removeListener_args.thrift_field_annotations = {
}
def removeListener_args__init__(self, req=None,):
self.req = req
removeListener_args.__init__ = removeListener_args__init__
def removeListener_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
removeListener_args.__getstate__ = lambda self: self.__dict__.copy()
removeListener_args.__setstate__ = removeListener_args__setstate__
class removeListener_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('removeListener_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(removeListener_result)
removeListener_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
removeListener_result.thrift_struct_annotations = {
}
removeListener_result.thrift_field_annotations = {
}
def removeListener_result__init__(self, success=None,):
self.success = success
removeListener_result.__init__ = removeListener_result__init__
def removeListener_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
removeListener_result.__getstate__ = lambda self: self.__dict__.copy()
removeListener_result.__setstate__ = removeListener_result__setstate__
class listListener_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListListenerReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listListener_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listListener_args)
listListener_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListListenerReq, ListListenerReq.thrift_spec, False], None, 2, ), # 1
)
listListener_args.thrift_struct_annotations = {
}
listListener_args.thrift_field_annotations = {
}
def listListener_args__init__(self, req=None,):
self.req = req
listListener_args.__init__ = listListener_args__init__
def listListener_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listListener_args.__getstate__ = lambda self: self.__dict__.copy()
listListener_args.__setstate__ = listListener_args__setstate__
class listListener_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListListenerResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listListener_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listListener_result)
listListener_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListListenerResp, ListListenerResp.thrift_spec, False], None, 2, ), # 0
)
listListener_result.thrift_struct_annotations = {
}
listListener_result.thrift_field_annotations = {
}
def listListener_result__init__(self, success=None,):
self.success = success
listListener_result.__init__ = listListener_result__init__
def listListener_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listListener_result.__getstate__ = lambda self: self.__dict__.copy()
listListener_result.__setstate__ = listListener_result__setstate__
class getStatis_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetStatisReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getStatis_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getStatis_args)
getStatis_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetStatisReq, GetStatisReq.thrift_spec, False], None, 2, ), # 1
)
getStatis_args.thrift_struct_annotations = {
}
getStatis_args.thrift_field_annotations = {
}
def getStatis_args__init__(self, req=None,):
self.req = req
getStatis_args.__init__ = getStatis_args__init__
def getStatis_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getStatis_args.__getstate__ = lambda self: self.__dict__.copy()
getStatis_args.__setstate__ = getStatis_args__setstate__
class getStatis_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetStatisResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getStatis_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getStatis_result)
getStatis_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetStatisResp, GetStatisResp.thrift_spec, False], None, 2, ), # 0
)
getStatis_result.thrift_struct_annotations = {
}
getStatis_result.thrift_field_annotations = {
}
def getStatis_result__init__(self, success=None,):
self.success = success
getStatis_result.__init__ = getStatis_result__init__
def getStatis_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getStatis_result.__getstate__ = lambda self: self.__dict__.copy()
getStatis_result.__setstate__ = getStatis_result__setstate__
class signInFTService_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = SignInFTServiceReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('signInFTService_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(signInFTService_args)
signInFTService_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [SignInFTServiceReq, SignInFTServiceReq.thrift_spec, False], None, 2, ), # 1
)
signInFTService_args.thrift_struct_annotations = {
}
signInFTService_args.thrift_field_annotations = {
}
def signInFTService_args__init__(self, req=None,):
self.req = req
signInFTService_args.__init__ = signInFTService_args__init__
def signInFTService_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
signInFTService_args.__getstate__ = lambda self: self.__dict__.copy()
signInFTService_args.__setstate__ = signInFTService_args__setstate__
class signInFTService_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('signInFTService_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(signInFTService_result)
signInFTService_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
signInFTService_result.thrift_struct_annotations = {
}
signInFTService_result.thrift_field_annotations = {
}
def signInFTService_result__init__(self, success=None,):
self.success = success
signInFTService_result.__init__ = signInFTService_result__init__
def signInFTService_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
signInFTService_result.__getstate__ = lambda self: self.__dict__.copy()
signInFTService_result.__setstate__ = signInFTService_result__setstate__
class signOutFTService_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = SignOutFTServiceReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('signOutFTService_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(signOutFTService_args)
signOutFTService_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [SignOutFTServiceReq, SignOutFTServiceReq.thrift_spec, False], None, 2, ), # 1
)
signOutFTService_args.thrift_struct_annotations = {
}
signOutFTService_args.thrift_field_annotations = {
}
def signOutFTService_args__init__(self, req=None,):
self.req = req
signOutFTService_args.__init__ = signOutFTService_args__init__
def signOutFTService_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
signOutFTService_args.__getstate__ = lambda self: self.__dict__.copy()
signOutFTService_args.__setstate__ = signOutFTService_args__setstate__
class signOutFTService_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('signOutFTService_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(signOutFTService_result)
signOutFTService_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
signOutFTService_result.thrift_struct_annotations = {
}
signOutFTService_result.thrift_field_annotations = {
}
def signOutFTService_result__init__(self, success=None,):
self.success = success
signOutFTService_result.__init__ = signOutFTService_result__init__
def signOutFTService_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
signOutFTService_result.__getstate__ = lambda self: self.__dict__.copy()
signOutFTService_result.__setstate__ = signOutFTService_result__setstate__
class listFTClients_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListFTClientsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listFTClients_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listFTClients_args)
listFTClients_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListFTClientsReq, ListFTClientsReq.thrift_spec, False], None, 2, ), # 1
)
listFTClients_args.thrift_struct_annotations = {
}
listFTClients_args.thrift_field_annotations = {
}
def listFTClients_args__init__(self, req=None,):
self.req = req
listFTClients_args.__init__ = listFTClients_args__init__
def listFTClients_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listFTClients_args.__getstate__ = lambda self: self.__dict__.copy()
listFTClients_args.__setstate__ = listFTClients_args__setstate__
class listFTClients_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListFTClientsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listFTClients_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listFTClients_result)
listFTClients_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListFTClientsResp, ListFTClientsResp.thrift_spec, False], None, 2, ), # 0
)
listFTClients_result.thrift_struct_annotations = {
}
listFTClients_result.thrift_field_annotations = {
}
def listFTClients_result__init__(self, success=None,):
self.success = success
listFTClients_result.__init__ = listFTClients_result__init__
def listFTClients_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listFTClients_result.__getstate__ = lambda self: self.__dict__.copy()
listFTClients_result.__setstate__ = listFTClients_result__setstate__
class createFTIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateFTIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createFTIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createFTIndex_args)
createFTIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateFTIndexReq, CreateFTIndexReq.thrift_spec, False], None, 2, ), # 1
)
createFTIndex_args.thrift_struct_annotations = {
}
createFTIndex_args.thrift_field_annotations = {
}
def createFTIndex_args__init__(self, req=None,):
self.req = req
createFTIndex_args.__init__ = createFTIndex_args__init__
def createFTIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createFTIndex_args.__getstate__ = lambda self: self.__dict__.copy()
createFTIndex_args.__setstate__ = createFTIndex_args__setstate__
class createFTIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createFTIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createFTIndex_result)
createFTIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
createFTIndex_result.thrift_struct_annotations = {
}
createFTIndex_result.thrift_field_annotations = {
}
def createFTIndex_result__init__(self, success=None,):
self.success = success
createFTIndex_result.__init__ = createFTIndex_result__init__
def createFTIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createFTIndex_result.__getstate__ = lambda self: self.__dict__.copy()
createFTIndex_result.__setstate__ = createFTIndex_result__setstate__
class dropFTIndex_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = DropFTIndexReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropFTIndex_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropFTIndex_args)
dropFTIndex_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [DropFTIndexReq, DropFTIndexReq.thrift_spec, False], None, 2, ), # 1
)
dropFTIndex_args.thrift_struct_annotations = {
}
dropFTIndex_args.thrift_field_annotations = {
}
def dropFTIndex_args__init__(self, req=None,):
self.req = req
dropFTIndex_args.__init__ = dropFTIndex_args__init__
def dropFTIndex_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
dropFTIndex_args.__getstate__ = lambda self: self.__dict__.copy()
dropFTIndex_args.__setstate__ = dropFTIndex_args__setstate__
class dropFTIndex_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('dropFTIndex_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(dropFTIndex_result)
dropFTIndex_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
dropFTIndex_result.thrift_struct_annotations = {
}
dropFTIndex_result.thrift_field_annotations = {
}
def dropFTIndex_result__init__(self, success=None,):
self.success = success
dropFTIndex_result.__init__ = dropFTIndex_result__init__
def dropFTIndex_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
dropFTIndex_result.__getstate__ = lambda self: self.__dict__.copy()
dropFTIndex_result.__setstate__ = dropFTIndex_result__setstate__
class listFTIndexes_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListFTIndexesReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listFTIndexes_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listFTIndexes_args)
listFTIndexes_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListFTIndexesReq, ListFTIndexesReq.thrift_spec, False], None, 2, ), # 1
)
listFTIndexes_args.thrift_struct_annotations = {
}
listFTIndexes_args.thrift_field_annotations = {
}
def listFTIndexes_args__init__(self, req=None,):
self.req = req
listFTIndexes_args.__init__ = listFTIndexes_args__init__
def listFTIndexes_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listFTIndexes_args.__getstate__ = lambda self: self.__dict__.copy()
listFTIndexes_args.__setstate__ = listFTIndexes_args__setstate__
class listFTIndexes_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListFTIndexesResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listFTIndexes_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listFTIndexes_result)
listFTIndexes_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListFTIndexesResp, ListFTIndexesResp.thrift_spec, False], None, 2, ), # 0
)
listFTIndexes_result.thrift_struct_annotations = {
}
listFTIndexes_result.thrift_field_annotations = {
}
def listFTIndexes_result__init__(self, success=None,):
self.success = success
listFTIndexes_result.__init__ = listFTIndexes_result__init__
def listFTIndexes_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listFTIndexes_result.__getstate__ = lambda self: self.__dict__.copy()
listFTIndexes_result.__setstate__ = listFTIndexes_result__setstate__
class createSession_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = CreateSessionReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createSession_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createSession_args)
createSession_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [CreateSessionReq, CreateSessionReq.thrift_spec, False], None, 2, ), # 1
)
createSession_args.thrift_struct_annotations = {
}
createSession_args.thrift_field_annotations = {
}
def createSession_args__init__(self, req=None,):
self.req = req
createSession_args.__init__ = createSession_args__init__
def createSession_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
createSession_args.__getstate__ = lambda self: self.__dict__.copy()
createSession_args.__setstate__ = createSession_args__setstate__
class createSession_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = CreateSessionResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('createSession_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(createSession_result)
createSession_result.thrift_spec = (
(0, TType.STRUCT, 'success', [CreateSessionResp, CreateSessionResp.thrift_spec, False], None, 2, ), # 0
)
createSession_result.thrift_struct_annotations = {
}
createSession_result.thrift_field_annotations = {
}
def createSession_result__init__(self, success=None,):
self.success = success
createSession_result.__init__ = createSession_result__init__
def createSession_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
createSession_result.__getstate__ = lambda self: self.__dict__.copy()
createSession_result.__setstate__ = createSession_result__setstate__
class updateSessions_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def | ():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = UpdateSessionsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('updateSessions_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(updateSessions_args)
updateSessions_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [UpdateSessionsReq, UpdateSessionsReq.thrift_spec, False], None, 2, ), # 1
)
updateSessions_args.thrift_struct_annotations = {
}
updateSessions_args.thrift_field_annotations = {
}
def updateSessions_args__init__(self, req=None,):
self.req = req
updateSessions_args.__init__ = updateSessions_args__init__
def updateSessions_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
updateSessions_args.__getstate__ = lambda self: self.__dict__.copy()
updateSessions_args.__setstate__ = updateSessions_args__setstate__
class updateSessions_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = UpdateSessionsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('updateSessions_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(updateSessions_result)
updateSessions_result.thrift_spec = (
(0, TType.STRUCT, 'success', [UpdateSessionsResp, UpdateSessionsResp.thrift_spec, False], None, 2, ), # 0
)
updateSessions_result.thrift_struct_annotations = {
}
updateSessions_result.thrift_field_annotations = {
}
def updateSessions_result__init__(self, success=None,):
self.success = success
updateSessions_result.__init__ = updateSessions_result__init__
def updateSessions_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
updateSessions_result.__getstate__ = lambda self: self.__dict__.copy()
updateSessions_result.__setstate__ = updateSessions_result__setstate__
class listSessions_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListSessionsReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listSessions_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listSessions_args)
listSessions_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListSessionsReq, ListSessionsReq.thrift_spec, False], None, 2, ), # 1
)
listSessions_args.thrift_struct_annotations = {
}
listSessions_args.thrift_field_annotations = {
}
def listSessions_args__init__(self, req=None,):
self.req = req
listSessions_args.__init__ = listSessions_args__init__
def listSessions_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listSessions_args.__getstate__ = lambda self: self.__dict__.copy()
listSessions_args.__setstate__ = listSessions_args__setstate__
class listSessions_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListSessionsResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listSessions_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listSessions_result)
listSessions_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListSessionsResp, ListSessionsResp.thrift_spec, False], None, 2, ), # 0
)
listSessions_result.thrift_struct_annotations = {
}
listSessions_result.thrift_field_annotations = {
}
def listSessions_result__init__(self, success=None,):
self.success = success
listSessions_result.__init__ = listSessions_result__init__
def listSessions_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listSessions_result.__getstate__ = lambda self: self.__dict__.copy()
listSessions_result.__setstate__ = listSessions_result__setstate__
class getSession_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetSessionReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getSession_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getSession_args)
getSession_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetSessionReq, GetSessionReq.thrift_spec, False], None, 2, ), # 1
)
getSession_args.thrift_struct_annotations = {
}
getSession_args.thrift_field_annotations = {
}
def getSession_args__init__(self, req=None,):
self.req = req
getSession_args.__init__ = getSession_args__init__
def getSession_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getSession_args.__getstate__ = lambda self: self.__dict__.copy()
getSession_args.__setstate__ = getSession_args__setstate__
class getSession_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetSessionResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getSession_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getSession_result)
getSession_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetSessionResp, GetSessionResp.thrift_spec, False], None, 2, ), # 0
)
getSession_result.thrift_struct_annotations = {
}
getSession_result.thrift_field_annotations = {
}
def getSession_result__init__(self, success=None,):
self.success = success
getSession_result.__init__ = getSession_result__init__
def getSession_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getSession_result.__getstate__ = lambda self: self.__dict__.copy()
getSession_result.__setstate__ = getSession_result__setstate__
class removeSession_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = RemoveSessionReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('removeSession_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(removeSession_args)
removeSession_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [RemoveSessionReq, RemoveSessionReq.thrift_spec, False], None, 2, ), # 1
)
removeSession_args.thrift_struct_annotations = {
}
removeSession_args.thrift_field_annotations = {
}
def removeSession_args__init__(self, req=None,):
self.req = req
removeSession_args.__init__ = removeSession_args__init__
def removeSession_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
removeSession_args.__getstate__ = lambda self: self.__dict__.copy()
removeSession_args.__setstate__ = removeSession_args__setstate__
class removeSession_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('removeSession_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(removeSession_result)
removeSession_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
removeSession_result.thrift_struct_annotations = {
}
removeSession_result.thrift_field_annotations = {
}
def removeSession_result__init__(self, success=None,):
self.success = success
removeSession_result.__init__ = removeSession_result__init__
def removeSession_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
removeSession_result.__getstate__ = lambda self: self.__dict__.copy()
removeSession_result.__setstate__ = removeSession_result__setstate__
class killQuery_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = KillQueryReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('killQuery_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(killQuery_args)
killQuery_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [KillQueryReq, KillQueryReq.thrift_spec, False], None, 2, ), # 1
)
killQuery_args.thrift_struct_annotations = {
}
killQuery_args.thrift_field_annotations = {
}
def killQuery_args__init__(self, req=None,):
self.req = req
killQuery_args.__init__ = killQuery_args__init__
def killQuery_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
killQuery_args.__getstate__ = lambda self: self.__dict__.copy()
killQuery_args.__setstate__ = killQuery_args__setstate__
class killQuery_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('killQuery_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(killQuery_result)
killQuery_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
killQuery_result.thrift_struct_annotations = {
}
killQuery_result.thrift_field_annotations = {
}
def killQuery_result__init__(self, success=None,):
self.success = success
killQuery_result.__init__ = killQuery_result__init__
def killQuery_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
killQuery_result.__getstate__ = lambda self: self.__dict__.copy()
killQuery_result.__setstate__ = killQuery_result__setstate__
class reportTaskFinish_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ReportTaskReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('reportTaskFinish_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(reportTaskFinish_args)
reportTaskFinish_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ReportTaskReq, ReportTaskReq.thrift_spec, False], None, 2, ), # 1
)
reportTaskFinish_args.thrift_struct_annotations = {
}
reportTaskFinish_args.thrift_field_annotations = {
}
def reportTaskFinish_args__init__(self, req=None,):
self.req = req
reportTaskFinish_args.__init__ = reportTaskFinish_args__init__
def reportTaskFinish_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
reportTaskFinish_args.__getstate__ = lambda self: self.__dict__.copy()
reportTaskFinish_args.__setstate__ = reportTaskFinish_args__setstate__
class reportTaskFinish_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ExecResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('reportTaskFinish_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(reportTaskFinish_result)
reportTaskFinish_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ExecResp, ExecResp.thrift_spec, False], None, 2, ), # 0
)
reportTaskFinish_result.thrift_struct_annotations = {
}
reportTaskFinish_result.thrift_field_annotations = {
}
def reportTaskFinish_result__init__(self, success=None,):
self.success = success
reportTaskFinish_result.__init__ = reportTaskFinish_result__init__
def reportTaskFinish_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
reportTaskFinish_result.__getstate__ = lambda self: self.__dict__.copy()
reportTaskFinish_result.__setstate__ = reportTaskFinish_result__setstate__
class listCluster_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = ListClusterInfoReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listCluster_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listCluster_args)
listCluster_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [ListClusterInfoReq, ListClusterInfoReq.thrift_spec, False], None, 2, ), # 1
)
listCluster_args.thrift_struct_annotations = {
}
listCluster_args.thrift_field_annotations = {
}
def listCluster_args__init__(self, req=None,):
self.req = req
listCluster_args.__init__ = listCluster_args__init__
def listCluster_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
listCluster_args.__getstate__ = lambda self: self.__dict__.copy()
listCluster_args.__setstate__ = listCluster_args__setstate__
class listCluster_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = ListClusterInfoResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('listCluster_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(listCluster_result)
listCluster_result.thrift_spec = (
(0, TType.STRUCT, 'success', [ListClusterInfoResp, ListClusterInfoResp.thrift_spec, False], None, 2, ), # 0
)
listCluster_result.thrift_struct_annotations = {
}
listCluster_result.thrift_field_annotations = {
}
def listCluster_result__init__(self, success=None,):
self.success = success
listCluster_result.__init__ = listCluster_result__init__
def listCluster_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
listCluster_result.__getstate__ = lambda self: self.__dict__.copy()
listCluster_result.__setstate__ = listCluster_result__setstate__
class getMetaDirInfo_args:
"""
Attributes:
- req
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.req = GetMetaDirInfoReq()
self.req.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getMetaDirInfo_args')
if self.req != None:
oprot.writeFieldBegin('req', TType.STRUCT, 1)
self.req.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.req is not None:
value = pprint.pformat(self.req, indent=0)
value = padding.join(value.splitlines(True))
L.append(' req=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getMetaDirInfo_args)
getMetaDirInfo_args.thrift_spec = (
None, # 0
(1, TType.STRUCT, 'req', [GetMetaDirInfoReq, GetMetaDirInfoReq.thrift_spec, False], None, 2, ), # 1
)
getMetaDirInfo_args.thrift_struct_annotations = {
}
getMetaDirInfo_args.thrift_field_annotations = {
}
def getMetaDirInfo_args__init__(self, req=None,):
self.req = req
getMetaDirInfo_args.__init__ = getMetaDirInfo_args__init__
def getMetaDirInfo_args__setstate__(self, state):
state.setdefault('req', None)
self.__dict__ = state
getMetaDirInfo_args.__getstate__ = lambda self: self.__dict__.copy()
getMetaDirInfo_args.__setstate__ = getMetaDirInfo_args__setstate__
class getMetaDirInfo_result:
"""
Attributes:
- success
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = GetMetaDirInfoResp()
self.success.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('getMetaDirInfo_result')
if self.success != None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
if self.success is not None:
value = pprint.pformat(self.success, indent=0)
value = padding.join(value.splitlines(True))
L.append(' success=%s' % (value))
return "%s(%s)" % (self.__class__.__name__, "\n" + ",\n".join(L) if L else '')
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
all_structs.append(getMetaDirInfo_result)
getMetaDirInfo_result.thrift_spec = (
(0, TType.STRUCT, 'success', [GetMetaDirInfoResp, GetMetaDirInfoResp.thrift_spec, False], None, 2, ), # 0
)
getMetaDirInfo_result.thrift_struct_annotations = {
}
getMetaDirInfo_result.thrift_field_annotations = {
}
def getMetaDirInfo_result__init__(self, success=None,):
self.success = success
getMetaDirInfo_result.__init__ = getMetaDirInfo_result__init__
def getMetaDirInfo_result__setstate__(self, state):
state.setdefault('success', None)
self.__dict__ = state
getMetaDirInfo_result.__getstate__ = lambda self: self.__dict__.copy()
getMetaDirInfo_result.__setstate__ = getMetaDirInfo_result__setstate__
class Client(Iface):
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self._iprot.trans.close()
if self._iprot is not self._oprot:
self._oprot.trans.close()
def __init__(self, iprot, oprot=None):
self._iprot = self._oprot = iprot
if oprot != None:
self._oprot = oprot
self._seqid = 0
def createSpace(self, req=None):
"""
Parameters:
- req
"""
self.send_createSpace(req)
return self.recv_createSpace()
def send_createSpace(self, req=None):
self._oprot.writeMessageBegin('createSpace', TMessageType.CALL, self._seqid)
args = createSpace_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createSpace(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createSpace_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createSpace failed: unknown result");
def dropSpace(self, req=None):
"""
Parameters:
- req
"""
self.send_dropSpace(req)
return self.recv_dropSpace()
def send_dropSpace(self, req=None):
self._oprot.writeMessageBegin('dropSpace', TMessageType.CALL, self._seqid)
args = dropSpace_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropSpace(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropSpace_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropSpace failed: unknown result");
def getSpace(self, req=None):
"""
Parameters:
- req
"""
self.send_getSpace(req)
return self.recv_getSpace()
def send_getSpace(self, req=None):
self._oprot.writeMessageBegin('getSpace', TMessageType.CALL, self._seqid)
args = getSpace_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getSpace(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getSpace_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getSpace failed: unknown result");
def listSpaces(self, req=None):
"""
Parameters:
- req
"""
self.send_listSpaces(req)
return self.recv_listSpaces()
def send_listSpaces(self, req=None):
self._oprot.writeMessageBegin('listSpaces', TMessageType.CALL, self._seqid)
args = listSpaces_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listSpaces(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listSpaces_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listSpaces failed: unknown result");
def createTag(self, req=None):
"""
Parameters:
- req
"""
self.send_createTag(req)
return self.recv_createTag()
def send_createTag(self, req=None):
self._oprot.writeMessageBegin('createTag', TMessageType.CALL, self._seqid)
args = createTag_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createTag(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createTag_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createTag failed: unknown result");
def alterTag(self, req=None):
"""
Parameters:
- req
"""
self.send_alterTag(req)
return self.recv_alterTag()
def send_alterTag(self, req=None):
self._oprot.writeMessageBegin('alterTag', TMessageType.CALL, self._seqid)
args = alterTag_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_alterTag(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = alterTag_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "alterTag failed: unknown result");
def dropTag(self, req=None):
"""
Parameters:
- req
"""
self.send_dropTag(req)
return self.recv_dropTag()
def send_dropTag(self, req=None):
self._oprot.writeMessageBegin('dropTag', TMessageType.CALL, self._seqid)
args = dropTag_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropTag(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropTag_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropTag failed: unknown result");
def getTag(self, req=None):
"""
Parameters:
- req
"""
self.send_getTag(req)
return self.recv_getTag()
def send_getTag(self, req=None):
self._oprot.writeMessageBegin('getTag', TMessageType.CALL, self._seqid)
args = getTag_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getTag(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getTag_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getTag failed: unknown result");
def listTags(self, req=None):
"""
Parameters:
- req
"""
self.send_listTags(req)
return self.recv_listTags()
def send_listTags(self, req=None):
self._oprot.writeMessageBegin('listTags', TMessageType.CALL, self._seqid)
args = listTags_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listTags(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listTags_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listTags failed: unknown result");
def createEdge(self, req=None):
"""
Parameters:
- req
"""
self.send_createEdge(req)
return self.recv_createEdge()
def send_createEdge(self, req=None):
self._oprot.writeMessageBegin('createEdge', TMessageType.CALL, self._seqid)
args = createEdge_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createEdge(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createEdge_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createEdge failed: unknown result");
def alterEdge(self, req=None):
"""
Parameters:
- req
"""
self.send_alterEdge(req)
return self.recv_alterEdge()
def send_alterEdge(self, req=None):
self._oprot.writeMessageBegin('alterEdge', TMessageType.CALL, self._seqid)
args = alterEdge_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_alterEdge(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = alterEdge_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "alterEdge failed: unknown result");
def dropEdge(self, req=None):
"""
Parameters:
- req
"""
self.send_dropEdge(req)
return self.recv_dropEdge()
def send_dropEdge(self, req=None):
self._oprot.writeMessageBegin('dropEdge', TMessageType.CALL, self._seqid)
args = dropEdge_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropEdge(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropEdge_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropEdge failed: unknown result");
def getEdge(self, req=None):
"""
Parameters:
- req
"""
self.send_getEdge(req)
return self.recv_getEdge()
def send_getEdge(self, req=None):
self._oprot.writeMessageBegin('getEdge', TMessageType.CALL, self._seqid)
args = getEdge_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getEdge(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getEdge_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getEdge failed: unknown result");
def listEdges(self, req=None):
"""
Parameters:
- req
"""
self.send_listEdges(req)
return self.recv_listEdges()
def send_listEdges(self, req=None):
self._oprot.writeMessageBegin('listEdges', TMessageType.CALL, self._seqid)
args = listEdges_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listEdges(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listEdges_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listEdges failed: unknown result");
def listHosts(self, req=None):
"""
Parameters:
- req
"""
self.send_listHosts(req)
return self.recv_listHosts()
def send_listHosts(self, req=None):
self._oprot.writeMessageBegin('listHosts', TMessageType.CALL, self._seqid)
args = listHosts_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listHosts(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listHosts_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listHosts failed: unknown result");
def getPartsAlloc(self, req=None):
"""
Parameters:
- req
"""
self.send_getPartsAlloc(req)
return self.recv_getPartsAlloc()
def send_getPartsAlloc(self, req=None):
self._oprot.writeMessageBegin('getPartsAlloc', TMessageType.CALL, self._seqid)
args = getPartsAlloc_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getPartsAlloc(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getPartsAlloc_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getPartsAlloc failed: unknown result");
def listParts(self, req=None):
"""
Parameters:
- req
"""
self.send_listParts(req)
return self.recv_listParts()
def send_listParts(self, req=None):
self._oprot.writeMessageBegin('listParts', TMessageType.CALL, self._seqid)
args = listParts_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listParts(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listParts_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listParts failed: unknown result");
def multiPut(self, req=None):
"""
Parameters:
- req
"""
self.send_multiPut(req)
return self.recv_multiPut()
def send_multiPut(self, req=None):
self._oprot.writeMessageBegin('multiPut', TMessageType.CALL, self._seqid)
args = multiPut_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_multiPut(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = multiPut_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "multiPut failed: unknown result");
def get(self, req=None):
"""
Parameters:
- req
"""
self.send_get(req)
return self.recv_get()
def send_get(self, req=None):
self._oprot.writeMessageBegin('get', TMessageType.CALL, self._seqid)
args = get_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_get(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = get_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "get failed: unknown result");
def multiGet(self, req=None):
"""
Parameters:
- req
"""
self.send_multiGet(req)
return self.recv_multiGet()
def send_multiGet(self, req=None):
self._oprot.writeMessageBegin('multiGet', TMessageType.CALL, self._seqid)
args = multiGet_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_multiGet(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = multiGet_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "multiGet failed: unknown result");
def remove(self, req=None):
"""
Parameters:
- req
"""
self.send_remove(req)
return self.recv_remove()
def send_remove(self, req=None):
self._oprot.writeMessageBegin('remove', TMessageType.CALL, self._seqid)
args = remove_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_remove(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = remove_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "remove failed: unknown result");
def removeRange(self, req=None):
"""
Parameters:
- req
"""
self.send_removeRange(req)
return self.recv_removeRange()
def send_removeRange(self, req=None):
self._oprot.writeMessageBegin('removeRange', TMessageType.CALL, self._seqid)
args = removeRange_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_removeRange(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = removeRange_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "removeRange failed: unknown result");
def scan(self, req=None):
"""
Parameters:
- req
"""
self.send_scan(req)
return self.recv_scan()
def send_scan(self, req=None):
self._oprot.writeMessageBegin('scan', TMessageType.CALL, self._seqid)
args = scan_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_scan(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = scan_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "scan failed: unknown result");
def createTagIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_createTagIndex(req)
return self.recv_createTagIndex()
def send_createTagIndex(self, req=None):
self._oprot.writeMessageBegin('createTagIndex', TMessageType.CALL, self._seqid)
args = createTagIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createTagIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createTagIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createTagIndex failed: unknown result");
def dropTagIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_dropTagIndex(req)
return self.recv_dropTagIndex()
def send_dropTagIndex(self, req=None):
self._oprot.writeMessageBegin('dropTagIndex', TMessageType.CALL, self._seqid)
args = dropTagIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropTagIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropTagIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropTagIndex failed: unknown result");
def getTagIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_getTagIndex(req)
return self.recv_getTagIndex()
def send_getTagIndex(self, req=None):
self._oprot.writeMessageBegin('getTagIndex', TMessageType.CALL, self._seqid)
args = getTagIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getTagIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getTagIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getTagIndex failed: unknown result");
def listTagIndexes(self, req=None):
"""
Parameters:
- req
"""
self.send_listTagIndexes(req)
return self.recv_listTagIndexes()
def send_listTagIndexes(self, req=None):
self._oprot.writeMessageBegin('listTagIndexes', TMessageType.CALL, self._seqid)
args = listTagIndexes_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listTagIndexes(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listTagIndexes_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listTagIndexes failed: unknown result");
def rebuildTagIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_rebuildTagIndex(req)
return self.recv_rebuildTagIndex()
def send_rebuildTagIndex(self, req=None):
self._oprot.writeMessageBegin('rebuildTagIndex', TMessageType.CALL, self._seqid)
args = rebuildTagIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_rebuildTagIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = rebuildTagIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "rebuildTagIndex failed: unknown result");
def listTagIndexStatus(self, req=None):
"""
Parameters:
- req
"""
self.send_listTagIndexStatus(req)
return self.recv_listTagIndexStatus()
def send_listTagIndexStatus(self, req=None):
self._oprot.writeMessageBegin('listTagIndexStatus', TMessageType.CALL, self._seqid)
args = listTagIndexStatus_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listTagIndexStatus(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listTagIndexStatus_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listTagIndexStatus failed: unknown result");
def createEdgeIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_createEdgeIndex(req)
return self.recv_createEdgeIndex()
def send_createEdgeIndex(self, req=None):
self._oprot.writeMessageBegin('createEdgeIndex', TMessageType.CALL, self._seqid)
args = createEdgeIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createEdgeIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createEdgeIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createEdgeIndex failed: unknown result");
def dropEdgeIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_dropEdgeIndex(req)
return self.recv_dropEdgeIndex()
def send_dropEdgeIndex(self, req=None):
self._oprot.writeMessageBegin('dropEdgeIndex', TMessageType.CALL, self._seqid)
args = dropEdgeIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropEdgeIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropEdgeIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropEdgeIndex failed: unknown result");
def getEdgeIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_getEdgeIndex(req)
return self.recv_getEdgeIndex()
def send_getEdgeIndex(self, req=None):
self._oprot.writeMessageBegin('getEdgeIndex', TMessageType.CALL, self._seqid)
args = getEdgeIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getEdgeIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getEdgeIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getEdgeIndex failed: unknown result");
def listEdgeIndexes(self, req=None):
"""
Parameters:
- req
"""
self.send_listEdgeIndexes(req)
return self.recv_listEdgeIndexes()
def send_listEdgeIndexes(self, req=None):
self._oprot.writeMessageBegin('listEdgeIndexes', TMessageType.CALL, self._seqid)
args = listEdgeIndexes_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listEdgeIndexes(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listEdgeIndexes_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listEdgeIndexes failed: unknown result");
def rebuildEdgeIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_rebuildEdgeIndex(req)
return self.recv_rebuildEdgeIndex()
def send_rebuildEdgeIndex(self, req=None):
self._oprot.writeMessageBegin('rebuildEdgeIndex', TMessageType.CALL, self._seqid)
args = rebuildEdgeIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_rebuildEdgeIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = rebuildEdgeIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "rebuildEdgeIndex failed: unknown result");
def listEdgeIndexStatus(self, req=None):
"""
Parameters:
- req
"""
self.send_listEdgeIndexStatus(req)
return self.recv_listEdgeIndexStatus()
def send_listEdgeIndexStatus(self, req=None):
self._oprot.writeMessageBegin('listEdgeIndexStatus', TMessageType.CALL, self._seqid)
args = listEdgeIndexStatus_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listEdgeIndexStatus(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listEdgeIndexStatus_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listEdgeIndexStatus failed: unknown result");
def createUser(self, req=None):
"""
Parameters:
- req
"""
self.send_createUser(req)
return self.recv_createUser()
def send_createUser(self, req=None):
self._oprot.writeMessageBegin('createUser', TMessageType.CALL, self._seqid)
args = createUser_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createUser(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createUser_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createUser failed: unknown result");
def dropUser(self, req=None):
"""
Parameters:
- req
"""
self.send_dropUser(req)
return self.recv_dropUser()
def send_dropUser(self, req=None):
self._oprot.writeMessageBegin('dropUser', TMessageType.CALL, self._seqid)
args = dropUser_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropUser(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropUser_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropUser failed: unknown result");
def alterUser(self, req=None):
"""
Parameters:
- req
"""
self.send_alterUser(req)
return self.recv_alterUser()
def send_alterUser(self, req=None):
self._oprot.writeMessageBegin('alterUser', TMessageType.CALL, self._seqid)
args = alterUser_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_alterUser(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = alterUser_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "alterUser failed: unknown result");
def grantRole(self, req=None):
"""
Parameters:
- req
"""
self.send_grantRole(req)
return self.recv_grantRole()
def send_grantRole(self, req=None):
self._oprot.writeMessageBegin('grantRole', TMessageType.CALL, self._seqid)
args = grantRole_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_grantRole(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = grantRole_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "grantRole failed: unknown result");
def revokeRole(self, req=None):
"""
Parameters:
- req
"""
self.send_revokeRole(req)
return self.recv_revokeRole()
def send_revokeRole(self, req=None):
self._oprot.writeMessageBegin('revokeRole', TMessageType.CALL, self._seqid)
args = revokeRole_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_revokeRole(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = revokeRole_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "revokeRole failed: unknown result");
def listUsers(self, req=None):
"""
Parameters:
- req
"""
self.send_listUsers(req)
return self.recv_listUsers()
def send_listUsers(self, req=None):
self._oprot.writeMessageBegin('listUsers', TMessageType.CALL, self._seqid)
args = listUsers_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listUsers(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listUsers_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listUsers failed: unknown result");
def listRoles(self, req=None):
"""
Parameters:
- req
"""
self.send_listRoles(req)
return self.recv_listRoles()
def send_listRoles(self, req=None):
self._oprot.writeMessageBegin('listRoles', TMessageType.CALL, self._seqid)
args = listRoles_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listRoles(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listRoles_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listRoles failed: unknown result");
def getUserRoles(self, req=None):
"""
Parameters:
- req
"""
self.send_getUserRoles(req)
return self.recv_getUserRoles()
def send_getUserRoles(self, req=None):
self._oprot.writeMessageBegin('getUserRoles', TMessageType.CALL, self._seqid)
args = getUserRoles_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getUserRoles(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getUserRoles_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getUserRoles failed: unknown result");
def changePassword(self, req=None):
"""
Parameters:
- req
"""
self.send_changePassword(req)
return self.recv_changePassword()
def send_changePassword(self, req=None):
self._oprot.writeMessageBegin('changePassword', TMessageType.CALL, self._seqid)
args = changePassword_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_changePassword(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = changePassword_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "changePassword failed: unknown result");
def heartBeat(self, req=None):
"""
Parameters:
- req
"""
self.send_heartBeat(req)
return self.recv_heartBeat()
def send_heartBeat(self, req=None):
self._oprot.writeMessageBegin('heartBeat', TMessageType.CALL, self._seqid)
args = heartBeat_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_heartBeat(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = heartBeat_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "heartBeat failed: unknown result");
def balance(self, req=None):
"""
Parameters:
- req
"""
self.send_balance(req)
return self.recv_balance()
def send_balance(self, req=None):
self._oprot.writeMessageBegin('balance', TMessageType.CALL, self._seqid)
args = balance_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_balance(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = balance_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "balance failed: unknown result");
def leaderBalance(self, req=None):
"""
Parameters:
- req
"""
self.send_leaderBalance(req)
return self.recv_leaderBalance()
def send_leaderBalance(self, req=None):
self._oprot.writeMessageBegin('leaderBalance', TMessageType.CALL, self._seqid)
args = leaderBalance_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_leaderBalance(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = leaderBalance_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "leaderBalance failed: unknown result");
def regConfig(self, req=None):
"""
Parameters:
- req
"""
self.send_regConfig(req)
return self.recv_regConfig()
def send_regConfig(self, req=None):
self._oprot.writeMessageBegin('regConfig', TMessageType.CALL, self._seqid)
args = regConfig_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_regConfig(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = regConfig_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "regConfig failed: unknown result");
def getConfig(self, req=None):
"""
Parameters:
- req
"""
self.send_getConfig(req)
return self.recv_getConfig()
def send_getConfig(self, req=None):
self._oprot.writeMessageBegin('getConfig', TMessageType.CALL, self._seqid)
args = getConfig_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getConfig(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getConfig_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getConfig failed: unknown result");
def setConfig(self, req=None):
"""
Parameters:
- req
"""
self.send_setConfig(req)
return self.recv_setConfig()
def send_setConfig(self, req=None):
self._oprot.writeMessageBegin('setConfig', TMessageType.CALL, self._seqid)
args = setConfig_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_setConfig(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = setConfig_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "setConfig failed: unknown result");
def listConfigs(self, req=None):
"""
Parameters:
- req
"""
self.send_listConfigs(req)
return self.recv_listConfigs()
def send_listConfigs(self, req=None):
self._oprot.writeMessageBegin('listConfigs', TMessageType.CALL, self._seqid)
args = listConfigs_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listConfigs(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listConfigs_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listConfigs failed: unknown result");
def createSnapshot(self, req=None):
"""
Parameters:
- req
"""
self.send_createSnapshot(req)
return self.recv_createSnapshot()
def send_createSnapshot(self, req=None):
self._oprot.writeMessageBegin('createSnapshot', TMessageType.CALL, self._seqid)
args = createSnapshot_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createSnapshot(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createSnapshot_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createSnapshot failed: unknown result");
def dropSnapshot(self, req=None):
"""
Parameters:
- req
"""
self.send_dropSnapshot(req)
return self.recv_dropSnapshot()
def send_dropSnapshot(self, req=None):
self._oprot.writeMessageBegin('dropSnapshot', TMessageType.CALL, self._seqid)
args = dropSnapshot_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropSnapshot(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropSnapshot_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropSnapshot failed: unknown result");
def listSnapshots(self, req=None):
"""
Parameters:
- req
"""
self.send_listSnapshots(req)
return self.recv_listSnapshots()
def send_listSnapshots(self, req=None):
self._oprot.writeMessageBegin('listSnapshots', TMessageType.CALL, self._seqid)
args = listSnapshots_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listSnapshots(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listSnapshots_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listSnapshots failed: unknown result");
def runAdminJob(self, req=None):
"""
Parameters:
- req
"""
self.send_runAdminJob(req)
return self.recv_runAdminJob()
def send_runAdminJob(self, req=None):
self._oprot.writeMessageBegin('runAdminJob', TMessageType.CALL, self._seqid)
args = runAdminJob_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_runAdminJob(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = runAdminJob_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "runAdminJob failed: unknown result");
def addZone(self, req=None):
"""
Parameters:
- req
"""
self.send_addZone(req)
return self.recv_addZone()
def send_addZone(self, req=None):
self._oprot.writeMessageBegin('addZone', TMessageType.CALL, self._seqid)
args = addZone_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_addZone(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = addZone_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "addZone failed: unknown result");
def dropZone(self, req=None):
"""
Parameters:
- req
"""
self.send_dropZone(req)
return self.recv_dropZone()
def send_dropZone(self, req=None):
self._oprot.writeMessageBegin('dropZone', TMessageType.CALL, self._seqid)
args = dropZone_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropZone(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropZone_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropZone failed: unknown result");
def addHostIntoZone(self, req=None):
"""
Parameters:
- req
"""
self.send_addHostIntoZone(req)
return self.recv_addHostIntoZone()
def send_addHostIntoZone(self, req=None):
self._oprot.writeMessageBegin('addHostIntoZone', TMessageType.CALL, self._seqid)
args = addHostIntoZone_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_addHostIntoZone(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = addHostIntoZone_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "addHostIntoZone failed: unknown result");
def dropHostFromZone(self, req=None):
"""
Parameters:
- req
"""
self.send_dropHostFromZone(req)
return self.recv_dropHostFromZone()
def send_dropHostFromZone(self, req=None):
self._oprot.writeMessageBegin('dropHostFromZone', TMessageType.CALL, self._seqid)
args = dropHostFromZone_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropHostFromZone(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropHostFromZone_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropHostFromZone failed: unknown result");
def getZone(self, req=None):
"""
Parameters:
- req
"""
self.send_getZone(req)
return self.recv_getZone()
def send_getZone(self, req=None):
self._oprot.writeMessageBegin('getZone', TMessageType.CALL, self._seqid)
args = getZone_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getZone(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getZone_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getZone failed: unknown result");
def listZones(self, req=None):
"""
Parameters:
- req
"""
self.send_listZones(req)
return self.recv_listZones()
def send_listZones(self, req=None):
self._oprot.writeMessageBegin('listZones', TMessageType.CALL, self._seqid)
args = listZones_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listZones(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listZones_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listZones failed: unknown result");
def addGroup(self, req=None):
"""
Parameters:
- req
"""
self.send_addGroup(req)
return self.recv_addGroup()
def send_addGroup(self, req=None):
self._oprot.writeMessageBegin('addGroup', TMessageType.CALL, self._seqid)
args = addGroup_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_addGroup(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = addGroup_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "addGroup failed: unknown result");
def dropGroup(self, req=None):
"""
Parameters:
- req
"""
self.send_dropGroup(req)
return self.recv_dropGroup()
def send_dropGroup(self, req=None):
self._oprot.writeMessageBegin('dropGroup', TMessageType.CALL, self._seqid)
args = dropGroup_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropGroup(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropGroup_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropGroup failed: unknown result");
def addZoneIntoGroup(self, req=None):
"""
Parameters:
- req
"""
self.send_addZoneIntoGroup(req)
return self.recv_addZoneIntoGroup()
def send_addZoneIntoGroup(self, req=None):
self._oprot.writeMessageBegin('addZoneIntoGroup', TMessageType.CALL, self._seqid)
args = addZoneIntoGroup_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_addZoneIntoGroup(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = addZoneIntoGroup_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "addZoneIntoGroup failed: unknown result");
def dropZoneFromGroup(self, req=None):
"""
Parameters:
- req
"""
self.send_dropZoneFromGroup(req)
return self.recv_dropZoneFromGroup()
def send_dropZoneFromGroup(self, req=None):
self._oprot.writeMessageBegin('dropZoneFromGroup', TMessageType.CALL, self._seqid)
args = dropZoneFromGroup_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropZoneFromGroup(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropZoneFromGroup_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropZoneFromGroup failed: unknown result");
def getGroup(self, req=None):
"""
Parameters:
- req
"""
self.send_getGroup(req)
return self.recv_getGroup()
def send_getGroup(self, req=None):
self._oprot.writeMessageBegin('getGroup', TMessageType.CALL, self._seqid)
args = getGroup_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getGroup(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getGroup_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getGroup failed: unknown result");
def listGroups(self, req=None):
"""
Parameters:
- req
"""
self.send_listGroups(req)
return self.recv_listGroups()
def send_listGroups(self, req=None):
self._oprot.writeMessageBegin('listGroups', TMessageType.CALL, self._seqid)
args = listGroups_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listGroups(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listGroups_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listGroups failed: unknown result");
def createBackup(self, req=None):
"""
Parameters:
- req
"""
self.send_createBackup(req)
return self.recv_createBackup()
def send_createBackup(self, req=None):
self._oprot.writeMessageBegin('createBackup', TMessageType.CALL, self._seqid)
args = createBackup_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createBackup(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createBackup_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createBackup failed: unknown result");
def restoreMeta(self, req=None):
"""
Parameters:
- req
"""
self.send_restoreMeta(req)
return self.recv_restoreMeta()
def send_restoreMeta(self, req=None):
self._oprot.writeMessageBegin('restoreMeta', TMessageType.CALL, self._seqid)
args = restoreMeta_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_restoreMeta(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = restoreMeta_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "restoreMeta failed: unknown result");
def addListener(self, req=None):
"""
Parameters:
- req
"""
self.send_addListener(req)
return self.recv_addListener()
def send_addListener(self, req=None):
self._oprot.writeMessageBegin('addListener', TMessageType.CALL, self._seqid)
args = addListener_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_addListener(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = addListener_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "addListener failed: unknown result");
def removeListener(self, req=None):
"""
Parameters:
- req
"""
self.send_removeListener(req)
return self.recv_removeListener()
def send_removeListener(self, req=None):
self._oprot.writeMessageBegin('removeListener', TMessageType.CALL, self._seqid)
args = removeListener_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_removeListener(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = removeListener_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "removeListener failed: unknown result");
def listListener(self, req=None):
"""
Parameters:
- req
"""
self.send_listListener(req)
return self.recv_listListener()
def send_listListener(self, req=None):
self._oprot.writeMessageBegin('listListener', TMessageType.CALL, self._seqid)
args = listListener_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listListener(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listListener_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listListener failed: unknown result");
def getStatis(self, req=None):
"""
Parameters:
- req
"""
self.send_getStatis(req)
return self.recv_getStatis()
def send_getStatis(self, req=None):
self._oprot.writeMessageBegin('getStatis', TMessageType.CALL, self._seqid)
args = getStatis_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getStatis(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getStatis_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getStatis failed: unknown result");
def signInFTService(self, req=None):
"""
Parameters:
- req
"""
self.send_signInFTService(req)
return self.recv_signInFTService()
def send_signInFTService(self, req=None):
self._oprot.writeMessageBegin('signInFTService', TMessageType.CALL, self._seqid)
args = signInFTService_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_signInFTService(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = signInFTService_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "signInFTService failed: unknown result");
def signOutFTService(self, req=None):
"""
Parameters:
- req
"""
self.send_signOutFTService(req)
return self.recv_signOutFTService()
def send_signOutFTService(self, req=None):
self._oprot.writeMessageBegin('signOutFTService', TMessageType.CALL, self._seqid)
args = signOutFTService_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_signOutFTService(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = signOutFTService_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "signOutFTService failed: unknown result");
def listFTClients(self, req=None):
"""
Parameters:
- req
"""
self.send_listFTClients(req)
return self.recv_listFTClients()
def send_listFTClients(self, req=None):
self._oprot.writeMessageBegin('listFTClients', TMessageType.CALL, self._seqid)
args = listFTClients_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listFTClients(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listFTClients_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listFTClients failed: unknown result");
def createFTIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_createFTIndex(req)
return self.recv_createFTIndex()
def send_createFTIndex(self, req=None):
self._oprot.writeMessageBegin('createFTIndex', TMessageType.CALL, self._seqid)
args = createFTIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createFTIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createFTIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createFTIndex failed: unknown result");
def dropFTIndex(self, req=None):
"""
Parameters:
- req
"""
self.send_dropFTIndex(req)
return self.recv_dropFTIndex()
def send_dropFTIndex(self, req=None):
self._oprot.writeMessageBegin('dropFTIndex', TMessageType.CALL, self._seqid)
args = dropFTIndex_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_dropFTIndex(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = dropFTIndex_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "dropFTIndex failed: unknown result");
def listFTIndexes(self, req=None):
"""
Parameters:
- req
"""
self.send_listFTIndexes(req)
return self.recv_listFTIndexes()
def send_listFTIndexes(self, req=None):
self._oprot.writeMessageBegin('listFTIndexes', TMessageType.CALL, self._seqid)
args = listFTIndexes_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listFTIndexes(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listFTIndexes_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listFTIndexes failed: unknown result");
def createSession(self, req=None):
"""
Parameters:
- req
"""
self.send_createSession(req)
return self.recv_createSession()
def send_createSession(self, req=None):
self._oprot.writeMessageBegin('createSession', TMessageType.CALL, self._seqid)
args = createSession_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_createSession(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = createSession_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "createSession failed: unknown result");
def updateSessions(self, req=None):
"""
Parameters:
- req
"""
self.send_updateSessions(req)
return self.recv_updateSessions()
def send_updateSessions(self, req=None):
self._oprot.writeMessageBegin('updateSessions', TMessageType.CALL, self._seqid)
args = updateSessions_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_updateSessions(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = updateSessions_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "updateSessions failed: unknown result");
def listSessions(self, req=None):
"""
Parameters:
- req
"""
self.send_listSessions(req)
return self.recv_listSessions()
def send_listSessions(self, req=None):
self._oprot.writeMessageBegin('listSessions', TMessageType.CALL, self._seqid)
args = listSessions_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listSessions(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listSessions_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listSessions failed: unknown result");
def getSession(self, req=None):
"""
Parameters:
- req
"""
self.send_getSession(req)
return self.recv_getSession()
def send_getSession(self, req=None):
self._oprot.writeMessageBegin('getSession', TMessageType.CALL, self._seqid)
args = getSession_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getSession(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getSession_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getSession failed: unknown result");
def removeSession(self, req=None):
"""
Parameters:
- req
"""
self.send_removeSession(req)
return self.recv_removeSession()
def send_removeSession(self, req=None):
self._oprot.writeMessageBegin('removeSession', TMessageType.CALL, self._seqid)
args = removeSession_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_removeSession(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = removeSession_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "removeSession failed: unknown result");
def killQuery(self, req=None):
"""
Parameters:
- req
"""
self.send_killQuery(req)
return self.recv_killQuery()
def send_killQuery(self, req=None):
self._oprot.writeMessageBegin('killQuery', TMessageType.CALL, self._seqid)
args = killQuery_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_killQuery(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = killQuery_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "killQuery failed: unknown result");
def reportTaskFinish(self, req=None):
"""
Parameters:
- req
"""
self.send_reportTaskFinish(req)
return self.recv_reportTaskFinish()
def send_reportTaskFinish(self, req=None):
self._oprot.writeMessageBegin('reportTaskFinish', TMessageType.CALL, self._seqid)
args = reportTaskFinish_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_reportTaskFinish(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = reportTaskFinish_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "reportTaskFinish failed: unknown result");
def listCluster(self, req=None):
"""
Parameters:
- req
"""
self.send_listCluster(req)
return self.recv_listCluster()
def send_listCluster(self, req=None):
self._oprot.writeMessageBegin('listCluster', TMessageType.CALL, self._seqid)
args = listCluster_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_listCluster(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = listCluster_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "listCluster failed: unknown result");
def getMetaDirInfo(self, req=None):
"""
Parameters:
- req
"""
self.send_getMetaDirInfo(req)
return self.recv_getMetaDirInfo()
def send_getMetaDirInfo(self, req=None):
self._oprot.writeMessageBegin('getMetaDirInfo', TMessageType.CALL, self._seqid)
args = getMetaDirInfo_args()
args.req = req
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getMetaDirInfo(self, ):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getMetaDirInfo_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success != None:
return result.success
raise TApplicationException(TApplicationException.MISSING_RESULT, "getMetaDirInfo failed: unknown result");
class Processor(Iface, TProcessor):
_onewayMethods = ()
def __init__(self, handler):
TProcessor.__init__(self)
self._handler = handler
self._processMap = {}
self._priorityMap = {}
self._processMap["createSpace"] = Processor.process_createSpace
self._priorityMap["createSpace"] = TPriority.NORMAL
self._processMap["dropSpace"] = Processor.process_dropSpace
self._priorityMap["dropSpace"] = TPriority.NORMAL
self._processMap["getSpace"] = Processor.process_getSpace
self._priorityMap["getSpace"] = TPriority.NORMAL
self._processMap["listSpaces"] = Processor.process_listSpaces
self._priorityMap["listSpaces"] = TPriority.NORMAL
self._processMap["createTag"] = Processor.process_createTag
self._priorityMap["createTag"] = TPriority.NORMAL
self._processMap["alterTag"] = Processor.process_alterTag
self._priorityMap["alterTag"] = TPriority.NORMAL
self._processMap["dropTag"] = Processor.process_dropTag
self._priorityMap["dropTag"] = TPriority.NORMAL
self._processMap["getTag"] = Processor.process_getTag
self._priorityMap["getTag"] = TPriority.NORMAL
self._processMap["listTags"] = Processor.process_listTags
self._priorityMap["listTags"] = TPriority.NORMAL
self._processMap["createEdge"] = Processor.process_createEdge
self._priorityMap["createEdge"] = TPriority.NORMAL
self._processMap["alterEdge"] = Processor.process_alterEdge
self._priorityMap["alterEdge"] = TPriority.NORMAL
self._processMap["dropEdge"] = Processor.process_dropEdge
self._priorityMap["dropEdge"] = TPriority.NORMAL
self._processMap["getEdge"] = Processor.process_getEdge
self._priorityMap["getEdge"] = TPriority.NORMAL
self._processMap["listEdges"] = Processor.process_listEdges
self._priorityMap["listEdges"] = TPriority.NORMAL
self._processMap["listHosts"] = Processor.process_listHosts
self._priorityMap["listHosts"] = TPriority.NORMAL
self._processMap["getPartsAlloc"] = Processor.process_getPartsAlloc
self._priorityMap["getPartsAlloc"] = TPriority.NORMAL
self._processMap["listParts"] = Processor.process_listParts
self._priorityMap["listParts"] = TPriority.NORMAL
self._processMap["multiPut"] = Processor.process_multiPut
self._priorityMap["multiPut"] = TPriority.NORMAL
self._processMap["get"] = Processor.process_get
self._priorityMap["get"] = TPriority.NORMAL
self._processMap["multiGet"] = Processor.process_multiGet
self._priorityMap["multiGet"] = TPriority.NORMAL
self._processMap["remove"] = Processor.process_remove
self._priorityMap["remove"] = TPriority.NORMAL
self._processMap["removeRange"] = Processor.process_removeRange
self._priorityMap["removeRange"] = TPriority.NORMAL
self._processMap["scan"] = Processor.process_scan
self._priorityMap["scan"] = TPriority.NORMAL
self._processMap["createTagIndex"] = Processor.process_createTagIndex
self._priorityMap["createTagIndex"] = TPriority.NORMAL
self._processMap["dropTagIndex"] = Processor.process_dropTagIndex
self._priorityMap["dropTagIndex"] = TPriority.NORMAL
self._processMap["getTagIndex"] = Processor.process_getTagIndex
self._priorityMap["getTagIndex"] = TPriority.NORMAL
self._processMap["listTagIndexes"] = Processor.process_listTagIndexes
self._priorityMap["listTagIndexes"] = TPriority.NORMAL
self._processMap["rebuildTagIndex"] = Processor.process_rebuildTagIndex
self._priorityMap["rebuildTagIndex"] = TPriority.NORMAL
self._processMap["listTagIndexStatus"] = Processor.process_listTagIndexStatus
self._priorityMap["listTagIndexStatus"] = TPriority.NORMAL
self._processMap["createEdgeIndex"] = Processor.process_createEdgeIndex
self._priorityMap["createEdgeIndex"] = TPriority.NORMAL
self._processMap["dropEdgeIndex"] = Processor.process_dropEdgeIndex
self._priorityMap["dropEdgeIndex"] = TPriority.NORMAL
self._processMap["getEdgeIndex"] = Processor.process_getEdgeIndex
self._priorityMap["getEdgeIndex"] = TPriority.NORMAL
self._processMap["listEdgeIndexes"] = Processor.process_listEdgeIndexes
self._priorityMap["listEdgeIndexes"] = TPriority.NORMAL
self._processMap["rebuildEdgeIndex"] = Processor.process_rebuildEdgeIndex
self._priorityMap["rebuildEdgeIndex"] = TPriority.NORMAL
self._processMap["listEdgeIndexStatus"] = Processor.process_listEdgeIndexStatus
self._priorityMap["listEdgeIndexStatus"] = TPriority.NORMAL
self._processMap["createUser"] = Processor.process_createUser
self._priorityMap["createUser"] = TPriority.NORMAL
self._processMap["dropUser"] = Processor.process_dropUser
self._priorityMap["dropUser"] = TPriority.NORMAL
self._processMap["alterUser"] = Processor.process_alterUser
self._priorityMap["alterUser"] = TPriority.NORMAL
self._processMap["grantRole"] = Processor.process_grantRole
self._priorityMap["grantRole"] = TPriority.NORMAL
self._processMap["revokeRole"] = Processor.process_revokeRole
self._priorityMap["revokeRole"] = TPriority.NORMAL
self._processMap["listUsers"] = Processor.process_listUsers
self._priorityMap["listUsers"] = TPriority.NORMAL
self._processMap["listRoles"] = Processor.process_listRoles
self._priorityMap["listRoles"] = TPriority.NORMAL
self._processMap["getUserRoles"] = Processor.process_getUserRoles
self._priorityMap["getUserRoles"] = TPriority.NORMAL
self._processMap["changePassword"] = Processor.process_changePassword
self._priorityMap["changePassword"] = TPriority.NORMAL
self._processMap["heartBeat"] = Processor.process_heartBeat
self._priorityMap["heartBeat"] = TPriority.NORMAL
self._processMap["balance"] = Processor.process_balance
self._priorityMap["balance"] = TPriority.NORMAL
self._processMap["leaderBalance"] = Processor.process_leaderBalance
self._priorityMap["leaderBalance"] = TPriority.NORMAL
self._processMap["regConfig"] = Processor.process_regConfig
self._priorityMap["regConfig"] = TPriority.NORMAL
self._processMap["getConfig"] = Processor.process_getConfig
self._priorityMap["getConfig"] = TPriority.NORMAL
self._processMap["setConfig"] = Processor.process_setConfig
self._priorityMap["setConfig"] = TPriority.NORMAL
self._processMap["listConfigs"] = Processor.process_listConfigs
self._priorityMap["listConfigs"] = TPriority.NORMAL
self._processMap["createSnapshot"] = Processor.process_createSnapshot
self._priorityMap["createSnapshot"] = TPriority.NORMAL
self._processMap["dropSnapshot"] = Processor.process_dropSnapshot
self._priorityMap["dropSnapshot"] = TPriority.NORMAL
self._processMap["listSnapshots"] = Processor.process_listSnapshots
self._priorityMap["listSnapshots"] = TPriority.NORMAL
self._processMap["runAdminJob"] = Processor.process_runAdminJob
self._priorityMap["runAdminJob"] = TPriority.NORMAL
self._processMap["addZone"] = Processor.process_addZone
self._priorityMap["addZone"] = TPriority.NORMAL
self._processMap["dropZone"] = Processor.process_dropZone
self._priorityMap["dropZone"] = TPriority.NORMAL
self._processMap["addHostIntoZone"] = Processor.process_addHostIntoZone
self._priorityMap["addHostIntoZone"] = TPriority.NORMAL
self._processMap["dropHostFromZone"] = Processor.process_dropHostFromZone
self._priorityMap["dropHostFromZone"] = TPriority.NORMAL
self._processMap["getZone"] = Processor.process_getZone
self._priorityMap["getZone"] = TPriority.NORMAL
self._processMap["listZones"] = Processor.process_listZones
self._priorityMap["listZones"] = TPriority.NORMAL
self._processMap["addGroup"] = Processor.process_addGroup
self._priorityMap["addGroup"] = TPriority.NORMAL
self._processMap["dropGroup"] = Processor.process_dropGroup
self._priorityMap["dropGroup"] = TPriority.NORMAL
self._processMap["addZoneIntoGroup"] = Processor.process_addZoneIntoGroup
self._priorityMap["addZoneIntoGroup"] = TPriority.NORMAL
self._processMap["dropZoneFromGroup"] = Processor.process_dropZoneFromGroup
self._priorityMap["dropZoneFromGroup"] = TPriority.NORMAL
self._processMap["getGroup"] = Processor.process_getGroup
self._priorityMap["getGroup"] = TPriority.NORMAL
self._processMap["listGroups"] = Processor.process_listGroups
self._priorityMap["listGroups"] = TPriority.NORMAL
self._processMap["createBackup"] = Processor.process_createBackup
self._priorityMap["createBackup"] = TPriority.NORMAL
self._processMap["restoreMeta"] = Processor.process_restoreMeta
self._priorityMap["restoreMeta"] = TPriority.NORMAL
self._processMap["addListener"] = Processor.process_addListener
self._priorityMap["addListener"] = TPriority.NORMAL
self._processMap["removeListener"] = Processor.process_removeListener
self._priorityMap["removeListener"] = TPriority.NORMAL
self._processMap["listListener"] = Processor.process_listListener
self._priorityMap["listListener"] = TPriority.NORMAL
self._processMap["getStatis"] = Processor.process_getStatis
self._priorityMap["getStatis"] = TPriority.NORMAL
self._processMap["signInFTService"] = Processor.process_signInFTService
self._priorityMap["signInFTService"] = TPriority.NORMAL
self._processMap["signOutFTService"] = Processor.process_signOutFTService
self._priorityMap["signOutFTService"] = TPriority.NORMAL
self._processMap["listFTClients"] = Processor.process_listFTClients
self._priorityMap["listFTClients"] = TPriority.NORMAL
self._processMap["createFTIndex"] = Processor.process_createFTIndex
self._priorityMap["createFTIndex"] = TPriority.NORMAL
self._processMap["dropFTIndex"] = Processor.process_dropFTIndex
self._priorityMap["dropFTIndex"] = TPriority.NORMAL
self._processMap["listFTIndexes"] = Processor.process_listFTIndexes
self._priorityMap["listFTIndexes"] = TPriority.NORMAL
self._processMap["createSession"] = Processor.process_createSession
self._priorityMap["createSession"] = TPriority.NORMAL
self._processMap["updateSessions"] = Processor.process_updateSessions
self._priorityMap["updateSessions"] = TPriority.NORMAL
self._processMap["listSessions"] = Processor.process_listSessions
self._priorityMap["listSessions"] = TPriority.NORMAL
self._processMap["getSession"] = Processor.process_getSession
self._priorityMap["getSession"] = TPriority.NORMAL
self._processMap["removeSession"] = Processor.process_removeSession
self._priorityMap["removeSession"] = TPriority.NORMAL
self._processMap["killQuery"] = Processor.process_killQuery
self._priorityMap["killQuery"] = TPriority.NORMAL
self._processMap["reportTaskFinish"] = Processor.process_reportTaskFinish
self._priorityMap["reportTaskFinish"] = TPriority.NORMAL
self._processMap["listCluster"] = Processor.process_listCluster
self._priorityMap["listCluster"] = TPriority.NORMAL
self._processMap["getMetaDirInfo"] = Processor.process_getMetaDirInfo
self._priorityMap["getMetaDirInfo"] = TPriority.NORMAL
def onewayMethods(self):
l = []
l.extend(Processor._onewayMethods)
return tuple(l)
@thrift_process_main()
def process(self,): pass
@thrift_process_method(createSpace_args, oneway=False)
def process_createSpace(self, args, handler_ctx):
result = createSpace_result()
try:
result.success = self._handler.createSpace(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createSpace', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropSpace_args, oneway=False)
def process_dropSpace(self, args, handler_ctx):
result = dropSpace_result()
try:
result.success = self._handler.dropSpace(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropSpace', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getSpace_args, oneway=False)
def process_getSpace(self, args, handler_ctx):
result = getSpace_result()
try:
result.success = self._handler.getSpace(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getSpace', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listSpaces_args, oneway=False)
def process_listSpaces(self, args, handler_ctx):
result = listSpaces_result()
try:
result.success = self._handler.listSpaces(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listSpaces', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createTag_args, oneway=False)
def process_createTag(self, args, handler_ctx):
result = createTag_result()
try:
result.success = self._handler.createTag(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createTag', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(alterTag_args, oneway=False)
def process_alterTag(self, args, handler_ctx):
result = alterTag_result()
try:
result.success = self._handler.alterTag(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'alterTag', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropTag_args, oneway=False)
def process_dropTag(self, args, handler_ctx):
result = dropTag_result()
try:
result.success = self._handler.dropTag(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropTag', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getTag_args, oneway=False)
def process_getTag(self, args, handler_ctx):
result = getTag_result()
try:
result.success = self._handler.getTag(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getTag', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listTags_args, oneway=False)
def process_listTags(self, args, handler_ctx):
result = listTags_result()
try:
result.success = self._handler.listTags(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listTags', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createEdge_args, oneway=False)
def process_createEdge(self, args, handler_ctx):
result = createEdge_result()
try:
result.success = self._handler.createEdge(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createEdge', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(alterEdge_args, oneway=False)
def process_alterEdge(self, args, handler_ctx):
result = alterEdge_result()
try:
result.success = self._handler.alterEdge(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'alterEdge', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropEdge_args, oneway=False)
def process_dropEdge(self, args, handler_ctx):
result = dropEdge_result()
try:
result.success = self._handler.dropEdge(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropEdge', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getEdge_args, oneway=False)
def process_getEdge(self, args, handler_ctx):
result = getEdge_result()
try:
result.success = self._handler.getEdge(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getEdge', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listEdges_args, oneway=False)
def process_listEdges(self, args, handler_ctx):
result = listEdges_result()
try:
result.success = self._handler.listEdges(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listEdges', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listHosts_args, oneway=False)
def process_listHosts(self, args, handler_ctx):
result = listHosts_result()
try:
result.success = self._handler.listHosts(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listHosts', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getPartsAlloc_args, oneway=False)
def process_getPartsAlloc(self, args, handler_ctx):
result = getPartsAlloc_result()
try:
result.success = self._handler.getPartsAlloc(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getPartsAlloc', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listParts_args, oneway=False)
def process_listParts(self, args, handler_ctx):
result = listParts_result()
try:
result.success = self._handler.listParts(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listParts', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(multiPut_args, oneway=False)
def process_multiPut(self, args, handler_ctx):
result = multiPut_result()
try:
result.success = self._handler.multiPut(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'multiPut', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(get_args, oneway=False)
def process_get(self, args, handler_ctx):
result = get_result()
try:
result.success = self._handler.get(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'get', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(multiGet_args, oneway=False)
def process_multiGet(self, args, handler_ctx):
result = multiGet_result()
try:
result.success = self._handler.multiGet(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'multiGet', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(remove_args, oneway=False)
def process_remove(self, args, handler_ctx):
result = remove_result()
try:
result.success = self._handler.remove(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'remove', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(removeRange_args, oneway=False)
def process_removeRange(self, args, handler_ctx):
result = removeRange_result()
try:
result.success = self._handler.removeRange(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'removeRange', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(scan_args, oneway=False)
def process_scan(self, args, handler_ctx):
result = scan_result()
try:
result.success = self._handler.scan(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'scan', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createTagIndex_args, oneway=False)
def process_createTagIndex(self, args, handler_ctx):
result = createTagIndex_result()
try:
result.success = self._handler.createTagIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createTagIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropTagIndex_args, oneway=False)
def process_dropTagIndex(self, args, handler_ctx):
result = dropTagIndex_result()
try:
result.success = self._handler.dropTagIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropTagIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getTagIndex_args, oneway=False)
def process_getTagIndex(self, args, handler_ctx):
result = getTagIndex_result()
try:
result.success = self._handler.getTagIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getTagIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listTagIndexes_args, oneway=False)
def process_listTagIndexes(self, args, handler_ctx):
result = listTagIndexes_result()
try:
result.success = self._handler.listTagIndexes(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listTagIndexes', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(rebuildTagIndex_args, oneway=False)
def process_rebuildTagIndex(self, args, handler_ctx):
result = rebuildTagIndex_result()
try:
result.success = self._handler.rebuildTagIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'rebuildTagIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listTagIndexStatus_args, oneway=False)
def process_listTagIndexStatus(self, args, handler_ctx):
result = listTagIndexStatus_result()
try:
result.success = self._handler.listTagIndexStatus(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listTagIndexStatus', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createEdgeIndex_args, oneway=False)
def process_createEdgeIndex(self, args, handler_ctx):
result = createEdgeIndex_result()
try:
result.success = self._handler.createEdgeIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createEdgeIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropEdgeIndex_args, oneway=False)
def process_dropEdgeIndex(self, args, handler_ctx):
result = dropEdgeIndex_result()
try:
result.success = self._handler.dropEdgeIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropEdgeIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getEdgeIndex_args, oneway=False)
def process_getEdgeIndex(self, args, handler_ctx):
result = getEdgeIndex_result()
try:
result.success = self._handler.getEdgeIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getEdgeIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listEdgeIndexes_args, oneway=False)
def process_listEdgeIndexes(self, args, handler_ctx):
result = listEdgeIndexes_result()
try:
result.success = self._handler.listEdgeIndexes(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listEdgeIndexes', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(rebuildEdgeIndex_args, oneway=False)
def process_rebuildEdgeIndex(self, args, handler_ctx):
result = rebuildEdgeIndex_result()
try:
result.success = self._handler.rebuildEdgeIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'rebuildEdgeIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listEdgeIndexStatus_args, oneway=False)
def process_listEdgeIndexStatus(self, args, handler_ctx):
result = listEdgeIndexStatus_result()
try:
result.success = self._handler.listEdgeIndexStatus(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listEdgeIndexStatus', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createUser_args, oneway=False)
def process_createUser(self, args, handler_ctx):
result = createUser_result()
try:
result.success = self._handler.createUser(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createUser', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropUser_args, oneway=False)
def process_dropUser(self, args, handler_ctx):
result = dropUser_result()
try:
result.success = self._handler.dropUser(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropUser', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(alterUser_args, oneway=False)
def process_alterUser(self, args, handler_ctx):
result = alterUser_result()
try:
result.success = self._handler.alterUser(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'alterUser', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(grantRole_args, oneway=False)
def process_grantRole(self, args, handler_ctx):
result = grantRole_result()
try:
result.success = self._handler.grantRole(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'grantRole', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(revokeRole_args, oneway=False)
def process_revokeRole(self, args, handler_ctx):
result = revokeRole_result()
try:
result.success = self._handler.revokeRole(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'revokeRole', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listUsers_args, oneway=False)
def process_listUsers(self, args, handler_ctx):
result = listUsers_result()
try:
result.success = self._handler.listUsers(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listUsers', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listRoles_args, oneway=False)
def process_listRoles(self, args, handler_ctx):
result = listRoles_result()
try:
result.success = self._handler.listRoles(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listRoles', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getUserRoles_args, oneway=False)
def process_getUserRoles(self, args, handler_ctx):
result = getUserRoles_result()
try:
result.success = self._handler.getUserRoles(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getUserRoles', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(changePassword_args, oneway=False)
def process_changePassword(self, args, handler_ctx):
result = changePassword_result()
try:
result.success = self._handler.changePassword(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'changePassword', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(heartBeat_args, oneway=False)
def process_heartBeat(self, args, handler_ctx):
result = heartBeat_result()
try:
result.success = self._handler.heartBeat(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'heartBeat', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(balance_args, oneway=False)
def process_balance(self, args, handler_ctx):
result = balance_result()
try:
result.success = self._handler.balance(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'balance', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(leaderBalance_args, oneway=False)
def process_leaderBalance(self, args, handler_ctx):
result = leaderBalance_result()
try:
result.success = self._handler.leaderBalance(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'leaderBalance', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(regConfig_args, oneway=False)
def process_regConfig(self, args, handler_ctx):
result = regConfig_result()
try:
result.success = self._handler.regConfig(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'regConfig', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getConfig_args, oneway=False)
def process_getConfig(self, args, handler_ctx):
result = getConfig_result()
try:
result.success = self._handler.getConfig(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getConfig', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(setConfig_args, oneway=False)
def process_setConfig(self, args, handler_ctx):
result = setConfig_result()
try:
result.success = self._handler.setConfig(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'setConfig', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listConfigs_args, oneway=False)
def process_listConfigs(self, args, handler_ctx):
result = listConfigs_result()
try:
result.success = self._handler.listConfigs(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listConfigs', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createSnapshot_args, oneway=False)
def process_createSnapshot(self, args, handler_ctx):
result = createSnapshot_result()
try:
result.success = self._handler.createSnapshot(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createSnapshot', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropSnapshot_args, oneway=False)
def process_dropSnapshot(self, args, handler_ctx):
result = dropSnapshot_result()
try:
result.success = self._handler.dropSnapshot(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropSnapshot', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listSnapshots_args, oneway=False)
def process_listSnapshots(self, args, handler_ctx):
result = listSnapshots_result()
try:
result.success = self._handler.listSnapshots(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listSnapshots', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(runAdminJob_args, oneway=False)
def process_runAdminJob(self, args, handler_ctx):
result = runAdminJob_result()
try:
result.success = self._handler.runAdminJob(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'runAdminJob', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addZone_args, oneway=False)
def process_addZone(self, args, handler_ctx):
result = addZone_result()
try:
result.success = self._handler.addZone(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropZone_args, oneway=False)
def process_dropZone(self, args, handler_ctx):
result = dropZone_result()
try:
result.success = self._handler.dropZone(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addHostIntoZone_args, oneway=False)
def process_addHostIntoZone(self, args, handler_ctx):
result = addHostIntoZone_result()
try:
result.success = self._handler.addHostIntoZone(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addHostIntoZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropHostFromZone_args, oneway=False)
def process_dropHostFromZone(self, args, handler_ctx):
result = dropHostFromZone_result()
try:
result.success = self._handler.dropHostFromZone(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropHostFromZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getZone_args, oneway=False)
def process_getZone(self, args, handler_ctx):
result = getZone_result()
try:
result.success = self._handler.getZone(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listZones_args, oneway=False)
def process_listZones(self, args, handler_ctx):
result = listZones_result()
try:
result.success = self._handler.listZones(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listZones', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addGroup_args, oneway=False)
def process_addGroup(self, args, handler_ctx):
result = addGroup_result()
try:
result.success = self._handler.addGroup(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropGroup_args, oneway=False)
def process_dropGroup(self, args, handler_ctx):
result = dropGroup_result()
try:
result.success = self._handler.dropGroup(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addZoneIntoGroup_args, oneway=False)
def process_addZoneIntoGroup(self, args, handler_ctx):
result = addZoneIntoGroup_result()
try:
result.success = self._handler.addZoneIntoGroup(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addZoneIntoGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropZoneFromGroup_args, oneway=False)
def process_dropZoneFromGroup(self, args, handler_ctx):
result = dropZoneFromGroup_result()
try:
result.success = self._handler.dropZoneFromGroup(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropZoneFromGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getGroup_args, oneway=False)
def process_getGroup(self, args, handler_ctx):
result = getGroup_result()
try:
result.success = self._handler.getGroup(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listGroups_args, oneway=False)
def process_listGroups(self, args, handler_ctx):
result = listGroups_result()
try:
result.success = self._handler.listGroups(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listGroups', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createBackup_args, oneway=False)
def process_createBackup(self, args, handler_ctx):
result = createBackup_result()
try:
result.success = self._handler.createBackup(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createBackup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(restoreMeta_args, oneway=False)
def process_restoreMeta(self, args, handler_ctx):
result = restoreMeta_result()
try:
result.success = self._handler.restoreMeta(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'restoreMeta', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addListener_args, oneway=False)
def process_addListener(self, args, handler_ctx):
result = addListener_result()
try:
result.success = self._handler.addListener(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addListener', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(removeListener_args, oneway=False)
def process_removeListener(self, args, handler_ctx):
result = removeListener_result()
try:
result.success = self._handler.removeListener(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'removeListener', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listListener_args, oneway=False)
def process_listListener(self, args, handler_ctx):
result = listListener_result()
try:
result.success = self._handler.listListener(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listListener', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getStatis_args, oneway=False)
def process_getStatis(self, args, handler_ctx):
result = getStatis_result()
try:
result.success = self._handler.getStatis(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getStatis', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(signInFTService_args, oneway=False)
def process_signInFTService(self, args, handler_ctx):
result = signInFTService_result()
try:
result.success = self._handler.signInFTService(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'signInFTService', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(signOutFTService_args, oneway=False)
def process_signOutFTService(self, args, handler_ctx):
result = signOutFTService_result()
try:
result.success = self._handler.signOutFTService(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'signOutFTService', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listFTClients_args, oneway=False)
def process_listFTClients(self, args, handler_ctx):
result = listFTClients_result()
try:
result.success = self._handler.listFTClients(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listFTClients', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createFTIndex_args, oneway=False)
def process_createFTIndex(self, args, handler_ctx):
result = createFTIndex_result()
try:
result.success = self._handler.createFTIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createFTIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropFTIndex_args, oneway=False)
def process_dropFTIndex(self, args, handler_ctx):
result = dropFTIndex_result()
try:
result.success = self._handler.dropFTIndex(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropFTIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listFTIndexes_args, oneway=False)
def process_listFTIndexes(self, args, handler_ctx):
result = listFTIndexes_result()
try:
result.success = self._handler.listFTIndexes(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listFTIndexes', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createSession_args, oneway=False)
def process_createSession(self, args, handler_ctx):
result = createSession_result()
try:
result.success = self._handler.createSession(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createSession', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(updateSessions_args, oneway=False)
def process_updateSessions(self, args, handler_ctx):
result = updateSessions_result()
try:
result.success = self._handler.updateSessions(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'updateSessions', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listSessions_args, oneway=False)
def process_listSessions(self, args, handler_ctx):
result = listSessions_result()
try:
result.success = self._handler.listSessions(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listSessions', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getSession_args, oneway=False)
def process_getSession(self, args, handler_ctx):
result = getSession_result()
try:
result.success = self._handler.getSession(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getSession', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(removeSession_args, oneway=False)
def process_removeSession(self, args, handler_ctx):
result = removeSession_result()
try:
result.success = self._handler.removeSession(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'removeSession', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(killQuery_args, oneway=False)
def process_killQuery(self, args, handler_ctx):
result = killQuery_result()
try:
result.success = self._handler.killQuery(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'killQuery', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(reportTaskFinish_args, oneway=False)
def process_reportTaskFinish(self, args, handler_ctx):
result = reportTaskFinish_result()
try:
result.success = self._handler.reportTaskFinish(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'reportTaskFinish', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listCluster_args, oneway=False)
def process_listCluster(self, args, handler_ctx):
result = listCluster_result()
try:
result.success = self._handler.listCluster(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listCluster', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getMetaDirInfo_args, oneway=False)
def process_getMetaDirInfo(self, args, handler_ctx):
result = getMetaDirInfo_result()
try:
result.success = self._handler.getMetaDirInfo(args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getMetaDirInfo', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
Iface._processor_type = Processor
class ContextProcessor(ContextIface, TProcessor):
_onewayMethods = ()
def __init__(self, handler):
TProcessor.__init__(self)
self._handler = handler
self._processMap = {}
self._priorityMap = {}
self._processMap["createSpace"] = ContextProcessor.process_createSpace
self._priorityMap["createSpace"] = TPriority.NORMAL
self._processMap["dropSpace"] = ContextProcessor.process_dropSpace
self._priorityMap["dropSpace"] = TPriority.NORMAL
self._processMap["getSpace"] = ContextProcessor.process_getSpace
self._priorityMap["getSpace"] = TPriority.NORMAL
self._processMap["listSpaces"] = ContextProcessor.process_listSpaces
self._priorityMap["listSpaces"] = TPriority.NORMAL
self._processMap["createTag"] = ContextProcessor.process_createTag
self._priorityMap["createTag"] = TPriority.NORMAL
self._processMap["alterTag"] = ContextProcessor.process_alterTag
self._priorityMap["alterTag"] = TPriority.NORMAL
self._processMap["dropTag"] = ContextProcessor.process_dropTag
self._priorityMap["dropTag"] = TPriority.NORMAL
self._processMap["getTag"] = ContextProcessor.process_getTag
self._priorityMap["getTag"] = TPriority.NORMAL
self._processMap["listTags"] = ContextProcessor.process_listTags
self._priorityMap["listTags"] = TPriority.NORMAL
self._processMap["createEdge"] = ContextProcessor.process_createEdge
self._priorityMap["createEdge"] = TPriority.NORMAL
self._processMap["alterEdge"] = ContextProcessor.process_alterEdge
self._priorityMap["alterEdge"] = TPriority.NORMAL
self._processMap["dropEdge"] = ContextProcessor.process_dropEdge
self._priorityMap["dropEdge"] = TPriority.NORMAL
self._processMap["getEdge"] = ContextProcessor.process_getEdge
self._priorityMap["getEdge"] = TPriority.NORMAL
self._processMap["listEdges"] = ContextProcessor.process_listEdges
self._priorityMap["listEdges"] = TPriority.NORMAL
self._processMap["listHosts"] = ContextProcessor.process_listHosts
self._priorityMap["listHosts"] = TPriority.NORMAL
self._processMap["getPartsAlloc"] = ContextProcessor.process_getPartsAlloc
self._priorityMap["getPartsAlloc"] = TPriority.NORMAL
self._processMap["listParts"] = ContextProcessor.process_listParts
self._priorityMap["listParts"] = TPriority.NORMAL
self._processMap["multiPut"] = ContextProcessor.process_multiPut
self._priorityMap["multiPut"] = TPriority.NORMAL
self._processMap["get"] = ContextProcessor.process_get
self._priorityMap["get"] = TPriority.NORMAL
self._processMap["multiGet"] = ContextProcessor.process_multiGet
self._priorityMap["multiGet"] = TPriority.NORMAL
self._processMap["remove"] = ContextProcessor.process_remove
self._priorityMap["remove"] = TPriority.NORMAL
self._processMap["removeRange"] = ContextProcessor.process_removeRange
self._priorityMap["removeRange"] = TPriority.NORMAL
self._processMap["scan"] = ContextProcessor.process_scan
self._priorityMap["scan"] = TPriority.NORMAL
self._processMap["createTagIndex"] = ContextProcessor.process_createTagIndex
self._priorityMap["createTagIndex"] = TPriority.NORMAL
self._processMap["dropTagIndex"] = ContextProcessor.process_dropTagIndex
self._priorityMap["dropTagIndex"] = TPriority.NORMAL
self._processMap["getTagIndex"] = ContextProcessor.process_getTagIndex
self._priorityMap["getTagIndex"] = TPriority.NORMAL
self._processMap["listTagIndexes"] = ContextProcessor.process_listTagIndexes
self._priorityMap["listTagIndexes"] = TPriority.NORMAL
self._processMap["rebuildTagIndex"] = ContextProcessor.process_rebuildTagIndex
self._priorityMap["rebuildTagIndex"] = TPriority.NORMAL
self._processMap["listTagIndexStatus"] = ContextProcessor.process_listTagIndexStatus
self._priorityMap["listTagIndexStatus"] = TPriority.NORMAL
self._processMap["createEdgeIndex"] = ContextProcessor.process_createEdgeIndex
self._priorityMap["createEdgeIndex"] = TPriority.NORMAL
self._processMap["dropEdgeIndex"] = ContextProcessor.process_dropEdgeIndex
self._priorityMap["dropEdgeIndex"] = TPriority.NORMAL
self._processMap["getEdgeIndex"] = ContextProcessor.process_getEdgeIndex
self._priorityMap["getEdgeIndex"] = TPriority.NORMAL
self._processMap["listEdgeIndexes"] = ContextProcessor.process_listEdgeIndexes
self._priorityMap["listEdgeIndexes"] = TPriority.NORMAL
self._processMap["rebuildEdgeIndex"] = ContextProcessor.process_rebuildEdgeIndex
self._priorityMap["rebuildEdgeIndex"] = TPriority.NORMAL
self._processMap["listEdgeIndexStatus"] = ContextProcessor.process_listEdgeIndexStatus
self._priorityMap["listEdgeIndexStatus"] = TPriority.NORMAL
self._processMap["createUser"] = ContextProcessor.process_createUser
self._priorityMap["createUser"] = TPriority.NORMAL
self._processMap["dropUser"] = ContextProcessor.process_dropUser
self._priorityMap["dropUser"] = TPriority.NORMAL
self._processMap["alterUser"] = ContextProcessor.process_alterUser
self._priorityMap["alterUser"] = TPriority.NORMAL
self._processMap["grantRole"] = ContextProcessor.process_grantRole
self._priorityMap["grantRole"] = TPriority.NORMAL
self._processMap["revokeRole"] = ContextProcessor.process_revokeRole
self._priorityMap["revokeRole"] = TPriority.NORMAL
self._processMap["listUsers"] = ContextProcessor.process_listUsers
self._priorityMap["listUsers"] = TPriority.NORMAL
self._processMap["listRoles"] = ContextProcessor.process_listRoles
self._priorityMap["listRoles"] = TPriority.NORMAL
self._processMap["getUserRoles"] = ContextProcessor.process_getUserRoles
self._priorityMap["getUserRoles"] = TPriority.NORMAL
self._processMap["changePassword"] = ContextProcessor.process_changePassword
self._priorityMap["changePassword"] = TPriority.NORMAL
self._processMap["heartBeat"] = ContextProcessor.process_heartBeat
self._priorityMap["heartBeat"] = TPriority.NORMAL
self._processMap["balance"] = ContextProcessor.process_balance
self._priorityMap["balance"] = TPriority.NORMAL
self._processMap["leaderBalance"] = ContextProcessor.process_leaderBalance
self._priorityMap["leaderBalance"] = TPriority.NORMAL
self._processMap["regConfig"] = ContextProcessor.process_regConfig
self._priorityMap["regConfig"] = TPriority.NORMAL
self._processMap["getConfig"] = ContextProcessor.process_getConfig
self._priorityMap["getConfig"] = TPriority.NORMAL
self._processMap["setConfig"] = ContextProcessor.process_setConfig
self._priorityMap["setConfig"] = TPriority.NORMAL
self._processMap["listConfigs"] = ContextProcessor.process_listConfigs
self._priorityMap["listConfigs"] = TPriority.NORMAL
self._processMap["createSnapshot"] = ContextProcessor.process_createSnapshot
self._priorityMap["createSnapshot"] = TPriority.NORMAL
self._processMap["dropSnapshot"] = ContextProcessor.process_dropSnapshot
self._priorityMap["dropSnapshot"] = TPriority.NORMAL
self._processMap["listSnapshots"] = ContextProcessor.process_listSnapshots
self._priorityMap["listSnapshots"] = TPriority.NORMAL
self._processMap["runAdminJob"] = ContextProcessor.process_runAdminJob
self._priorityMap["runAdminJob"] = TPriority.NORMAL
self._processMap["addZone"] = ContextProcessor.process_addZone
self._priorityMap["addZone"] = TPriority.NORMAL
self._processMap["dropZone"] = ContextProcessor.process_dropZone
self._priorityMap["dropZone"] = TPriority.NORMAL
self._processMap["addHostIntoZone"] = ContextProcessor.process_addHostIntoZone
self._priorityMap["addHostIntoZone"] = TPriority.NORMAL
self._processMap["dropHostFromZone"] = ContextProcessor.process_dropHostFromZone
self._priorityMap["dropHostFromZone"] = TPriority.NORMAL
self._processMap["getZone"] = ContextProcessor.process_getZone
self._priorityMap["getZone"] = TPriority.NORMAL
self._processMap["listZones"] = ContextProcessor.process_listZones
self._priorityMap["listZones"] = TPriority.NORMAL
self._processMap["addGroup"] = ContextProcessor.process_addGroup
self._priorityMap["addGroup"] = TPriority.NORMAL
self._processMap["dropGroup"] = ContextProcessor.process_dropGroup
self._priorityMap["dropGroup"] = TPriority.NORMAL
self._processMap["addZoneIntoGroup"] = ContextProcessor.process_addZoneIntoGroup
self._priorityMap["addZoneIntoGroup"] = TPriority.NORMAL
self._processMap["dropZoneFromGroup"] = ContextProcessor.process_dropZoneFromGroup
self._priorityMap["dropZoneFromGroup"] = TPriority.NORMAL
self._processMap["getGroup"] = ContextProcessor.process_getGroup
self._priorityMap["getGroup"] = TPriority.NORMAL
self._processMap["listGroups"] = ContextProcessor.process_listGroups
self._priorityMap["listGroups"] = TPriority.NORMAL
self._processMap["createBackup"] = ContextProcessor.process_createBackup
self._priorityMap["createBackup"] = TPriority.NORMAL
self._processMap["restoreMeta"] = ContextProcessor.process_restoreMeta
self._priorityMap["restoreMeta"] = TPriority.NORMAL
self._processMap["addListener"] = ContextProcessor.process_addListener
self._priorityMap["addListener"] = TPriority.NORMAL
self._processMap["removeListener"] = ContextProcessor.process_removeListener
self._priorityMap["removeListener"] = TPriority.NORMAL
self._processMap["listListener"] = ContextProcessor.process_listListener
self._priorityMap["listListener"] = TPriority.NORMAL
self._processMap["getStatis"] = ContextProcessor.process_getStatis
self._priorityMap["getStatis"] = TPriority.NORMAL
self._processMap["signInFTService"] = ContextProcessor.process_signInFTService
self._priorityMap["signInFTService"] = TPriority.NORMAL
self._processMap["signOutFTService"] = ContextProcessor.process_signOutFTService
self._priorityMap["signOutFTService"] = TPriority.NORMAL
self._processMap["listFTClients"] = ContextProcessor.process_listFTClients
self._priorityMap["listFTClients"] = TPriority.NORMAL
self._processMap["createFTIndex"] = ContextProcessor.process_createFTIndex
self._priorityMap["createFTIndex"] = TPriority.NORMAL
self._processMap["dropFTIndex"] = ContextProcessor.process_dropFTIndex
self._priorityMap["dropFTIndex"] = TPriority.NORMAL
self._processMap["listFTIndexes"] = ContextProcessor.process_listFTIndexes
self._priorityMap["listFTIndexes"] = TPriority.NORMAL
self._processMap["createSession"] = ContextProcessor.process_createSession
self._priorityMap["createSession"] = TPriority.NORMAL
self._processMap["updateSessions"] = ContextProcessor.process_updateSessions
self._priorityMap["updateSessions"] = TPriority.NORMAL
self._processMap["listSessions"] = ContextProcessor.process_listSessions
self._priorityMap["listSessions"] = TPriority.NORMAL
self._processMap["getSession"] = ContextProcessor.process_getSession
self._priorityMap["getSession"] = TPriority.NORMAL
self._processMap["removeSession"] = ContextProcessor.process_removeSession
self._priorityMap["removeSession"] = TPriority.NORMAL
self._processMap["killQuery"] = ContextProcessor.process_killQuery
self._priorityMap["killQuery"] = TPriority.NORMAL
self._processMap["reportTaskFinish"] = ContextProcessor.process_reportTaskFinish
self._priorityMap["reportTaskFinish"] = TPriority.NORMAL
self._processMap["listCluster"] = ContextProcessor.process_listCluster
self._priorityMap["listCluster"] = TPriority.NORMAL
self._processMap["getMetaDirInfo"] = ContextProcessor.process_getMetaDirInfo
self._priorityMap["getMetaDirInfo"] = TPriority.NORMAL
def onewayMethods(self):
l = []
l.extend(ContextProcessor._onewayMethods)
return tuple(l)
@thrift_process_main()
def process(self,): pass
@thrift_process_method(createSpace_args, oneway=False)
def process_createSpace(self, args, handler_ctx):
result = createSpace_result()
try:
result.success = self._handler.createSpace(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createSpace', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropSpace_args, oneway=False)
def process_dropSpace(self, args, handler_ctx):
result = dropSpace_result()
try:
result.success = self._handler.dropSpace(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropSpace', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getSpace_args, oneway=False)
def process_getSpace(self, args, handler_ctx):
result = getSpace_result()
try:
result.success = self._handler.getSpace(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getSpace', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listSpaces_args, oneway=False)
def process_listSpaces(self, args, handler_ctx):
result = listSpaces_result()
try:
result.success = self._handler.listSpaces(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listSpaces', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createTag_args, oneway=False)
def process_createTag(self, args, handler_ctx):
result = createTag_result()
try:
result.success = self._handler.createTag(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createTag', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(alterTag_args, oneway=False)
def process_alterTag(self, args, handler_ctx):
result = alterTag_result()
try:
result.success = self._handler.alterTag(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'alterTag', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropTag_args, oneway=False)
def process_dropTag(self, args, handler_ctx):
result = dropTag_result()
try:
result.success = self._handler.dropTag(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropTag', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getTag_args, oneway=False)
def process_getTag(self, args, handler_ctx):
result = getTag_result()
try:
result.success = self._handler.getTag(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getTag', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listTags_args, oneway=False)
def process_listTags(self, args, handler_ctx):
result = listTags_result()
try:
result.success = self._handler.listTags(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listTags', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createEdge_args, oneway=False)
def process_createEdge(self, args, handler_ctx):
result = createEdge_result()
try:
result.success = self._handler.createEdge(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createEdge', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(alterEdge_args, oneway=False)
def process_alterEdge(self, args, handler_ctx):
result = alterEdge_result()
try:
result.success = self._handler.alterEdge(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'alterEdge', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropEdge_args, oneway=False)
def process_dropEdge(self, args, handler_ctx):
result = dropEdge_result()
try:
result.success = self._handler.dropEdge(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropEdge', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getEdge_args, oneway=False)
def process_getEdge(self, args, handler_ctx):
result = getEdge_result()
try:
result.success = self._handler.getEdge(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getEdge', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listEdges_args, oneway=False)
def process_listEdges(self, args, handler_ctx):
result = listEdges_result()
try:
result.success = self._handler.listEdges(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listEdges', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listHosts_args, oneway=False)
def process_listHosts(self, args, handler_ctx):
result = listHosts_result()
try:
result.success = self._handler.listHosts(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listHosts', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getPartsAlloc_args, oneway=False)
def process_getPartsAlloc(self, args, handler_ctx):
result = getPartsAlloc_result()
try:
result.success = self._handler.getPartsAlloc(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getPartsAlloc', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listParts_args, oneway=False)
def process_listParts(self, args, handler_ctx):
result = listParts_result()
try:
result.success = self._handler.listParts(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listParts', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(multiPut_args, oneway=False)
def process_multiPut(self, args, handler_ctx):
result = multiPut_result()
try:
result.success = self._handler.multiPut(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'multiPut', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(get_args, oneway=False)
def process_get(self, args, handler_ctx):
result = get_result()
try:
result.success = self._handler.get(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'get', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(multiGet_args, oneway=False)
def process_multiGet(self, args, handler_ctx):
result = multiGet_result()
try:
result.success = self._handler.multiGet(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'multiGet', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(remove_args, oneway=False)
def process_remove(self, args, handler_ctx):
result = remove_result()
try:
result.success = self._handler.remove(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'remove', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(removeRange_args, oneway=False)
def process_removeRange(self, args, handler_ctx):
result = removeRange_result()
try:
result.success = self._handler.removeRange(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'removeRange', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(scan_args, oneway=False)
def process_scan(self, args, handler_ctx):
result = scan_result()
try:
result.success = self._handler.scan(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'scan', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createTagIndex_args, oneway=False)
def process_createTagIndex(self, args, handler_ctx):
result = createTagIndex_result()
try:
result.success = self._handler.createTagIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createTagIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropTagIndex_args, oneway=False)
def process_dropTagIndex(self, args, handler_ctx):
result = dropTagIndex_result()
try:
result.success = self._handler.dropTagIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropTagIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getTagIndex_args, oneway=False)
def process_getTagIndex(self, args, handler_ctx):
result = getTagIndex_result()
try:
result.success = self._handler.getTagIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getTagIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listTagIndexes_args, oneway=False)
def process_listTagIndexes(self, args, handler_ctx):
result = listTagIndexes_result()
try:
result.success = self._handler.listTagIndexes(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listTagIndexes', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(rebuildTagIndex_args, oneway=False)
def process_rebuildTagIndex(self, args, handler_ctx):
result = rebuildTagIndex_result()
try:
result.success = self._handler.rebuildTagIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'rebuildTagIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listTagIndexStatus_args, oneway=False)
def process_listTagIndexStatus(self, args, handler_ctx):
result = listTagIndexStatus_result()
try:
result.success = self._handler.listTagIndexStatus(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listTagIndexStatus', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createEdgeIndex_args, oneway=False)
def process_createEdgeIndex(self, args, handler_ctx):
result = createEdgeIndex_result()
try:
result.success = self._handler.createEdgeIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createEdgeIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropEdgeIndex_args, oneway=False)
def process_dropEdgeIndex(self, args, handler_ctx):
result = dropEdgeIndex_result()
try:
result.success = self._handler.dropEdgeIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropEdgeIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getEdgeIndex_args, oneway=False)
def process_getEdgeIndex(self, args, handler_ctx):
result = getEdgeIndex_result()
try:
result.success = self._handler.getEdgeIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getEdgeIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listEdgeIndexes_args, oneway=False)
def process_listEdgeIndexes(self, args, handler_ctx):
result = listEdgeIndexes_result()
try:
result.success = self._handler.listEdgeIndexes(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listEdgeIndexes', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(rebuildEdgeIndex_args, oneway=False)
def process_rebuildEdgeIndex(self, args, handler_ctx):
result = rebuildEdgeIndex_result()
try:
result.success = self._handler.rebuildEdgeIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'rebuildEdgeIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listEdgeIndexStatus_args, oneway=False)
def process_listEdgeIndexStatus(self, args, handler_ctx):
result = listEdgeIndexStatus_result()
try:
result.success = self._handler.listEdgeIndexStatus(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listEdgeIndexStatus', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createUser_args, oneway=False)
def process_createUser(self, args, handler_ctx):
result = createUser_result()
try:
result.success = self._handler.createUser(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createUser', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropUser_args, oneway=False)
def process_dropUser(self, args, handler_ctx):
result = dropUser_result()
try:
result.success = self._handler.dropUser(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropUser', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(alterUser_args, oneway=False)
def process_alterUser(self, args, handler_ctx):
result = alterUser_result()
try:
result.success = self._handler.alterUser(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'alterUser', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(grantRole_args, oneway=False)
def process_grantRole(self, args, handler_ctx):
result = grantRole_result()
try:
result.success = self._handler.grantRole(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'grantRole', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(revokeRole_args, oneway=False)
def process_revokeRole(self, args, handler_ctx):
result = revokeRole_result()
try:
result.success = self._handler.revokeRole(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'revokeRole', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listUsers_args, oneway=False)
def process_listUsers(self, args, handler_ctx):
result = listUsers_result()
try:
result.success = self._handler.listUsers(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listUsers', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listRoles_args, oneway=False)
def process_listRoles(self, args, handler_ctx):
result = listRoles_result()
try:
result.success = self._handler.listRoles(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listRoles', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getUserRoles_args, oneway=False)
def process_getUserRoles(self, args, handler_ctx):
result = getUserRoles_result()
try:
result.success = self._handler.getUserRoles(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getUserRoles', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(changePassword_args, oneway=False)
def process_changePassword(self, args, handler_ctx):
result = changePassword_result()
try:
result.success = self._handler.changePassword(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'changePassword', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(heartBeat_args, oneway=False)
def process_heartBeat(self, args, handler_ctx):
result = heartBeat_result()
try:
result.success = self._handler.heartBeat(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'heartBeat', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(balance_args, oneway=False)
def process_balance(self, args, handler_ctx):
result = balance_result()
try:
result.success = self._handler.balance(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'balance', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(leaderBalance_args, oneway=False)
def process_leaderBalance(self, args, handler_ctx):
result = leaderBalance_result()
try:
result.success = self._handler.leaderBalance(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'leaderBalance', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(regConfig_args, oneway=False)
def process_regConfig(self, args, handler_ctx):
result = regConfig_result()
try:
result.success = self._handler.regConfig(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'regConfig', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getConfig_args, oneway=False)
def process_getConfig(self, args, handler_ctx):
result = getConfig_result()
try:
result.success = self._handler.getConfig(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getConfig', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(setConfig_args, oneway=False)
def process_setConfig(self, args, handler_ctx):
result = setConfig_result()
try:
result.success = self._handler.setConfig(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'setConfig', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listConfigs_args, oneway=False)
def process_listConfigs(self, args, handler_ctx):
result = listConfigs_result()
try:
result.success = self._handler.listConfigs(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listConfigs', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createSnapshot_args, oneway=False)
def process_createSnapshot(self, args, handler_ctx):
result = createSnapshot_result()
try:
result.success = self._handler.createSnapshot(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createSnapshot', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropSnapshot_args, oneway=False)
def process_dropSnapshot(self, args, handler_ctx):
result = dropSnapshot_result()
try:
result.success = self._handler.dropSnapshot(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropSnapshot', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listSnapshots_args, oneway=False)
def process_listSnapshots(self, args, handler_ctx):
result = listSnapshots_result()
try:
result.success = self._handler.listSnapshots(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listSnapshots', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(runAdminJob_args, oneway=False)
def process_runAdminJob(self, args, handler_ctx):
result = runAdminJob_result()
try:
result.success = self._handler.runAdminJob(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'runAdminJob', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addZone_args, oneway=False)
def process_addZone(self, args, handler_ctx):
result = addZone_result()
try:
result.success = self._handler.addZone(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropZone_args, oneway=False)
def process_dropZone(self, args, handler_ctx):
result = dropZone_result()
try:
result.success = self._handler.dropZone(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addHostIntoZone_args, oneway=False)
def process_addHostIntoZone(self, args, handler_ctx):
result = addHostIntoZone_result()
try:
result.success = self._handler.addHostIntoZone(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addHostIntoZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropHostFromZone_args, oneway=False)
def process_dropHostFromZone(self, args, handler_ctx):
result = dropHostFromZone_result()
try:
result.success = self._handler.dropHostFromZone(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropHostFromZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getZone_args, oneway=False)
def process_getZone(self, args, handler_ctx):
result = getZone_result()
try:
result.success = self._handler.getZone(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getZone', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listZones_args, oneway=False)
def process_listZones(self, args, handler_ctx):
result = listZones_result()
try:
result.success = self._handler.listZones(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listZones', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addGroup_args, oneway=False)
def process_addGroup(self, args, handler_ctx):
result = addGroup_result()
try:
result.success = self._handler.addGroup(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropGroup_args, oneway=False)
def process_dropGroup(self, args, handler_ctx):
result = dropGroup_result()
try:
result.success = self._handler.dropGroup(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addZoneIntoGroup_args, oneway=False)
def process_addZoneIntoGroup(self, args, handler_ctx):
result = addZoneIntoGroup_result()
try:
result.success = self._handler.addZoneIntoGroup(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addZoneIntoGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropZoneFromGroup_args, oneway=False)
def process_dropZoneFromGroup(self, args, handler_ctx):
result = dropZoneFromGroup_result()
try:
result.success = self._handler.dropZoneFromGroup(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropZoneFromGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getGroup_args, oneway=False)
def process_getGroup(self, args, handler_ctx):
result = getGroup_result()
try:
result.success = self._handler.getGroup(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getGroup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listGroups_args, oneway=False)
def process_listGroups(self, args, handler_ctx):
result = listGroups_result()
try:
result.success = self._handler.listGroups(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listGroups', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createBackup_args, oneway=False)
def process_createBackup(self, args, handler_ctx):
result = createBackup_result()
try:
result.success = self._handler.createBackup(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createBackup', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(restoreMeta_args, oneway=False)
def process_restoreMeta(self, args, handler_ctx):
result = restoreMeta_result()
try:
result.success = self._handler.restoreMeta(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'restoreMeta', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(addListener_args, oneway=False)
def process_addListener(self, args, handler_ctx):
result = addListener_result()
try:
result.success = self._handler.addListener(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'addListener', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(removeListener_args, oneway=False)
def process_removeListener(self, args, handler_ctx):
result = removeListener_result()
try:
result.success = self._handler.removeListener(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'removeListener', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listListener_args, oneway=False)
def process_listListener(self, args, handler_ctx):
result = listListener_result()
try:
result.success = self._handler.listListener(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listListener', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getStatis_args, oneway=False)
def process_getStatis(self, args, handler_ctx):
result = getStatis_result()
try:
result.success = self._handler.getStatis(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getStatis', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(signInFTService_args, oneway=False)
def process_signInFTService(self, args, handler_ctx):
result = signInFTService_result()
try:
result.success = self._handler.signInFTService(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'signInFTService', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(signOutFTService_args, oneway=False)
def process_signOutFTService(self, args, handler_ctx):
result = signOutFTService_result()
try:
result.success = self._handler.signOutFTService(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'signOutFTService', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listFTClients_args, oneway=False)
def process_listFTClients(self, args, handler_ctx):
result = listFTClients_result()
try:
result.success = self._handler.listFTClients(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listFTClients', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createFTIndex_args, oneway=False)
def process_createFTIndex(self, args, handler_ctx):
result = createFTIndex_result()
try:
result.success = self._handler.createFTIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createFTIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(dropFTIndex_args, oneway=False)
def process_dropFTIndex(self, args, handler_ctx):
result = dropFTIndex_result()
try:
result.success = self._handler.dropFTIndex(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'dropFTIndex', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listFTIndexes_args, oneway=False)
def process_listFTIndexes(self, args, handler_ctx):
result = listFTIndexes_result()
try:
result.success = self._handler.listFTIndexes(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listFTIndexes', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(createSession_args, oneway=False)
def process_createSession(self, args, handler_ctx):
result = createSession_result()
try:
result.success = self._handler.createSession(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'createSession', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(updateSessions_args, oneway=False)
def process_updateSessions(self, args, handler_ctx):
result = updateSessions_result()
try:
result.success = self._handler.updateSessions(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'updateSessions', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listSessions_args, oneway=False)
def process_listSessions(self, args, handler_ctx):
result = listSessions_result()
try:
result.success = self._handler.listSessions(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listSessions', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getSession_args, oneway=False)
def process_getSession(self, args, handler_ctx):
result = getSession_result()
try:
result.success = self._handler.getSession(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getSession', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(removeSession_args, oneway=False)
def process_removeSession(self, args, handler_ctx):
result = removeSession_result()
try:
result.success = self._handler.removeSession(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'removeSession', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(killQuery_args, oneway=False)
def process_killQuery(self, args, handler_ctx):
result = killQuery_result()
try:
result.success = self._handler.killQuery(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'killQuery', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(reportTaskFinish_args, oneway=False)
def process_reportTaskFinish(self, args, handler_ctx):
result = reportTaskFinish_result()
try:
result.success = self._handler.reportTaskFinish(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'reportTaskFinish', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(listCluster_args, oneway=False)
def process_listCluster(self, args, handler_ctx):
result = listCluster_result()
try:
result.success = self._handler.listCluster(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'listCluster', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
@thrift_process_method(getMetaDirInfo_args, oneway=False)
def process_getMetaDirInfo(self, args, handler_ctx):
result = getMetaDirInfo_result()
try:
result.success = self._handler.getMetaDirInfo(handler_ctx, args.req)
except:
ex = sys.exc_info()[1]
self._event_handler.handlerError(handler_ctx, 'getMetaDirInfo', ex)
result = Thrift.TApplicationException(message=repr(ex))
return result
ContextIface._processor_type = ContextProcessor
fix_spec(all_structs)
del all_structs
| isUnion |
test_user_event.py | # Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
from unittest.mock import patch, Mock
import unittest
import pytest
from cla.models.dynamo_models import User, Project, Company, CCLAWhitelistRequest
from cla.models.event_types import EventType
from cla.controllers import user as user_controller
from cla.auth import AuthUser
@pytest.fixture
def create_event_user():
user_controller.create_event = Mock()
class TestRequestCompanyWhitelist:
def setup(self) -> None:
self.old_load = User.load
self.old_get_user_name = User.get_user_name
self.get_user_emails = User.get_user_emails
self.get_user_email = User.get_user_email
self.company_load = Company.load
self.get_company_name = Company.get_company_name
self.project_load = Project.load
self.get_project_name = Project.get_project_name
def teardown(self) -> None:
User.load = self.old_load
User.get_user_name = self.old_get_user_name
User.get_user_emails = self.get_user_emails
User.get_user_email = self.get_user_email
Company.load = self.company_load
Company.get_company_name = self.get_company_name
Project.load = self.project_load
Project.get_project_name = self.get_project_name
def test_request_company_whitelist(self, create_event_user, project, company, user):
""" Test user requesting to be added to the Approved List event """
with patch('cla.controllers.user.Event.create_event') as mock_event:
event_type = EventType.RequestCompanyWL
User.load = Mock()
User.get_user_name = Mock(return_value=user.get_user_name())
User.get_user_emails = Mock(return_value=[user.get_user_email()])
User.get_user_email = Mock(return_value=user.get_user_email())
Company.load = Mock()
Company.get_company_name = Mock(return_value=company.get_company_name())
Project.load = Mock()
Project.get_project_name = Mock(return_value=project.get_project_name())
user_controller.get_email_service = Mock()
user_controller.send = Mock()
user_controller.request_company_whitelist(
user.get_user_id(),
company.get_company_id(),
user.get_user_name(),
user.get_user_email(),
project.get_project_id(),
message="Please add",
recipient_name="Recipient Name",
recipient_email="Recipient Email",
)
event_data = (f'CLA: contributor {user.get_user_name()} requests to be Approved for the '
f'project: {project.get_project_name()} '
f'organization: {company.get_company_name()} '
f'as {user.get_user_name()} <{user.get_user_email()}>')
mock_event.assert_called_once_with(
event_user_id=user.get_user_id(),
event_project_id=project.get_project_id(),
event_company_id=company.get_company_id(),
event_type=event_type,
event_data=event_data,
event_summary=event_data,
contains_pii=True,
)
class TestInviteClaManager:
def setup(self):
self.user_load = User.load
self.load_project_by_name = Project.load_project_by_name
self.save = CCLAWhitelistRequest.save
def teardown(self):
User.load = self.user_load
Project.load_project_by_name = self.load_project_by_name
CCLAWhitelistRequest.save = self.save
@patch('cla.controllers.user.Event.create_event')
def test_invite_cla_manager(self, mock_event, create_event_user, user):
""" Test send email to CLA manager event """
User.load = Mock()
Project.load_project_by_name = Mock()
CCLAWhitelistRequest.save = Mock()
user_controller.send_email_to_cla_manager = Mock()
contributor_id = user.get_user_id()
contributor_name = user.get_user_name()
contributor_email = user.get_user_email()
cla_manager_name = "admin"
cla_manager_email = "[email protected]"
project_name = "foo_project"
company_name = "Test Company"
event_data = (f'sent email to CLA Manager: {cla_manager_name} with email {cla_manager_email} '
f'for project {project_name} and company {company_name} '
f'to user {contributor_name} with email {contributor_email}')
# TODO FIX Unit test - need to mock Project load_project_by_name() function
user_controller.invite_cla_manager(contributor_id, contributor_name, contributor_email,
cla_manager_name, cla_manager_email,
project_name, company_name)
mock_event.assert_called_once_with(
event_user_id=contributor_id,
event_project_name=project_name,
event_data=event_data,
event_type=EventType.InviteAdmin,
event_summary=event_data,
contains_pii=True,
)
class TestRequestCompanyCCLA:
def setup(self):
self.user_load = User.load
self.get_user_name = User.get_user_name
self.company_load = Company.load
self.project_load = Project.load
self.get_project_name = Project.get_project_name
self.get_managers = Company.get_managers
def teardown(self):
User.load = self.user_load
User.get_user_name = self.get_user_name
Company.load = self.company_load
Project.load = self.project_load
Project.get_project_name = self.get_project_name
Company.get_managers = self.get_managers
@patch('cla.controllers.user.Event.create_event')
def | (self, mock_event, create_event_user, user, project, company):
""" Test request company ccla event """
User.load = Mock()
User.get_user_name = Mock(return_value=user.get_user_name())
email = user.get_user_email()
Company.load = Mock()
Project.load = Mock()
Project.get_project_name = Mock(return_value=project.get_project_name())
manager = User(lf_username="harold", user_email="[email protected]")
Company.get_managers = Mock(return_value=[manager, ])
event_data = f"Sent email to sign ccla for {project.get_project_name()}"
CCLAWhitelistRequest.save = Mock(return_value=None)
user_controller.request_company_ccla(
user.get_user_id(), email, company.get_company_id(), project.get_project_id()
)
mock_event.assert_called_once_with(
event_data=event_data,
event_summary=event_data,
event_type=EventType.RequestCCLA,
event_user_id=user.get_user_id(),
event_company_id=company.get_company_id(),
contains_pii=False,
)
| test_request_company_ccla |
mod.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2020 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed under the MIT license, which can be found here:
// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
//---------------------------------------------------------------------------//
/*!
Module with all the code for managing the view for Tables.
!*/
use qt_widgets::QCheckBox;
use qt_widgets::QAction;
use qt_widgets::QComboBox;
use qt_widgets::QGridLayout;
use qt_widgets::QLineEdit;
use qt_widgets::QPushButton;
use qt_widgets::QTableView;
use qt_widgets::QMenu;
use qt_widgets::QWidget;
use qt_widgets::QScrollArea;
use qt_widgets::QLabel;
use qt_gui::QListOfQStandardItem;
use qt_gui::QStandardItem;
use qt_gui::QStandardItemModel;
use qt_core::QAbstractItemModel;
use qt_core::QBox;
use qt_core::QModelIndex;
use qt_core::CheckState;
use qt_core::QFlags;
use qt_core::AlignmentFlag;
use qt_core::QSortFilterProxyModel;
use qt_core::QStringList;
use qt_core::QString;
use qt_core::QTimer;
use qt_core::QVariant;
use qt_core::q_item_selection_model::SelectionFlag;
use qt_core::MatchFlag;
use qt_core::QPtr;
use qt_core::QSignalBlocker;
use qt_core::QObject;
use cpp_core::Ptr;
use std::collections::BTreeMap;
use std::{fmt, fmt::Debug};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::sync::atomic::{AtomicBool, AtomicPtr};
use std::rc::Rc;
use rpfm_error::{ErrorKind, Result};
use rpfm_lib::common::parse_str_as_bool;
use rpfm_lib::packedfile::PackedFileType;
use rpfm_lib::packedfile::table::{DependencyData, anim_fragment::AnimFragment, animtable::AnimTable, DecodedData, db::DB, loc::Loc, matched_combat::MatchedCombat, Table};
use rpfm_lib::schema::{Definition, FieldType, Schema, VersionedFile};
use rpfm_lib::SCHEMA;
use rpfm_lib::SETTINGS;
use crate::app_ui::AppUI;
use crate::CENTRAL_COMMAND;
use crate::communications::*;
use crate::diagnostics_ui::DiagnosticsUI;
use crate::ffi::*;
use crate::global_search_ui::GlobalSearchUI;
use crate::locale::{qtr, qtre};
use crate::packfile_contents_ui::PackFileContentsUI;
use crate::packedfile_views::{View, ViewType};
use crate::utils::atomic_from_ptr;
use crate::utils::create_grid_layout;
use crate::utils::show_dialog;
use crate::utils::ptr_from_atomic;
use self::slots::*;
use self::utils::*;
mod connections;
pub mod slots;
mod raw;
mod shortcuts;
mod tips;
pub mod utils;
// Column default sizes.
pub static COLUMN_SIZE_BOOLEAN: i32 = 100;
pub static COLUMN_SIZE_NUMBER: i32 = 140;
pub static COLUMN_SIZE_STRING: i32 = 350;
pub static ITEM_HAS_SOURCE_VALUE: i32 = 30;
pub static ITEM_SOURCE_VALUE: i32 = 31;
pub static ITEM_IS_SEQUENCE: i32 = 35;
pub static ITEM_SEQUENCE_DATA: i32 = 36;
//-------------------------------------------------------------------------------//
// Enums & Structs
//-------------------------------------------------------------------------------//
/// This enum is used to distinguish between the different types of tables we can decode.
#[derive(Clone, Debug)]
pub enum TableType {
AnimFragment(AnimFragment),
AnimTable(AnimTable),
DependencyManager(Vec<Vec<DecodedData>>),
DB(DB),
Loc(Loc),
MatchedCombat(MatchedCombat),
/// This one is for random views that just need a table with advanced behavior.
NormalTable(Table),
}
/// Enum to know what operation was done while editing tables, so we can revert them with undo.
pub enum TableOperations {
/// Intended for any kind of item editing. Holds a Vec<((row, column), AtomicPtr<item>)>, so we can do this in batches.
Editing(Vec<((i32, i32), AtomicPtr<QStandardItem>)>),
/// Intended for when adding/inserting rows. It holds a list of positions where the rows where inserted.
AddRows(Vec<i32>),
/// Intended for when removing rows. It holds a list of positions where the rows where deleted and the deleted rows data, in consecutive batches.
RemoveRows(Vec<(i32, Vec<Vec<AtomicPtr<QStandardItem>>>)>),
/// It holds a copy of the entire table, before importing.
ImportTSV(Vec<AtomicPtr<QListOfQStandardItem>>),
/// A Jack-of-all-Trades. It holds a Vec<TableOperations>, for those situations one is not enough.
Carolina(Vec<TableOperations>),
}
/// This struct contains all the stuff needed to perform a table search. There is one per table, integrated in the view.
#[derive(Clone)]
pub struct TableSearch {
pattern: Ptr<QString>,
replace: Ptr<QString>,
regex: bool,
case_sensitive: bool,
column: Option<i32>,
/// This one contains the QModelIndex of the model and the QModelIndex of the filter, if exists.
matches: Vec<(Ptr<QModelIndex>, Option<Ptr<QModelIndex>>)>,
current_item: Option<u64>,
}
/// This enum defines the operation to be done when updating something related to the TableSearch.
pub enum TableSearchUpdate {
Update,
Search,
PrevMatch,
NextMatch,
}
/// This struct contains pointers to all the widgets in a Table View.
pub struct TableView {
table_view_primary: QBox<QTableView>,
table_view_frozen: QBox<QTableView>,
table_filter: QBox<QSortFilterProxyModel>,
table_model: QBox<QStandardItemModel>,
filter_base_widget: QBox<QWidget>,
filters: Arc<RwLock<Vec<Arc<FilterView>>>>,
column_sort_state: Arc<RwLock<(i32, i8)>>,
context_menu: QBox<QMenu>,
context_menu_add_rows: QPtr<QAction>,
context_menu_insert_rows: QPtr<QAction>,
context_menu_delete_rows: QPtr<QAction>,
context_menu_delete_rows_not_in_filter: QPtr<QAction>,
context_menu_clone_and_append: QPtr<QAction>,
context_menu_clone_and_insert: QPtr<QAction>,
context_menu_copy: QPtr<QAction>,
context_menu_copy_as_lua_table: QPtr<QAction>,
context_menu_paste: QPtr<QAction>,
context_menu_paste_as_new_row: QPtr<QAction>,
context_menu_invert_selection: QPtr<QAction>,
context_menu_reset_selection: QPtr<QAction>,
context_menu_rewrite_selection: QPtr<QAction>,
context_menu_generate_ids: QPtr<QAction>,
context_menu_undo: QPtr<QAction>,
context_menu_redo: QPtr<QAction>,
context_menu_import_tsv: QPtr<QAction>,
context_menu_export_tsv: QPtr<QAction>,
context_menu_resize_columns: QPtr<QAction>,
context_menu_sidebar: QPtr<QAction>,
context_menu_search: QPtr<QAction>,
context_menu_cascade_edition: QPtr<QAction>,
smart_delete: QBox<QAction>,
context_menu_go_to: QBox<QMenu>,
context_menu_go_to_definition: QPtr<QAction>,
context_menu_go_to_loc: Vec<QPtr<QAction>>,
sidebar_scroll_area: QBox<QScrollArea>,
search_widget: QBox<QWidget>,
sidebar_hide_checkboxes: Vec<QBox<QCheckBox>>,
sidebar_hide_checkboxes_all: QBox<QCheckBox>,
sidebar_freeze_checkboxes: Vec<QBox<QCheckBox>>,
sidebar_freeze_checkboxes_all: QBox<QCheckBox>,
search_search_line_edit: QBox<QLineEdit>,
search_replace_line_edit: QBox<QLineEdit>,
search_search_button: QBox<QPushButton>,
search_replace_current_button: QBox<QPushButton>,
search_replace_all_button: QBox<QPushButton>,
search_close_button: QBox<QPushButton>,
search_prev_match_button: QBox<QPushButton>,
search_next_match_button: QBox<QPushButton>,
search_matches_label: QBox<QLabel>,
search_column_selector: QBox<QComboBox>,
search_case_sensitive_button: QBox<QPushButton>,
search_data: Arc<RwLock<TableSearch>>,
table_name: Option<String>,
table_uuid: Option<String>,
packed_file_path: Option<Arc<RwLock<Vec<String>>>>,
packed_file_type: Arc<PackedFileType>,
table_definition: Arc<RwLock<Definition>>,
dependency_data: Arc<RwLock<BTreeMap<i32, DependencyData>>>,
save_lock: Arc<AtomicBool>,
undo_lock: Arc<AtomicBool>,
undo_model: QBox<QStandardItemModel>,
history_undo: Arc<RwLock<Vec<TableOperations>>>,
history_redo: Arc<RwLock<Vec<TableOperations>>>,
pub timer_delayed_updates: QBox<QTimer>,
}
/// This struct contains the stuff needed for a filter row.
pub struct FilterView {
filter_widget: QBox<QWidget>,
filter_case_sensitive_button: QBox<QPushButton>,
filter_column_selector: QBox<QComboBox>,
filter_line_edit: QBox<QLineEdit>,
filter_add: QBox<QPushButton>,
filter_remove: QBox<QPushButton>,
}
//-------------------------------------------------------------------------------//
// Implementations
//-------------------------------------------------------------------------------//
/// Implementation for `TableView`.
impl TableView {
/// This function creates a new Table View, and sets up his slots and connections.
///
/// NOTE: To open the dependency list, pass it an empty path.
pub unsafe fn new_view(
parent: &QBox<QWidget>,
app_ui: &Rc<AppUI>,
global_search_ui: &Rc<GlobalSearchUI>,
pack_file_contents_ui: &Rc<PackFileContentsUI>,
diagnostics_ui: &Rc<DiagnosticsUI>,
table_data: TableType,
packed_file_path: Option<Arc<RwLock<Vec<String>>>>
) -> Result<Arc<Self>> {
let (table_definition, table_name, table_uuid, packed_file_type) = match table_data {
TableType::DependencyManager(_) => {
let schema = SCHEMA.read().unwrap();
(schema.as_ref().unwrap().get_ref_versioned_file_dep_manager().unwrap().get_version_list()[0].clone(), None, None, PackedFileType::DependencyPackFilesList)
},
TableType::DB(ref table) => (table.get_definition(), Some(table.get_table_name()), Some(table.get_uuid()), PackedFileType::DB),
TableType::Loc(ref table) => (table.get_definition(), None, None, PackedFileType::Loc),
TableType::MatchedCombat(ref table) => (table.get_definition(), None, None, PackedFileType::MatchedCombat),
TableType::AnimTable(ref table) => (table.get_definition(), None, None, PackedFileType::AnimTable),
TableType::AnimFragment(ref table) => (table.get_definition(), None, None, PackedFileType::AnimFragment),
TableType::NormalTable(ref table) => (table.get_definition(), None, None, PackedFileType::Unknown),
};
// Get the dependency data of this Table.
let table_name_for_ref = if let Some(ref name) = table_name { name.to_owned() } else { "".to_owned() };
let dependency_data = get_reference_data(&table_name_for_ref, &table_definition)?;
// Create the locks for undoing and saving. These are needed to optimize the undo/saving process.
let undo_lock = Arc::new(AtomicBool::new(false));
let save_lock = Arc::new(AtomicBool::new(false));
// Prepare the Table and its model.
let table_filter = new_tableview_filter_safe(parent.static_upcast());
let table_model = QStandardItemModel::new_1a(parent);
let undo_model = QStandardItemModel::new_1a(parent);
table_filter.set_source_model(&table_model);
let (table_view_primary, table_view_frozen) = new_tableview_frozen_safe(&parent.as_ptr());
set_frozen_data_model_safe(&table_view_primary.as_ptr(), &table_filter.static_upcast::<QAbstractItemModel>().as_ptr());
// Make the last column fill all the available space, if the setting says so.
if SETTINGS.read().unwrap().settings_bool["extend_last_column_on_tables"] {
table_view_primary.horizontal_header().set_stretch_last_section(true);
table_view_frozen.horizontal_header().set_stretch_last_section(true);
}
// Setup tight mode if the setting is enabled.
if SETTINGS.read().unwrap().settings_bool["tight_table_mode"] {
table_view_primary.vertical_header().set_minimum_section_size(22);
table_view_primary.vertical_header().set_maximum_section_size(22);
table_view_primary.vertical_header().set_default_section_size(22);
table_view_frozen.vertical_header().set_minimum_section_size(22);
table_view_frozen.vertical_header().set_maximum_section_size(22);
table_view_frozen.vertical_header().set_default_section_size(22);
}
let warning_message = QLabel::from_q_string_q_widget(&qtr("dependency_packfile_list_label"), parent);
// Create the filter's widgets.
let filter_base_widget = QWidget::new_1a(parent);
let _filter_base_grid = create_grid_layout(filter_base_widget.static_upcast());
// Add everything to the grid.
let layout: QPtr<QGridLayout> = parent.layout().static_downcast();
if let PackedFileType::DependencyPackFilesList = packed_file_type {
layout.add_widget_5a(&warning_message, 0, 0, 1, 4);
} else {
warning_message.set_visible(false);
}
layout.add_widget_5a(&table_view_primary, 1, 0, 1, 1);
layout.add_widget_5a(&filter_base_widget, 3, 0, 1, 2);
// Action to make the delete button delete contents.
let smart_delete = QAction::from_q_object(&table_view_primary);
// Create the Contextual Menu for the TableView.
let context_menu = QMenu::from_q_widget(&table_view_primary);
let context_menu_add_rows = context_menu.add_action_q_string(&qtr("context_menu_add_rows"));
let context_menu_insert_rows = context_menu.add_action_q_string(&qtr("context_menu_insert_rows"));
let context_menu_delete_rows = context_menu.add_action_q_string(&qtr("context_menu_delete_rows"));
let context_menu_delete_rows_not_in_filter = context_menu.add_action_q_string(&qtr("context_menu_delete_filtered_out_rows"));
let context_menu_clone_submenu = QMenu::from_q_string_q_widget(&qtr("context_menu_clone_submenu"), &table_view_primary);
let context_menu_clone_and_insert = context_menu_clone_submenu.add_action_q_string(&qtr("context_menu_clone_and_insert"));
let context_menu_clone_and_append = context_menu_clone_submenu.add_action_q_string(&qtr("context_menu_clone_and_append"));
let context_menu_copy_submenu = QMenu::from_q_string_q_widget(&qtr("context_menu_copy_submenu"), &table_view_primary);
let context_menu_copy = context_menu_copy_submenu.add_action_q_string(&qtr("context_menu_copy"));
let context_menu_copy_as_lua_table = context_menu_copy_submenu.add_action_q_string(&qtr("context_menu_copy_as_lua_table"));
let context_menu_paste = context_menu.add_action_q_string(&qtr("context_menu_paste"));
let context_menu_paste_as_new_row = context_menu.add_action_q_string(&qtr("context_menu_paste_as_new_row"));
let context_menu_generate_ids = context_menu.add_action_q_string(&qtr("context_menu_generate_ids"));
let context_menu_rewrite_selection = context_menu.add_action_q_string(&qtr("context_menu_rewrite_selection"));
let context_menu_invert_selection = context_menu.add_action_q_string(&qtr("context_menu_invert_selection"));
let context_menu_reset_selection = context_menu.add_action_q_string(&qtr("context_menu_reset_selection"));
let context_menu_resize_columns = context_menu.add_action_q_string(&qtr("context_menu_resize_columns"));
let context_menu_import_tsv = context_menu.add_action_q_string(&qtr("context_menu_import_tsv"));
let context_menu_export_tsv = context_menu.add_action_q_string(&qtr("context_menu_export_tsv"));
let context_menu_search = context_menu.add_action_q_string(&qtr("context_menu_search"));
let context_menu_sidebar = context_menu.add_action_q_string(&qtr("context_menu_sidebar"));
let context_menu_cascade_edition = context_menu.add_action_q_string(&qtr("context_menu_cascade_edition"));
let context_menu_undo = context_menu.add_action_q_string(&qtr("context_menu_undo"));
let context_menu_redo = context_menu.add_action_q_string(&qtr("context_menu_redo"));
let context_menu_go_to = QMenu::from_q_string_q_widget(&qtr("context_menu_go_to"), &table_view_primary);
let context_menu_go_to_definition = context_menu_go_to.add_action_q_string(&qtr("context_menu_go_to_definition"));
let mut context_menu_go_to_loc = vec![];
for (index, loc_column) in table_definition.get_localised_fields().iter().enumerate() {
let context_menu_go_to_loc_action = context_menu_go_to.add_action_q_string(&qtre("context_menu_go_to_loc", &[loc_column.get_name()]));
if index == 0 { context_menu_go_to.insert_separator(&context_menu_go_to_loc_action); }
context_menu_go_to_loc.push(context_menu_go_to_loc_action)
}
// Insert some separators to space the menu, and the paste submenu.
context_menu.insert_menu(&context_menu_paste, &context_menu_clone_submenu);
context_menu.insert_menu(&context_menu_paste, &context_menu_copy_submenu);
context_menu.insert_menu(&context_menu_paste, &context_menu_go_to);
context_menu.insert_separator(&context_menu_rewrite_selection);
context_menu.insert_separator(&context_menu_import_tsv);
context_menu.insert_separator(&context_menu_search);
context_menu.insert_separator(&context_menu_undo);
//--------------------------------------------------//
// Search Section.
//--------------------------------------------------//
//
let search_widget = QWidget::new_1a(parent);
let search_grid = create_grid_layout(search_widget.static_upcast());
let search_matches_label = QLabel::from_q_widget(&search_widget);
let search_search_label = QLabel::from_q_string_q_widget(&QString::from_std_str("Search Pattern:"), &search_widget);
let search_replace_label = QLabel::from_q_string_q_widget(&QString::from_std_str("Replace Pattern:"), &search_widget);
let search_search_line_edit = QLineEdit::from_q_widget(&search_widget);
let search_replace_line_edit = QLineEdit::from_q_widget(&search_widget);
let search_prev_match_button = QPushButton::from_q_string_q_widget(&QString::from_std_str("Prev. Match"), &search_widget);
let search_next_match_button = QPushButton::from_q_string_q_widget(&QString::from_std_str("Next Match"), &search_widget);
let search_search_button = QPushButton::from_q_string_q_widget(&QString::from_std_str("Search"), &search_widget);
let search_replace_current_button = QPushButton::from_q_string_q_widget(&QString::from_std_str("Replace Current"), &search_widget);
let search_replace_all_button = QPushButton::from_q_string_q_widget(&QString::from_std_str("Replace All"), &search_widget);
let search_close_button = QPushButton::from_q_string_q_widget(&QString::from_std_str("Close"), &search_widget);
let search_column_selector = QComboBox::new_1a(&search_widget);
let search_column_list = QStandardItemModel::new_1a(&search_column_selector);
let search_case_sensitive_button = QPushButton::from_q_string_q_widget(&QString::from_std_str("Case Sensitive"), &search_widget);
search_search_line_edit.set_placeholder_text(&QString::from_std_str("Type here what you want to search."));
search_replace_line_edit.set_placeholder_text(&QString::from_std_str("If you want to replace the searched text with something, type the replacement here."));
search_column_selector.set_model(&search_column_list);
search_column_selector.add_item_q_string(&QString::from_std_str("* (All Columns)"));
let fields = get_fields_sorted(&table_definition);
for column in &fields {
search_column_selector.add_item_q_string(&QString::from_std_str(&utils::clean_column_names(&column.get_name())));
}
search_case_sensitive_button.set_checkable(true);
search_prev_match_button.set_enabled(false);
search_next_match_button.set_enabled(false);
search_replace_current_button.set_enabled(false);
search_replace_all_button.set_enabled(false);
// Add all the widgets to the search grid.
search_grid.add_widget_5a(&search_search_label, 0, 0, 1, 1);
search_grid.add_widget_5a(&search_search_line_edit, 0, 1, 1, 1);
search_grid.add_widget_5a(&search_prev_match_button, 0, 2, 1, 1);
search_grid.add_widget_5a(&search_next_match_button, 0, 3, 1, 1);
search_grid.add_widget_5a(&search_replace_label, 1, 0, 1, 1);
search_grid.add_widget_5a(&search_replace_line_edit, 1, 1, 1, 3);
search_grid.add_widget_5a(&search_search_button, 0, 4, 1, 1);
search_grid.add_widget_5a(&search_replace_current_button, 1, 4, 1, 1);
search_grid.add_widget_5a(&search_replace_all_button, 2, 4, 1, 1);
search_grid.add_widget_5a(&search_close_button, 2, 0, 1, 1);
search_grid.add_widget_5a(&search_matches_label, 2, 1, 1, 1);
search_grid.add_widget_5a(&search_column_selector, 2, 2, 1, 1);
search_grid.add_widget_5a(&search_case_sensitive_button, 2, 3, 1, 1);
layout.add_widget_5a(&search_widget, 2, 0, 1, 2);
layout.set_column_stretch(0, 10);
search_widget.hide();
//--------------------------------------------------//
// Freeze/Hide Section.
//--------------------------------------------------//
// Create the search and hide/show/freeze widgets.
let sidebar_scroll_area = QScrollArea::new_1a(parent);
let sidebar_widget = QWidget::new_1a(&sidebar_scroll_area);
let sidebar_grid = create_grid_layout(sidebar_widget.static_upcast());
sidebar_scroll_area.set_widget(&sidebar_widget);
sidebar_scroll_area.set_widget_resizable(true);
sidebar_scroll_area.horizontal_scroll_bar().set_enabled(false);
sidebar_grid.set_contents_margins_4a(4, 0, 4, 4);
sidebar_grid.set_spacing(4);
let header_column = QLabel::from_q_string_q_widget(&qtr("header_column"), &sidebar_widget);
let header_hidden = QLabel::from_q_string_q_widget(&qtr("header_hidden"), &sidebar_widget);
let header_frozen = QLabel::from_q_string_q_widget(&qtr("header_frozen"), &sidebar_widget);
sidebar_grid.set_alignment_q_widget_q_flags_alignment_flag(&header_column, QFlags::from(AlignmentFlag::AlignHCenter));
sidebar_grid.set_alignment_q_widget_q_flags_alignment_flag(&header_hidden, QFlags::from(AlignmentFlag::AlignHCenter));
sidebar_grid.set_alignment_q_widget_q_flags_alignment_flag(&header_frozen, QFlags::from(AlignmentFlag::AlignHCenter));
sidebar_grid.add_widget_5a(&header_column, 0, 0, 1, 1);
sidebar_grid.add_widget_5a(&header_hidden, 0, 1, 1, 1);
sidebar_grid.add_widget_5a(&header_frozen, 0, 2, 1, 1);
let label_all = QLabel::from_q_string_q_widget(&qtr("all"), &sidebar_widget);
let sidebar_hide_checkboxes_all = QCheckBox::from_q_widget(&sidebar_widget);
let sidebar_freeze_checkboxes_all = QCheckBox::from_q_widget(&sidebar_widget);
sidebar_freeze_checkboxes_all.set_enabled(false);
sidebar_grid.set_alignment_q_widget_q_flags_alignment_flag(&sidebar_hide_checkboxes_all, QFlags::from(AlignmentFlag::AlignHCenter));
sidebar_grid.set_alignment_q_widget_q_flags_alignment_flag(&sidebar_freeze_checkboxes_all, QFlags::from(AlignmentFlag::AlignHCenter));
sidebar_grid.add_widget_5a(&label_all, 1, 0, 1, 1);
sidebar_grid.add_widget_5a(&sidebar_hide_checkboxes_all, 1, 1, 1, 1);
sidebar_grid.add_widget_5a(&sidebar_freeze_checkboxes_all, 1, 2, 1, 1);
let mut sidebar_hide_checkboxes = vec![];
let mut sidebar_freeze_checkboxes = vec![];
for (index, column) in fields.iter().enumerate() {
let column_name = QLabel::from_q_string_q_widget(&QString::from_std_str(&utils::clean_column_names(&column.get_name())), &sidebar_widget);
let hide_show_checkbox = QCheckBox::from_q_widget(&sidebar_widget);
let freeze_unfreeze_checkbox = QCheckBox::from_q_widget(&sidebar_widget);
freeze_unfreeze_checkbox.set_enabled(false);
sidebar_grid.set_alignment_q_widget_q_flags_alignment_flag(&hide_show_checkbox, QFlags::from(AlignmentFlag::AlignHCenter));
sidebar_grid.set_alignment_q_widget_q_flags_alignment_flag(&freeze_unfreeze_checkbox, QFlags::from(AlignmentFlag::AlignHCenter));
sidebar_grid.add_widget_5a(&column_name, (index + 2) as i32, 0, 1, 1);
sidebar_grid.add_widget_5a(&hide_show_checkbox, (index + 2) as i32, 1, 1, 1);
sidebar_grid.add_widget_5a(&freeze_unfreeze_checkbox, (index + 2) as i32, 2, 1, 1);
sidebar_hide_checkboxes.push(hide_show_checkbox);
sidebar_freeze_checkboxes.push(freeze_unfreeze_checkbox);
}
// Add all the stuff to the main grid and hide the search widget.
layout.add_widget_5a(&sidebar_scroll_area, 0, 4, 4, 1);
sidebar_scroll_area.hide();
sidebar_grid.set_row_stretch(999, 10);
let timer_delayed_updates = QTimer::new_1a(parent);
timer_delayed_updates.set_single_shot(true);
// Create the raw Struct and begin
let packed_file_table_view = Arc::new(TableView {
table_view_primary,
table_view_frozen,
table_filter,
table_model,
//table_enable_lookups_button: table_enable_lookups_button.into_ptr(),
filters: Arc::new(RwLock::new(vec![])),
filter_base_widget,
column_sort_state: Arc::new(RwLock::new((-1, 0))),
context_menu,
context_menu_add_rows,
context_menu_insert_rows,
context_menu_delete_rows,
context_menu_delete_rows_not_in_filter,
context_menu_clone_and_append,
context_menu_clone_and_insert,
context_menu_copy,
context_menu_copy_as_lua_table,
context_menu_paste,
context_menu_paste_as_new_row,
context_menu_invert_selection,
context_menu_reset_selection,
context_menu_rewrite_selection,
context_menu_generate_ids,
context_menu_undo,
context_menu_redo,
context_menu_import_tsv,
context_menu_export_tsv,
context_menu_resize_columns,
context_menu_sidebar,
context_menu_search,
context_menu_cascade_edition,
smart_delete,
context_menu_go_to,
context_menu_go_to_definition,
context_menu_go_to_loc,
search_search_line_edit,
search_replace_line_edit,
search_search_button,
search_replace_current_button,
search_replace_all_button,
search_close_button,
search_prev_match_button,
search_next_match_button,
search_matches_label,
search_column_selector,
search_case_sensitive_button,
search_data: Arc::new(RwLock::new(TableSearch::default())),
sidebar_hide_checkboxes,
sidebar_hide_checkboxes_all,
sidebar_freeze_checkboxes,
sidebar_freeze_checkboxes_all,
sidebar_scroll_area,
search_widget,
table_name,
table_uuid,
dependency_data: Arc::new(RwLock::new(dependency_data)),
table_definition: Arc::new(RwLock::new(table_definition)),
packed_file_path: packed_file_path.clone(),
packed_file_type: Arc::new(packed_file_type),
undo_lock,
save_lock,
undo_model,
history_undo: Arc::new(RwLock::new(vec![])),
history_redo: Arc::new(RwLock::new(vec![])),
timer_delayed_updates,
});
let packed_file_table_view_slots = TableViewSlots::new(
&packed_file_table_view,
app_ui,
pack_file_contents_ui,
global_search_ui,
diagnostics_ui,
packed_file_path.clone(),
);
// Build the first filter.
FilterView::new(&packed_file_table_view);
// Load the data to the Table. For some reason, if we do this after setting the titles of
// the columns, the titles will be reseted to 1, 2, 3,... so we do this here.
load_data(
&packed_file_table_view.get_mut_ptr_table_view_primary(),
&packed_file_table_view.get_mut_ptr_table_view_frozen(),
&packed_file_table_view.table_definition.read().unwrap(),
&packed_file_table_view.dependency_data,
&table_data
);
// Initialize the undo model.
update_undo_model(&packed_file_table_view.get_mut_ptr_table_model(), &packed_file_table_view.get_mut_ptr_undo_model());
// Build the columns. If we have a model from before, use it to paint our cells as they were last time we painted them.
let table_name = if let Some(ref path) = packed_file_path {
path.read().unwrap().get(1).cloned()
} else { None };
build_columns(
&packed_file_table_view.get_mut_ptr_table_view_primary(),
Some(&packed_file_table_view.get_mut_ptr_table_view_frozen()),
&packed_file_table_view.table_definition.read().unwrap(),
table_name.as_ref()
);
// Set the connections and return success.
connections::set_connections(&packed_file_table_view, &packed_file_table_view_slots);
shortcuts::set_shortcuts(&packed_file_table_view);
tips::set_tips(&packed_file_table_view);
Ok(packed_file_table_view)
}
/// Function to reload the data of the view without having to delete the view itself.
///
/// NOTE: This allows for a table to change it's definition on-the-fly, so be carefull with that!
pub unsafe fn reload_view(&self, data: TableType) {
let table_view_primary = &self.get_mut_ptr_table_view_primary();
let table_view_frozen = &self.get_mut_ptr_table_view_frozen();
let undo_model = &self.get_mut_ptr_undo_model();
let filter: QPtr<QSortFilterProxyModel> = table_view_primary.model().static_downcast();
let model: QPtr<QStandardItemModel> = filter.source_model().static_downcast();
// Update the stored definition.
let table_definition = match data {
TableType::DB(ref table) => table.get_definition(),
TableType::Loc(ref table) => table.get_definition(),
_ => unimplemented!(),
};
*self.table_definition.write().unwrap() = table_definition;
// Load the data to the Table. For some reason, if we do this after setting the titles of
// the columns, the titles will be reseted to 1, 2, 3,... so we do this here.
load_data(
&table_view_primary,
&table_view_frozen,
&self.get_ref_table_definition(),
&self.dependency_data,
&data
);
// Prepare the diagnostic pass.
self.start_delayed_updates_timer();
// Reset the undo model and the undo/redo history.
update_undo_model(&model, &undo_model);
self.history_undo.write().unwrap().clear();
self.history_redo.write().unwrap().clear();
let table_name = if let Some(path) = self.get_packed_file_path() {
path.get(1).cloned()
} else { None };
// Rebuild the column's stuff.
build_columns(
&table_view_primary,
Some(&table_view_frozen),
&self.get_ref_table_definition(),
table_name.as_ref()
);
// Rebuild the column list of the filter and search panels, just in case the definition changed.
// NOTE: We need to lock the signals for the column selector so it doesn't try to trigger in the middle of the rebuild, causing a deadlock.
for filter in self.get_ref_mut_filters().iter() {
let _filter_blocker = QSignalBlocker::from_q_object(filter.filter_column_selector.static_upcast::<QObject>());
filter.filter_column_selector.clear();
for column in self.table_definition.read().unwrap().get_fields_processed() {
let name = QString::from_std_str(&utils::clean_column_names(&column.get_name()));
filter.filter_column_selector.add_item_q_string(&name);
}
}
let search_column_selector = &self.search_column_selector;
search_column_selector.clear();
search_column_selector.add_item_q_string(&QString::from_std_str("* (All Columns)"));
for column in self.table_definition.read().unwrap().get_fields_processed() {
let name = QString::from_std_str(&utils::clean_column_names(&column.get_name()));
search_column_selector.add_item_q_string(&name);
}
// Reset this setting so the last column gets resized properly.
table_view_primary.horizontal_header().set_stretch_last_section(!SETTINGS.read().unwrap().settings_bool["extend_last_column_on_tables"]);
table_view_primary.horizontal_header().set_stretch_last_section(SETTINGS.read().unwrap().settings_bool["extend_last_column_on_tables"]);
}
/// This function returns a reference to the StandardItemModel widget.
pub unsafe fn get_mut_ptr_table_model(&self) -> QPtr<QStandardItemModel> {
self.table_model.static_upcast()
}
// This function returns a mutable reference to the `Enable Lookups` Pushbutton.
//pub fn get_mut_ptr_enable_lookups_button(&self) -> QPtr<QPushButton> {
// q_ptr_from_atomic(&self.table_enable_lookups_button)
//}
/// This function returns a pointer to the Primary TableView widget.
pub unsafe fn get_mut_ptr_table_view_primary(&self) -> QPtr<QTableView> {
self.table_view_primary.static_upcast()
}
/// This function returns a pointer to the Frozen TableView widget.
pub unsafe fn get_mut_ptr_table_view_frozen(&self) -> QPtr<QTableView> {
self.table_view_frozen.static_upcast()
}
pub unsafe fn get_mut_ptr_table_view_filter(&self) -> QPtr<QSortFilterProxyModel> {
self.table_filter.static_upcast()
}
/// This function returns a pointer to the filter's LineEdit widget.
pub unsafe fn get_mut_ptr_filter_base_widget(&self) -> QPtr<QWidget> {
self.filter_base_widget.static_upcast()
}
/// This function returns a pointer to the add rows action.
pub fn get_mut_ptr_context_menu_add_rows(&self) -> &QPtr<QAction> {
&self.context_menu_add_rows
}
/// This function returns a pointer to the insert rows action.
pub fn get_mut_ptr_context_menu_insert_rows(&self) -> &QPtr<QAction> {
&self.context_menu_insert_rows
}
/// This function returns a pointer to the delete rows action.
pub fn get_mut_ptr_context_menu_delete_rows(&self) -> &QPtr<QAction> {
&self.context_menu_delete_rows
}
/// This function returns a pointer to the delete rows not in filter action.
pub fn get_mut_ptr_context_menu_delete_rows_not_in_filter(&self) -> &QPtr<QAction> {
&self.context_menu_delete_rows_not_in_filter
}
/// This function returns a pointer to the clone_and_append action.
pub fn get_mut_ptr_context_menu_clone_and_append(&self) -> &QPtr<QAction> {
&self.context_menu_clone_and_append
}
/// This function returns a pointer to the clone_and_insert action.
pub fn get_mut_ptr_context_menu_clone_and_insert(&self) -> &QPtr<QAction> {
&self.context_menu_clone_and_insert
}
/// This function returns a pointer to the copy action.
pub fn get_mut_ptr_context_menu_copy(&self) -> &QPtr<QAction> {
&self.context_menu_copy
}
/// This function returns a pointer to the copy as lua table action.
pub fn get_mut_ptr_context_menu_copy_as_lua_table(&self) -> &QPtr<QAction> {
&self.context_menu_copy_as_lua_table
}
/// This function returns a pointer to the paste action.
pub fn get_mut_ptr_context_menu_paste(&self) -> &QPtr<QAction> {
&self.context_menu_paste
}
/// This function returns a pointer to the paste as new row action.
pub fn get_mut_ptr_context_menu_paste_as_new_row(&self) -> &QPtr<QAction> {
&self.context_menu_paste_as_new_row
}
/// This function returns a pointer to the invert selection action.
pub fn get_mut_ptr_context_menu_invert_selection(&self) -> &QPtr<QAction> {
&self.context_menu_invert_selection
}
/// This function returns a pointer to the reset selection action.
pub fn get_mut_ptr_context_menu_reset_selection(&self) -> &QPtr<QAction> {
&self.context_menu_reset_selection
}
/// This function returns a pointer to the rewrite selection action.
pub fn get_mut_ptr_context_menu_rewrite_selection(&self) -> &QPtr<QAction> {
&self.context_menu_rewrite_selection
}
/// This function returns a pointer to the fill ids action.
pub fn get_mut_ptr_context_menu_generate_ids(&self) -> &QPtr<QAction> {
&self.context_menu_generate_ids
}
/// This function returns a pointer to the undo action.
pub fn get_mut_ptr_context_menu_undo(&self) -> &QPtr<QAction> {
&self.context_menu_undo
}
/// This function returns a pointer to the redo action.
pub fn get_mut_ptr_context_menu_redo(&self) -> &QPtr<QAction> {
&self.context_menu_redo
}
/// This function returns a pointer to the import TSV action.
pub fn get_mut_ptr_context_menu_import_tsv(&self) -> &QPtr<QAction> {
&self.context_menu_import_tsv
}
/// This function returns a pointer to the export TSV action.
pub fn get_mut_ptr_context_menu_export_tsv(&self) -> &QPtr<QAction> {
&self.context_menu_export_tsv
}
/// This function returns a pointer to the smart delete action.
pub fn get_mut_ptr_smart_delete(&self) -> &QBox<QAction> {
&self.smart_delete
}
/// This function returns a pointer to the resize columns action.
pub fn get_mut_ptr_context_menu_resize_columns(&self) -> &QPtr<QAction> {
&self.context_menu_resize_columns
}
/// This function returns a pointer to the sidebar action.
pub fn get_mut_ptr_context_menu_sidebar(&self) -> &QPtr<QAction> {
&self.context_menu_sidebar
}
/// This function returns a pointer to the search action.
pub fn get_mut_ptr_context_menu_search(&self) -> &QPtr<QAction> {
&self.context_menu_search
}
/// This function returns a pointer to the cascade edition action.
pub fn ge | self) -> &QPtr<QAction> {
&self.context_menu_cascade_edition
}
/// This function returns a pointer to the go to definition action.
pub fn get_mut_ptr_context_menu_go_to_definition(&self) -> &QPtr<QAction> {
&self.context_menu_go_to_definition
}
/// This function returns a vector with the entire go to loc action list.
pub fn get_go_to_loc_actions(&self) -> &[QPtr<QAction>] {
&self.context_menu_go_to_loc
}
/// This function returns a vector with the entire hide/show checkbox list.
pub fn get_hide_show_checkboxes(&self) -> &[QBox<QCheckBox>] {
&self.sidebar_hide_checkboxes
}
/// This function returns the checkbox to hide them all.
pub fn get_hide_show_checkboxes_all(&self) -> &QBox<QCheckBox> {
&self.sidebar_hide_checkboxes_all
}
/// This function returns a vector with the entire freeze checkbox list.
pub fn get_freeze_checkboxes(&self) -> &[QBox<QCheckBox>] {
&self.sidebar_freeze_checkboxes
}
/// This function returns a the checkbox to freeze them all.
pub fn get_freeze_checkboxes_all(&self) -> &QBox<QCheckBox> {
&self.sidebar_freeze_checkboxes_all
}
/// This function returns a pointer to the search lineedit in the search panel.
pub fn get_mut_ptr_search_search_line_edit(&self) -> &QBox<QLineEdit> {
&self.search_search_line_edit
}
/// This function returns a pointer to the search button in the search panel.
pub fn get_mut_ptr_search_search_button(&self) -> &QBox<QPushButton> {
&self.search_search_button
}
/// This function returns a pointer to the prev match button in the search panel.
pub fn get_mut_ptr_search_prev_match_button(&self) -> &QBox<QPushButton> {
&self.search_prev_match_button
}
/// This function returns a pointer to the next_match button in the search panel.
pub fn get_mut_ptr_search_next_match_button(&self) -> &QBox<QPushButton> {
&self.search_next_match_button
}
/// This function returns a pointer to the replace current button in the search panel.
pub fn get_mut_ptr_search_replace_current_button(&self) -> &QBox<QPushButton> {
&self.search_replace_current_button
}
/// This function returns a pointer to the replace all button in the search panel.
pub fn get_mut_ptr_search_replace_all_button(&self) -> &QBox<QPushButton> {
&self.search_replace_all_button
}
/// This function returns a pointer to the close button in the search panel.
pub fn get_mut_ptr_search_close_button(&self) -> &QBox<QPushButton> {
&self.search_close_button
}
pub unsafe fn get_mut_ptr_undo_model(&self) -> QPtr<QStandardItemModel> {
self.undo_model.static_upcast()
}
/// This function returns a reference to this table's name.
pub fn get_ref_table_name(&self) -> &Option<String> {
&self.table_name
}
/// This function returns a reference to this table's uuid.
pub fn get_ref_table_uuid(&self) -> &Option<String> {
&self.table_uuid
}
/// This function returns a reference to the definition of this table.
pub fn get_ref_table_definition(&self) -> RwLockReadGuard<Definition> {
self.table_definition.read().unwrap()
}
pub fn get_ref_filters(&self) -> RwLockReadGuard<Vec<Arc<FilterView>>> {
self.filters.read().unwrap()
}
pub fn get_ref_mut_filters(&self) -> RwLockWriteGuard<Vec<Arc<FilterView>>> {
self.filters.write().unwrap()
}
/// This function allows you to set a new dependency data to an already created table.
pub fn set_dependency_data(&self, data: &BTreeMap<i32, DependencyData>) {
*self.dependency_data.write().unwrap() = data.clone();
}
/// This function returns the path of the PackedFile corresponding to this table, if exists.
pub fn get_packed_file_path(&self) -> Option<Vec<String>> {
match self.packed_file_path {
Some(ref path) => Some(path.read().unwrap().clone()),
None => None,
}
}
pub unsafe fn start_delayed_updates_timer(&self) {
self.timer_delayed_updates.set_interval(1500);
self.timer_delayed_updates.start_0a();
}
}
//----------------------------------------------------------------//
// Implementations of `TableOperation`.
//----------------------------------------------------------------//
/// Debug implementation of TableOperations, so we can at least guess what is in the history.
impl Debug for TableOperations {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Editing(data) => write!(f, "Cell/s edited, starting in row {}, column {}.", (data[0].0).0, (data[0].0).1),
Self::AddRows(data) => write!(f, "Removing row/s added in position/s {}.", data.iter().map(|x| format!("{}, ", x)).collect::<String>()),
Self::RemoveRows(data) => write!(f, "Re-adding row/s removed in {} batches.", data.len()),
Self::ImportTSV(_) => write!(f, "Imported TSV file."),
Self::Carolina(_) => write!(f, "Carolina, trátame bien, no te rías de mi, no me arranques la piel."),
}
}
}
/// CLone implementation for TableOperations.
///
/// NOTE: CAROLINA'S CLONE IS NOT IMPLEMENTED. It'll crash if you try to clone it.
impl Clone for TableOperations {
fn clone(&self) -> Self {
match self {
Self::Editing(items) => Self::Editing(items.iter().map(|(x, y)| (*x, atomic_from_ptr(ptr_from_atomic(y)))).collect()),
Self::AddRows(rows) => Self::AddRows(rows.to_vec()),
Self::RemoveRows(rows) => Self::RemoveRows(rows.iter()
.map(|(x, y)| (*x, y.iter()
.map(|y| y.iter()
.map(|z| atomic_from_ptr(ptr_from_atomic(z)))
.collect()
).collect()
)).collect()),
_ => unimplemented!()
}
}
}
//----------------------------------------------------------------//
// Implementations of `TableSearch`.
//----------------------------------------------------------------//
/// Default implementation for TableSearch.
impl Default for TableSearch {
fn default() -> Self {
Self {
pattern: unsafe { QString::new().into_ptr() },
replace: unsafe { QString::new().into_ptr() },
regex: false,
case_sensitive: false,
column: None,
matches: vec![],
current_item: None,
}
}
}
/// Implementation of `TableSearch`.
impl TableSearch {
/// This function returns the list of matches present in the model.
fn get_matches_in_model(&self) -> Vec<Ptr<QModelIndex>> {
self.matches.iter().map(|x| x.0).collect()
}
/// This function returns the list of matches visible to the user with the current filter.
fn get_matches_in_filter(&self) -> Vec<Ptr<QModelIndex>> {
self.matches.iter().filter_map(|x| x.1).collect()
}
/// This function returns the list of matches present in the model that are visible to the user with the current filter.
fn get_visible_matches_in_model(&self) -> Vec<Ptr<QModelIndex>> {
self.matches.iter().filter(|x| x.1.is_some()).map(|x| x.0).collect()
}
/// This function takes care of searching data whithin a column, and adding the matches to the matches list.
unsafe fn find_in_column(
&mut self,
model: Ptr<QStandardItemModel>,
filter: Ptr<QSortFilterProxyModel>,
definition: &Definition,
flags: QFlags<MatchFlag>,
column: i32
) {
// First, check the column type. Boolean columns need special logic, as they cannot be matched by string.
let is_bool = definition.get_fields_processed()[column as usize].get_ref_field_type() == &FieldType::Boolean;
let matches_unprocessed = if is_bool {
match parse_str_as_bool(&self.pattern.to_std_string()) {
Ok(boolean) => {
let check_state = if boolean { CheckState::Checked } else { CheckState::Unchecked };
let items = QListOfQStandardItem::new();
for row in 0..model.row_count_0a() {
let item = model.item_2a(row, column);
if item.check_state() == check_state {
items.append_q_standard_item(&item.as_mut_raw_ptr());
}
}
items
}
// If this fails, ignore the entire column.
Err(_) => return,
}
}
else {
model.find_items_3a(self.pattern.as_ref().unwrap(), flags, column)
};
for index in 0..matches_unprocessed.count_0a() {
let model_index = matches_unprocessed.value_1a(index).index();
let filter_model_index = filter.map_from_source(&model_index);
self.matches.push((
model_index.into_ptr(),
if filter_model_index.is_valid() { Some(filter_model_index.into_ptr()) } else { None }
));
}
}
/// This function takes care of updating the UI to reflect changes in the table search.
pub unsafe fn update_search_ui(parent: &TableView, update_type: TableSearchUpdate) {
let table_search = &mut parent.search_data.write().unwrap();
let matches_in_filter = table_search.get_matches_in_filter();
let matches_in_model = table_search.get_matches_in_model();
match update_type {
TableSearchUpdate::Search => {
if table_search.pattern.is_empty() {
parent.search_matches_label.set_text(&QString::new());
parent.search_prev_match_button.set_enabled(false);
parent.search_next_match_button.set_enabled(false);
parent.search_replace_current_button.set_enabled(false);
parent.search_replace_all_button.set_enabled(false);
}
// If no matches have been found, report it.
else if table_search.matches.is_empty() {
table_search.current_item = None;
parent.search_matches_label.set_text(&QString::from_std_str("No matches found."));
parent.search_prev_match_button.set_enabled(false);
parent.search_next_match_button.set_enabled(false);
parent.search_replace_current_button.set_enabled(false);
parent.search_replace_all_button.set_enabled(false);
}
// Otherwise, if no matches have been found in the current filter, but they have been in the model...
else if matches_in_filter.is_empty() {
table_search.current_item = None;
parent.search_matches_label.set_text(&QString::from_std_str(&format!("{} in current filter ({} in total)", matches_in_filter.len(), matches_in_model.len())));
parent.search_prev_match_button.set_enabled(false);
parent.search_next_match_button.set_enabled(false);
parent.search_replace_current_button.set_enabled(false);
parent.search_replace_all_button.set_enabled(false);
}
// Otherwise, matches have been found both, in the model and in the filter.
else {
table_search.current_item = Some(0);
parent.search_matches_label.set_text(&QString::from_std_str(&format!("1 of {} in current filter ({} in total)", matches_in_filter.len(), matches_in_model.len())));
parent.search_prev_match_button.set_enabled(false);
parent.search_replace_current_button.set_enabled(true);
parent.search_replace_all_button.set_enabled(true);
if matches_in_filter.len() > 1 {
parent.search_next_match_button.set_enabled(true);
}
else {
parent.search_next_match_button.set_enabled(false);
}
parent.table_view_primary.selection_model().select_q_model_index_q_flags_selection_flag(
matches_in_filter[0].as_ref().unwrap(),
QFlags::from(SelectionFlag::ClearAndSelect)
);
}
}
TableSearchUpdate::PrevMatch => {
let matches_in_model = table_search.get_matches_in_model();
let matches_in_filter = table_search.get_matches_in_filter();
if let Some(ref mut pos) = table_search.current_item {
// If we are in an invalid result, return. If it's the first one, disable the button and return.
if *pos > 0 {
*pos -= 1;
if *pos == 0 { parent.search_prev_match_button.set_enabled(false); }
else { parent.search_prev_match_button.set_enabled(true); }
if *pos as usize >= matches_in_filter.len() - 1 { parent.search_next_match_button.set_enabled(false); }
else { parent.search_next_match_button.set_enabled(true); }
parent.table_view_primary.selection_model().select_q_model_index_q_flags_selection_flag(
matches_in_filter[*pos as usize].as_ref().unwrap(),
QFlags::from(SelectionFlag::ClearAndSelect)
);
parent.search_matches_label.set_text(&QString::from_std_str(&format!("{} of {} in current filter ({} in total)", *pos + 1, matches_in_filter.len(), matches_in_model.len())));
}
}
}
TableSearchUpdate::NextMatch => {
let matches_in_model = table_search.get_matches_in_model();
let matches_in_filter = table_search.get_matches_in_filter();
if let Some(ref mut pos) = table_search.current_item {
// If we are in an invalid result, return. If it's the last one, disable the button and return.
if *pos as usize >= matches_in_filter.len() - 1 {
parent.search_next_match_button.set_enabled(false);
}
else {
*pos += 1;
if *pos == 0 { parent.search_prev_match_button.set_enabled(false); }
else { parent.search_prev_match_button.set_enabled(true); }
if *pos as usize >= matches_in_filter.len() - 1 { parent.search_next_match_button.set_enabled(false); }
else { parent.search_next_match_button.set_enabled(true); }
parent.table_view_primary.selection_model().select_q_model_index_q_flags_selection_flag(
matches_in_filter[*pos as usize].as_ref().unwrap(),
QFlags::from(SelectionFlag::ClearAndSelect)
);
parent.search_matches_label.set_text(&QString::from_std_str(&format!("{} of {} in current filter ({} in total)", *pos + 1, matches_in_filter.len(), matches_in_model.len())));
}
}
}
TableSearchUpdate::Update => {
if table_search.pattern.is_empty() {
parent.search_matches_label.set_text(&QString::new());
parent.search_prev_match_button.set_enabled(false);
parent.search_next_match_button.set_enabled(false);
parent.search_replace_current_button.set_enabled(false);
parent.search_replace_all_button.set_enabled(false);
}
// If no matches have been found, report it.
else if table_search.matches.is_empty() {
table_search.current_item = None;
parent.search_matches_label.set_text(&QString::from_std_str("No matches found."));
parent.search_prev_match_button.set_enabled(false);
parent.search_next_match_button.set_enabled(false);
parent.search_replace_current_button.set_enabled(false);
parent.search_replace_all_button.set_enabled(false);
}
// Otherwise, if no matches have been found in the current filter, but they have been in the model...
else if matches_in_filter.is_empty() {
table_search.current_item = None;
parent.search_matches_label.set_text(&QString::from_std_str(&format!("{} in current filter ({} in total)", matches_in_filter.len(), matches_in_model.len())));
parent.search_prev_match_button.set_enabled(false);
parent.search_next_match_button.set_enabled(false);
parent.search_replace_current_button.set_enabled(false);
parent.search_replace_all_button.set_enabled(false);
}
// Otherwise, matches have been found both, in the model and in the filter. Which means we have to recalculate
// our position, and then behave more or less like a normal search.
else {
table_search.current_item = match table_search.current_item {
Some(pos) => if (pos as usize) < matches_in_filter.len() { Some(pos) } else { Some(0) }
None => Some(0)
};
parent.search_matches_label.set_text(&QString::from_std_str(&format!("{} of {} in current filter ({} in total)", table_search.current_item.unwrap() + 1, matches_in_filter.len(), matches_in_model.len())));
if table_search.current_item.unwrap() == 0 {
parent.search_prev_match_button.set_enabled(false);
}
else {
parent.search_prev_match_button.set_enabled(true);
}
if matches_in_filter.len() > 1 && (table_search.current_item.unwrap() as usize) < matches_in_filter.len() - 1 {
parent.search_next_match_button.set_enabled(true);
}
else {
parent.search_next_match_button.set_enabled(false);
}
parent.search_replace_current_button.set_enabled(true);
parent.search_replace_all_button.set_enabled(true);
}
}
}
}
/// This function takes care of updating the search data whenever a change that can alter the results happens.
pub unsafe fn update_search(parent: &TableView) {
{
let table_search = &mut parent.search_data.write().unwrap();
table_search.matches.clear();
let mut flags = if table_search.regex {
QFlags::from(MatchFlag::MatchRegExp)
} else {
QFlags::from(MatchFlag::MatchContains)
};
if table_search.case_sensitive {
flags = flags | QFlags::from(MatchFlag::MatchCaseSensitive);
}
let columns_to_search = match table_search.column {
Some(column) => vec![column],
None => (0..parent.get_ref_table_definition().get_fields_processed().len()).map(|x| x as i32).collect::<Vec<i32>>(),
};
for column in &columns_to_search {
table_search.find_in_column(parent.table_model.as_ptr(), parent.table_filter.as_ptr(), &parent.get_ref_table_definition(), flags, *column);
}
}
Self::update_search_ui(parent, TableSearchUpdate::Update);
}
/// This function takes care of searching the patter we provided in the TableView.
pub unsafe fn search(parent: &TableView) {
{
let table_search = &mut parent.search_data.write().unwrap();
table_search.matches.clear();
table_search.current_item = None;
table_search.pattern = parent.search_search_line_edit.text().into_ptr();
//table_search.regex = parent.search_search_line_edit.is_checked();
table_search.case_sensitive = parent.search_case_sensitive_button.is_checked();
table_search.column = {
let column = parent.search_column_selector.current_text().to_std_string().replace(' ', "_").to_lowercase();
if column == "*_(all_columns)" { None }
else { Some(parent.get_ref_table_definition().get_fields_processed().iter().position(|x| x.get_name() == column).unwrap() as i32) }
};
let mut flags = if table_search.regex {
QFlags::from(MatchFlag::MatchRegExp)
} else {
QFlags::from(MatchFlag::MatchContains)
};
if table_search.case_sensitive {
flags = flags | QFlags::from(MatchFlag::MatchCaseSensitive);
}
let columns_to_search = match table_search.column {
Some(column) => vec![column],
None => (0..parent.get_ref_table_definition().get_fields_processed().len()).map(|x| x as i32).collect::<Vec<i32>>(),
};
for column in &columns_to_search {
table_search.find_in_column(parent.table_model.as_ptr(), parent.table_filter.as_ptr(), &parent.get_ref_table_definition(), flags, *column);
}
}
Self::update_search_ui(parent, TableSearchUpdate::Search);
}
/// This function takes care of moving the selection to the previous match on the matches list.
pub unsafe fn prev_match(parent: &TableView) {
Self::update_search_ui(parent, TableSearchUpdate::PrevMatch);
}
/// This function takes care of moving the selection to the next match on the matches list.
pub unsafe fn next_match(parent: &TableView) {
Self::update_search_ui(parent, TableSearchUpdate::NextMatch);
}
/// This function takes care of replacing the current match with the provided replacing text.
pub unsafe fn replace_current(parent: &TableView) {
// NOTE: WE CANNOT HAVE THE SEARCH DATA LOCK UNTIL AFTER WE DO THE REPLACE. That's why there are a lot of read here.
let text_source = parent.search_data.read().unwrap().pattern.to_std_string();
if !text_source.is_empty() {
// Get the replace data here, as we probably don't have it updated.
parent.search_data.write().unwrap().replace = parent.search_replace_line_edit.text().into_ptr();
let text_replace = parent.search_data.read().unwrap().replace.to_std_string();
if text_source == text_replace { return }
// And if we got a valid position.
let item;
let replaced_text;
if let Some(ref position) = parent.search_data.read().unwrap().current_item {
// Here is save to lock, as the lock will be drop before doing the replace.
let table_search = &mut parent.search_data.read().unwrap();
// Get the list of all valid ModelIndex for the current filter and the current position.
let matches_in_model_and_filter = table_search.get_visible_matches_in_model();
let model_index = matches_in_model_and_filter[*position as usize];
// If the position is still valid (not required, but just in case)...
if model_index.is_valid() {
item = parent.table_model.item_from_index(model_index.as_ref().unwrap());
if parent.get_ref_table_definition().get_fields_processed()[model_index.column() as usize].get_ref_field_type() == &FieldType::Boolean {
replaced_text = text_replace;
}
else {
let text = item.text().to_std_string();
replaced_text = text.replace(&text_source, &text_replace);
}
// We need to do an extra check to ensure the new text can be in the field.
match parent.get_ref_table_definition().get_fields_processed()[model_index.column() as usize].get_ref_field_type() {
FieldType::Boolean => if parse_str_as_bool(&replaced_text).is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
FieldType::F32 => if replaced_text.parse::<f32>().is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
FieldType::I16 => if replaced_text.parse::<i16>().is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
FieldType::I32 => if replaced_text.parse::<i32>().is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
FieldType::I64 => if replaced_text.parse::<i64>().is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
_ => {}
}
} else { return }
} else { return }
// At this point, we trigger editions. Which mean, here ALL LOCKS SHOULD HAVE BEEN ALREADY DROP.
match parent.get_ref_table_definition().get_fields_processed()[item.column() as usize].get_ref_field_type() {
FieldType::Boolean => item.set_check_state(if parse_str_as_bool(&replaced_text).unwrap() { CheckState::Checked } else { CheckState::Unchecked }),
FieldType::F32 => item.set_data_2a(&QVariant::from_float(replaced_text.parse::<f32>().unwrap()), 2),
FieldType::I16 => item.set_data_2a(&QVariant::from_int(replaced_text.parse::<i16>().unwrap().into()), 2),
FieldType::I32 => item.set_data_2a(&QVariant::from_int(replaced_text.parse::<i32>().unwrap()), 2),
FieldType::I64 => item.set_data_2a(&QVariant::from_i64(replaced_text.parse::<i64>().unwrap()), 2),
_ => item.set_text(&QString::from_std_str(&replaced_text)),
}
// At this point, the edition has been done. We're free to lock again. If we still have matches, select the next match, if any, or the first one.
let table_search = &mut parent.search_data.read().unwrap();
if let Some(pos) = table_search.current_item {
let matches_in_filter = table_search.get_matches_in_filter();
parent.table_view_primary.selection_model().select_q_model_index_q_flags_selection_flag(
matches_in_filter[pos as usize].as_ref().unwrap(),
QFlags::from(SelectionFlag::ClearAndSelect)
);
}
}
}
/// This function takes care of replacing all the instances of a match with the provided replacing text.
pub unsafe fn replace_all(parent: &TableView) {
// NOTE: WE CANNOT HAVE THE SEARCH DATA LOCK UNTIL AFTER WE DO THE REPLACE. That's why there are a lot of read here.
let text_source = parent.search_data.read().unwrap().pattern.to_std_string();
if !text_source.is_empty() {
// Get the replace data here, as we probably don't have it updated.
parent.search_data.write().unwrap().replace = parent.search_replace_line_edit.text().into_ptr();
let text_replace = parent.search_data.read().unwrap().replace.to_std_string();
if text_source == text_replace { return }
let mut positions_and_texts: Vec<(Ptr<QModelIndex>, String)> = vec![];
{
// Here is save to lock, as the lock will be drop before doing the replace.
let table_search = &mut parent.search_data.read().unwrap();
// Get the list of all valid ModelIndex for the current filter and the current position.
let matches_in_model_and_filter = table_search.get_visible_matches_in_model();
for model_index in &matches_in_model_and_filter {
// If the position is still valid (not required, but just in case)...
if model_index.is_valid() {
let item = parent.table_model.item_from_index(model_index.as_ref().unwrap());
let original_text = match parent.get_ref_table_definition().get_fields_processed()[model_index.column() as usize].get_ref_field_type() {
FieldType::Boolean => item.data_0a().to_bool().to_string(),
FieldType::F32 => item.data_0a().to_float_0a().to_string(),
FieldType::I16 => item.data_0a().to_int_0a().to_string(),
FieldType::I32 => item.data_0a().to_int_0a().to_string(),
FieldType::I64 => item.data_0a().to_long_long_0a().to_string(),
_ => item.text().to_std_string(),
};
let replaced_text = if parent.get_ref_table_definition().get_fields_processed()[model_index.column() as usize].get_ref_field_type() == &FieldType::Boolean {
text_replace.to_owned()
}
else {
let text = item.text().to_std_string();
text.replace(&text_source, &text_replace)
};
// If no replacement has been done, skip it.
if original_text == replaced_text {
continue;
}
// We need to do an extra check to ensure the new text can be in the field.
match parent.get_ref_table_definition().get_fields_processed()[model_index.column() as usize].get_ref_field_type() {
FieldType::Boolean => if parse_str_as_bool(&replaced_text).is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
FieldType::F32 => if replaced_text.parse::<f32>().is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
FieldType::I16 => if replaced_text.parse::<i16>().is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
FieldType::I32 => if replaced_text.parse::<i32>().is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
FieldType::I64 => if replaced_text.parse::<i64>().is_err() { return show_dialog(&parent.table_view_primary, ErrorKind::DBTableReplaceInvalidData, false) }
_ => {}
}
positions_and_texts.push((*model_index, replaced_text));
} else { return }
}
}
// At this point, we trigger editions. Which mean, here ALL LOCKS SHOULD HAVE BEEN ALREADY DROP.
for (model_index, replaced_text) in &positions_and_texts {
let item = parent.table_model.item_from_index(model_index.as_ref().unwrap());
match parent.get_ref_table_definition().get_fields_processed()[item.column() as usize].get_ref_field_type() {
FieldType::Boolean => item.set_check_state(if parse_str_as_bool(&replaced_text).unwrap() { CheckState::Checked } else { CheckState::Unchecked }),
FieldType::F32 => item.set_data_2a(&QVariant::from_float(replaced_text.parse::<f32>().unwrap()), 2),
FieldType::I16 => item.set_data_2a(&QVariant::from_int(replaced_text.parse::<i16>().unwrap().into()), 2),
FieldType::I32 => item.set_data_2a(&QVariant::from_int(replaced_text.parse::<i32>().unwrap()), 2),
FieldType::I64 => item.set_data_2a(&QVariant::from_i64(replaced_text.parse::<i64>().unwrap()), 2),
_ => item.set_text(&QString::from_std_str(&replaced_text)),
}
}
// At this point, the edition has been done. We're free to lock again. As this is a full replace,
// we have to fix the undo history to compensate the mass-editing and turn it into a single action.
if !positions_and_texts.is_empty() {
{
let mut history_undo = parent.history_undo.write().unwrap();
let mut history_redo = parent.history_redo.write().unwrap();
let len = history_undo.len();
let mut edits_data = vec![];
{
let mut edits = history_undo.drain((len - positions_and_texts.len())..);
for edit in &mut edits {
if let TableOperations::Editing(mut edit) = edit {
edits_data.append(&mut edit);
}
}
}
history_undo.push(TableOperations::Editing(edits_data));
history_redo.clear();
}
update_undo_model(&parent.get_mut_ptr_table_model(), &parent.get_mut_ptr_undo_model());
}
}
}
}
impl FilterView {
pub unsafe fn new(view: &Arc<TableView>) {
let parent = view.get_mut_ptr_filter_base_widget();
// Create the filter's widgets.
let filter_widget = QWidget::new_1a(&parent);
let filter_grid = create_grid_layout(filter_widget.static_upcast());
filter_grid.set_column_stretch(0, 99);
filter_grid.set_column_stretch(3, 0);
filter_grid.set_column_stretch(4, 0);
let filter_line_edit = QLineEdit::from_q_widget(&parent);
let filter_column_selector = QComboBox::new_1a(&parent);
let filter_case_sensitive_button = QPushButton::from_q_string_q_widget(&qtr("table_filter_case_sensitive"), &parent);
let filter_column_list = QStandardItemModel::new_1a(&filter_column_selector);
let filter_add = QPushButton::from_q_string_q_widget(&QString::from_std_str("+"), &parent);
let filter_remove = QPushButton::from_q_string_q_widget(&QString::from_std_str("-"), &parent);
filter_column_selector.set_model(&filter_column_list);
let fields = get_fields_sorted(&view.get_ref_table_definition());
for field in &fields {
let name = clean_column_names(&field.get_name());
filter_column_selector.add_item_q_string(&QString::from_std_str(&name));
}
filter_line_edit.set_placeholder_text(&qtr("packedfile_filter"));
filter_line_edit.set_clear_button_enabled(true);
filter_case_sensitive_button.set_checkable(true);
// Add everything to the grid.
filter_grid.add_widget_5a(&filter_line_edit, 0, 0, 1, 1);
filter_grid.add_widget_5a(&filter_case_sensitive_button, 0, 1, 1, 1);
filter_grid.add_widget_5a(&filter_column_selector, 0, 2, 1, 1);
filter_grid.add_widget_5a(&filter_add, 0, 3, 1, 1);
filter_grid.add_widget_5a(&filter_remove, 0, 4, 1, 1);
let parent_grid: QPtr<QGridLayout> = parent.layout().static_downcast();
parent_grid.add_widget_5a(&filter_widget, view.get_ref_filters().len() as i32 + 3, 0, 1, 2);
let filter = Arc::new(Self {
filter_widget,
filter_line_edit,
filter_case_sensitive_button,
filter_column_selector,
filter_add,
filter_remove,
});
let slots = FilterViewSlots::new(&filter, &view);
connections::set_connections_filter(&filter, &slots);
view.get_ref_mut_filters().push(filter);
}
}
| t_mut_ptr_context_menu_cascade_edition(& |
test2.py | from engine import *
chingyatsikpingwu = []
chingyatsikpingwu.append(SimpleTile(2, 'Man'))
chingyatsikpingwu.append(SimpleTile(3, 'Man'))
chingyatsikpingwu.append(SimpleTile(4, 'Man'))
chingyatsikpingwu.append(SimpleTile(1, 'Man'))
chingyatsikpingwu.append(SimpleTile(2, 'Man'))
chingyatsikpingwu.append(SimpleTile(3, 'Man'))
chingyatsikpingwu.append(SimpleTile(4, 'Man'))
chingyatsikpingwu.append(SimpleTile(5, 'Man'))
chingyatsikpingwu.append(SimpleTile(6, 'Man'))
chingyatsikpingwu.append(SimpleTile(2, 'Man')) | chingyatsikpingwu.append(SimpleTile(9, 'Man'))
supcharmyiu = []
supcharmyiu.append(SimpleTile(1, 'Man'))
supcharmyiu.append(SimpleTile(1, 'Bamboo'))
supcharmyiu.append(SimpleTile(1, 'Circle'))
supcharmyiu.append(SimpleTile(9, 'Man'))
supcharmyiu.append(SimpleTile(9, 'Bamboo'))
supcharmyiu.append(SimpleTile(9, 'Circle'))
supcharmyiu.append(HonorTile.from_str('g'))
supcharmyiu.append(HonorTile.from_str('r'))
supcharmyiu.append(HonorTile.from_str('wh'))
supcharmyiu.append(HonorTile.from_str('e'))
supcharmyiu.append(HonorTile.from_str('s'))
supcharmyiu.append(HonorTile.from_str('we'))
supcharmyiu.append(HonorTile.from_str('n'))
supcharmyiu.append(HonorTile.from_str('n'))
#print(supcharmyiu)
asetoftiles = FanCalculator()
asetoftiles.tiles = chingyatsikpingwu
print(asetoftiles.tiles)
print()
print(asetoftiles.all_com())
eatable, legit_hands = asetoftiles.legitimate_hands()
if eatable:
print('It is a legitimate hand and there is(are) {} possible hand(s)!\n'.format(len(legit_hands)))
for legit_hand in legit_hands:
fan, reasons = asetoftiles.handtype_fan_calculator(legit_hand)
print('Total {} Fan\n'.format(fan))
print("The reasons are:")
for reason in reasons:
print(reason)
else:
print('There is no legitimate hand!') | chingyatsikpingwu.append(SimpleTile(3, 'Man'))
chingyatsikpingwu.append(SimpleTile(4, 'Man'))
chingyatsikpingwu.append(SimpleTile(9, 'Man')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.