file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
_configuration.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential class
(Configuration): """Configuration for ResourcePrivateLinkClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID of the target subscription. :type subscription_id: str """ def __init__( self, credential: "TokenCredential", subscription_id: str, **kwargs: Any ) -> None: super(ResourcePrivateLinkClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential self.subscription_id = subscription_id self.api_version = "2020-05-01" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-resource/{}'.format(VERSION)) self._configure(**kwargs) def _configure( self, **kwargs # type: Any ): # type: (...) -> None self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
ResourcePrivateLinkClientConfiguration
resolvers.js
const Resolvers = { Query: { aproject(_, args) { return AProject.find({ where: args }); }, }, }; export default Resolvers;
import { AProject } from './connectors';
http_redirect.py
from lona.html import Strong, Div, H2, P from lona.view import LonaView class HTTPRedirectView(LonaView): def handle_request(self, request):
html = Div( H2('Redirect'), P('You will be HTTP redirected in ', s, ' seconds'), ) for i in [3, 2, 1]: s.set_text(str(i)) self.show(html) self.sleep(1) return { 'http_redirect': '/', }
s = Strong()
posting.js
import React from "react"; import { Link, graphql } from "gatsby"; import Img from "gatsby-image"; import Layout from "../components/NavLayout/index"; export const query = graphql` query PostingTemplate($id: Int!) { strapiPosting(strapiId: { eq: $id }) { title description media { childImageSharp { fluid(maxWidth: 960) { ...GatsbyImageSharpFluid }
`; const ArticleTemplate = ({ data }) => ( <Layout> <h1>{data.strapiPosting.title}</h1> <Img fluid={data.strapiPosting.media.childImageSharp.fluid} /> <p>{data.strapiPosting.description}</p> </Layout> ); export default ArticleTemplate;
} } } }
epics.ts
import { Injectable } from '@angular/core' import { LoginEpics } from './epics/login.epic' @Injectable() export class Epics { constructor( private loginEpics: LoginEpics ) {} public createEpics() {
epics = [ ...this.loginEpics.createEpics(), ...epics ] return epics } }
let epics: any[] = []
utils.go
package main import ( "encoding/json" "io/ioutil" ) func saveClientConfig(c ClientConfig) (err error)
func loadClientConfig() (c ClientConfig, err error) { var b []byte if b, err = ioutil.ReadFile(CLIENT_CONFIG_FILE); err != nil { return } err = json.Unmarshal(b, &c) return }
{ var b []byte if b, err = json.Marshal(c); err != nil { return } return ioutil.WriteFile(CLIENT_CONFIG_FILE, b, 0644) }
tail.go
// Copyright © 2017 Aidan Steele <[email protected]> // // 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 cmd
"github.com/aws/aws-sdk-go/service/sts" "github.com/glassechidna/stackit/cmd/honey" "github.com/glassechidna/stackit/pkg/stackit" "github.com/spf13/cobra" "github.com/spf13/viper" ) var tailCmd = &cobra.Command{ Use: "tail", Short: "Tail output of stack change in progress", Run: func(cmd *cobra.Command, args []string) { region := viper.GetString("region") profile := viper.GetString("profile") stackName := viper.GetString("stack-name") printer := stackit.NewTailPrinter(cmd.OutOrStderr()) sess := awsSession(profile, region) sit := stackit.NewStackit(cloudformation.New(sess), sts.New(sess)) ctx, end := honey.RootContext() defer end() stack, _ := sit.Describe(ctx, stackName) if stack == nil || stackit.IsTerminalStatus(*stack.StackStatus) { return } _, err := sit.PollStackEvents(ctx, *stack.StackId, "", func(event stackit.TailStackEvent) { printer.PrintTailEvent(event) }) if err != nil { panic(err) } }, } func init() { RootCmd.AddCommand(tailCmd) }
import ( "github.com/aws/aws-sdk-go/service/cloudformation"
lazy.rs
use std::collections::HashMap; use std::fmt; use std::sync; use liquid_compiler; use liquid_compiler::Language; use liquid_error::Result; use liquid_interpreter; use liquid_interpreter::PartialStore; use liquid_interpreter::Renderable; use super::PartialCompiler; use super::PartialSource; /// An lazily-caching compiler for `PartialSource`. /// /// This would be useful in cases where: /// - Most partial-templates aren't used /// - Of the used partial-templates, they are generally used many times. /// /// Note: partial-compilation error reporting is deferred to render-time so content can still be /// generated even when the content is in an intermediate-state. #[derive(Debug)] pub struct LazyCompiler<S: PartialSource> { source: S, } impl<S> LazyCompiler<S> where S: PartialSource, { /// Create an on-demand compiler for `PartialSource`. pub fn new(source: S) -> Self { LazyCompiler { source } } } impl<S> LazyCompiler<S> where S: PartialSource + Default, { /// Create an empty compiler for `PartialSource`. pub fn empty() -> Self { Default::default() } } impl<S> Default for LazyCompiler<S> where S: PartialSource + Default, { fn default() -> Self { Self { source: Default::default(), } } } impl<S> ::std::ops::Deref for LazyCompiler<S> where S: PartialSource, { type Target = S; fn deref(&self) -> &S { &self.source } } impl<S> ::std::ops::DerefMut for LazyCompiler<S> where S: PartialSource, { fn deref_mut(&mut self) -> &mut S { &mut self.source } } impl<S> PartialCompiler for LazyCompiler<S> where S: PartialSource + Send + Sync + 'static, { fn compile(self, language: sync::Arc<Language>) -> Result<Box<dyn PartialStore + Send + Sync>> { let store = LazyStore { language: language, source: self.source, cache: sync::Mutex::new(Default::default()), }; Ok(Box::new(store)) } fn source(&self) -> &dyn PartialSource { &self.source } } struct LazyStore<S: PartialSource> { language: sync::Arc<Language>, source: S, cache: sync::Mutex<HashMap<String, Result<sync::Arc<dyn liquid_interpreter::Renderable>>>>, } impl<S> LazyStore<S> where S: PartialSource, { fn try_get_or_create(&self, name: &str) -> Option<sync::Arc<dyn Renderable>> { let cache = self.cache.lock().expect("not to be poisoned and reused"); if let Some(result) = cache.get(name) { result.as_ref().ok().cloned() } else { let s = self.source.try_get(name)?; let s = s.as_ref(); let template = liquid_compiler::parse(s, &self.language) .map(liquid_interpreter::Template::new) .map(sync::Arc::new) .ok()?; Some(template) } } fn get_or_create(&self, name: &str) -> Result<sync::Arc<dyn Renderable>> { let cache = self.cache.lock().expect("not to be poisoned and reused"); if let Some(result) = cache.get(name) { result.clone() } else { let s = self.source.get(name)?;
Ok(template) } } } impl<S> PartialStore for LazyStore<S> where S: PartialSource, { fn contains(&self, name: &str) -> bool { self.source.contains(name) } fn names(&self) -> Vec<&str> { self.source.names() } fn try_get(&self, name: &str) -> Option<sync::Arc<dyn Renderable>> { self.try_get_or_create(name) } fn get(&self, name: &str) -> Result<sync::Arc<dyn Renderable>> { self.get_or_create(name) } } impl<S> fmt::Debug for LazyStore<S> where S: PartialSource, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.source.fmt(f) } }
let s = s.as_ref(); let template = liquid_compiler::parse(s, &self.language) .map(liquid_interpreter::Template::new) .map(sync::Arc::new)?;
required.rs
use crate::{ compilation::{context::CompilationContext, JSONSchema}, error::{error, no_error, CompilationError, ErrorIterator, ValidationError}, keywords::CompilationResult, validator::Validate, }; use serde_json::{Map, Value}; pub(crate) struct RequiredValidator { required: Vec<String>, } impl RequiredValidator { #[inline] pub(crate) fn compile(schema: &Value) -> CompilationResult { match schema { Value::Array(items) => { let mut required = Vec::with_capacity(items.len()); for item in items { match item { Value::String(string) => required.push(string.clone()), _ => return Err(CompilationError::SchemaError), } } Ok(Box::new(RequiredValidator { required })) } _ => Err(CompilationError::SchemaError), } } } impl Validate for RequiredValidator { fn is_valid(&self, _: &JSONSchema, instance: &Value) -> bool { if let Value::Object(item) = instance { self.required .iter() .all(|property_name| item.contains_key(property_name)) } else { true } } fn validate<'a>(&self, _: &'a JSONSchema, instance: &'a Value) -> ErrorIterator<'a> { if let Value::Object(item) = instance { for property_name in &self.required { if !item.contains_key(property_name) { return error(ValidationError::required(instance, property_name.clone())); } } } no_error() } } impl ToString for RequiredValidator { fn
(&self) -> String { format!("required: [{}]", self.required.join(", ")) } } #[inline] pub(crate) fn compile( _: &Map<String, Value>, schema: &Value, _: &CompilationContext, ) -> Option<CompilationResult> { Some(RequiredValidator::compile(schema)) }
to_string
POST_graphql_mutation_putSchoolExperiences.e2e.test.ts
/* eslint-disable @typescript-eslint/no-unused-expressions */ // node_modules import 'reflect-metadata'; import { FastifyInstance, FastifyLoggerInstance } from 'fastify'; import { IncomingMessage, Server, ServerResponse } from 'http'; import { expect } from 'chai'; import * as _ from 'lodash'; // libraries import { e2eTestEnv } from '../../../../../lib/environment'; import { mongo } from '../../../../../../src/lib/mongo'; import * as jwt from '../../../../../../src/lib/jwt'; // models import { SchoolExperience } from '../../../../../../src/models/resume'; // testees import { bootstrap } from '../../../../../../src/app'; let app: FastifyInstance<Server, IncomingMessage, ServerResponse, FastifyLoggerInstance>; // data import { loadSchoolExperiencesData, unloadSchoolExperiencesData } from '../../../../../data/loaders/resume'; import { readStaticSchoolExperienceData } from '../../../../../data/static/resume/SchoolExperience'; import { readStaticUserData } from '../../../../../data/static/user/User'; import { loadUsersData } from '../../../../../data/loaders/user'; // file constants/functions let staticSchoolExperienceData: any | any[]; let staticUserData: any | any[]; let cachedSchoolExperienceData: any | any[]; let cachedUserData: any | any[]; async function customStartUp() { try { // return explicitly return; } catch (err) { // throw error explicitly throw err; } } async function
() { try { // return explicitly return; } catch (err) { // throw error explicitly throw err; } } // tests describe('api/resume/resolvers/SchoolExperience.resolver - POST /graphql mutation putSchoolExperiences - e2e tests', () => { before(async () => { try { // load out environment await e2eTestEnv.init(); // initialize asynchronous tasks, connectiones, etc. here await Promise.all([mongo.init(require('../../../../../../src/configs/mongo').default)]); // initialize synchronous tasks, connectiones, etc. here []; // create and store app app = await bootstrap(); // cusom start up functionality await customStartUp(); // return explicitly return; } catch (err) { // throw explicitly throw err; } }); describe('{ mutation putSchoolExperiences }', () => { context('({ schoolExperiences: [3 do not exist...] })', () => { context('static data', () => { beforeEach(async () => { try { // create the faked data staticSchoolExperienceData = await readStaticSchoolExperienceData(3); staticUserData = await readStaticUserData(3); // load data into datasources cachedSchoolExperienceData = staticSchoolExperienceData.slice(); cachedUserData = await loadUsersData({ users: staticUserData, }); // return explicitly } catch (err) { // throw explicitly throw err; } }); afterEach(async () => { try { // unload data from datasources await unloadSchoolExperiencesData({ schoolExperiences: cachedSchoolExperienceData, }); // reset data holders staticUserData = undefined; cachedUserData = undefined; // return explicitly } catch (err) { // throw explicitly throw err; } }); it('- should replace 1...N school experience instances that exist correlated by schoolExperienceId or insert/create 1...N school experience instances that do not exist correlated by schoolExperienceId', async () => { try { ///////////////////////// //////// setup ////////// ///////////////////////// // none const EXPECTED_TYPE_OF_STRING = 'string'; const EXPECTED_ARRAY_CLASS_INSTANCE = Array; const EXPECTED_SCHOOL_EXPERIENCES = cachedSchoolExperienceData.slice(); const EXPECTED_SCHOOL_EXPERIENCES_LENGTH = EXPECTED_SCHOOL_EXPERIENCES.length; ///////////////////////// //////// test /////////// ///////////////////////// // query mongo to get info const blainerrichardsonCloudDb = await mongo.getConnection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_DB_NAME); let foundItems = await blainerrichardsonCloudDb .collection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_SCHOOL_EXPERIENCES_COLLECTION_NAME) .find({ schoolExperienceId: { $in: cachedSchoolExperienceData.map((item: any) => item.schoolExperienceId) } }) .toArray(); // run assertions expect(foundItems !== undefined).to.be.true; expect(foundItems instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(foundItems.length === 0).to.be.true; // run testee const httpRequest: any = { method: 'POST', url: '/graphql', headers: { 'content-type': 'application/json', authorization: jwt.sign({ userId: cachedUserData[0].userId }), }, payload: { query: `mutation putSchoolExperiences($data: PutSchoolExperiencesInputType!) { putSchoolExperiences(data: $data) { schoolExperiences { schoolExperienceId, schoolName } } }`, variables: { data: { schoolExperiences: cachedSchoolExperienceData, }, }, }, }; const httResponse = await app.inject(httpRequest); // run assertions expect(httResponse !== undefined).to.be.true; expect(httResponse.statusCode !== undefined).to.be.true; expect(httResponse.statusCode === 200).to.be.true; expect(httResponse.body !== undefined).to.be.true; expect(typeof httResponse.body === EXPECTED_TYPE_OF_STRING).to.be.true; // parse JSON body const parsedBody = JSON.parse(httResponse.body); // validate results expect(parsedBody !== undefined).to.be.true; expect(parsedBody.data !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences.length === EXPECTED_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const schoolExperience of parsedBody.data.putSchoolExperiences.schoolExperiences) { expect( EXPECTED_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === schoolExperience.schoolExperienceId, ) !== undefined, ).to.be.true; } // query mongo to get info foundItems = await blainerrichardsonCloudDb .collection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_SCHOOL_EXPERIENCES_COLLECTION_NAME) .find({ schoolExperienceId: { $in: cachedSchoolExperienceData.map((item: any) => item.schoolExperienceId) } }) .toArray(); // run assertions expect(foundItems !== undefined).to.be.true; expect(foundItems !== undefined).to.be.true; expect(foundItems instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(foundItems.length === EXPECTED_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const foundItem of foundItems) { expect( EXPECTED_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) !== undefined, ).to.be.true; } // return explicitly return; } catch (err) { // throw explicitly throw err; } }); }); }); context('({ schoolExperiences: [2 do not exist..., 1 does exist...] })', () => { context('static data', () => { beforeEach(async () => { try { // create the faked data staticSchoolExperienceData = await readStaticSchoolExperienceData(3); staticUserData = await readStaticUserData(3); // load data into datasources cachedSchoolExperienceData = _.flatten([ await loadSchoolExperiencesData({ schoolExperiences: [staticSchoolExperienceData.slice()[0]], }), staticSchoolExperienceData.slice(1), ]); cachedUserData = await loadUsersData({ users: staticUserData, }); // return explicitly } catch (err) { // throw explicitly throw err; } }); afterEach(async () => { try { // unload data from datasources await unloadSchoolExperiencesData({ schoolExperiences: cachedSchoolExperienceData, }); // reset data holders staticUserData = undefined; cachedUserData = undefined; // return explicitly } catch (err) { // throw explicitly throw err; } }); it('- should replace 1...N school experience instances that exist correlated by schoolExperienceId or insert/create 1...N school experience instances that do not exist correlated by schoolExperienceId', async () => { try { ///////////////////////// //////// setup ////////// ///////////////////////// // update first element to make sure // that things are updated if they // already exist in the backend datastores const updatedSchoolExperienceData = _.flatten([ _.assign({}, cachedSchoolExperienceData.slice()[0], { workName: 'UPDATE' }), cachedSchoolExperienceData.slice(1), ]); // none const EXPECTED_ARRAY_CLASS_INSTANCE = Array; const EXPECTED_TYPE_OF_STRING = 'string'; const EXPECTED_EXISTING_SCHOOL_EXPERIENCES = [cachedSchoolExperienceData.slice()[0]]; const EXPECTED_EXISTING_SCHOOL_EXPERIENCES_LENGTH = EXPECTED_EXISTING_SCHOOL_EXPERIENCES.length; const EXPECTED_NONEXISTING_SCHOOL_EXPERIENCES = cachedSchoolExperienceData.slice(1); const EXPECTED_SCHOOL_EXPERIENCES = updatedSchoolExperienceData.slice(); const EXPECTED_SCHOOL_EXPERIENCES_LENGTH = EXPECTED_SCHOOL_EXPERIENCES.length; ///////////////////////// //////// test /////////// ///////////////////////// // query mongo to get info const blainerrichardsonCloudDb = await mongo.getConnection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_DB_NAME); let foundItems = await blainerrichardsonCloudDb .collection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_SCHOOL_EXPERIENCES_COLLECTION_NAME) .find({ schoolExperienceId: { $in: cachedSchoolExperienceData.map((item: any) => item.schoolExperienceId) } }) .toArray(); // run assertions expect(foundItems !== undefined).to.be.true; expect(foundItems !== undefined).to.be.true; expect(foundItems instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(foundItems.length === EXPECTED_EXISTING_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const foundItem of foundItems) { expect( EXPECTED_EXISTING_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) !== undefined, ).to.be.true; } for (const foundItem of foundItems) { expect( EXPECTED_NONEXISTING_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) === undefined, ).to.be.true; } // run testee const httpRequest: any = { method: 'POST', url: '/graphql', headers: { 'content-type': 'application/json', authorization: jwt.sign({ userId: cachedUserData[0].userId }), }, payload: { query: `mutation putSchoolExperiences($data: PutSchoolExperiencesInputType!) { putSchoolExperiences(data: $data) { schoolExperiences { schoolExperienceId, schoolName } } }`, variables: { data: { schoolExperiences: cachedSchoolExperienceData.map((item: any) => _.omitBy(_.assign({}, item, { _id: undefined }), _.isUndefined), ), }, }, }, }; const httResponse = await app.inject(httpRequest); // run assertions expect(httResponse !== undefined).to.be.true; expect(httResponse.statusCode !== undefined).to.be.true; expect(httResponse.statusCode === 200).to.be.true; expect(httResponse.body !== undefined).to.be.true; expect(typeof httResponse.body === EXPECTED_TYPE_OF_STRING).to.be.true; // parse JSON body const parsedBody = JSON.parse(httResponse.body); // validate results expect(parsedBody !== undefined).to.be.true; expect(parsedBody.data !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences.length === EXPECTED_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const schoolExperience of parsedBody.data.putSchoolExperiences.schoolExperiences) { expect( EXPECTED_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === schoolExperience.schoolExperienceId, ) !== undefined, ).to.be.true; } // query mongo to get info foundItems = await blainerrichardsonCloudDb .collection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_SCHOOL_EXPERIENCES_COLLECTION_NAME) .find({ schoolExperienceId: { $in: cachedSchoolExperienceData.map((item: any) => item.schoolExperienceId) } }) .toArray(); // run assertions expect(foundItems !== undefined).to.be.true; expect(foundItems !== undefined).to.be.true; expect(foundItems instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(foundItems.length === EXPECTED_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const foundItem of foundItems) { expect( EXPECTED_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) !== undefined, ).to.be.true; } // return explicitly return; } catch (err) { // throw explicitly throw err; } }); }); }); context('({ schoolExperiences: [1 does not exist..., 2 do exist...] })', () => { context('static data', () => { beforeEach(async () => { try { // create the faked data staticSchoolExperienceData = await readStaticSchoolExperienceData(3); staticUserData = await readStaticUserData(3); // load data into datasources cachedSchoolExperienceData = _.flatten([ await loadSchoolExperiencesData({ schoolExperiences: staticSchoolExperienceData.slice(0, 2), }), staticSchoolExperienceData.slice(-1), ]); cachedUserData = await loadUsersData({ users: staticUserData, }); // return explicitly } catch (err) { // throw explicitly throw err; } }); afterEach(async () => { try { // unload data from datasources await unloadSchoolExperiencesData({ schoolExperiences: cachedSchoolExperienceData, }); // reset data holders staticUserData = undefined; cachedUserData = undefined; // return explicitly } catch (err) { // throw explicitly throw err; } }); it('- should replace 1...N school experience instances that exist correlated by schoolExperienceId or insert/create 1...N school experience instances that do not exist correlated by schoolExperienceId', async () => { try { ///////////////////////// //////// setup ////////// ///////////////////////// // update first element to make sure // that things are updated if they // already exist in the backend datastores const updatedSchoolExperienceData = _.flatten([ staticSchoolExperienceData .slice(0, 2) .map((item: any, itemIndex: number) => _.assign({}, item, { workName: `UPDATE ${itemIndex}` })), cachedSchoolExperienceData.slice(-1), ]); // none const EXPECTED_ARRAY_CLASS_INSTANCE = Array; const EXPECTED_TYPE_OF_STRING = 'string'; const EXPECTED_EXISTING_SCHOOL_EXPERIENCES = staticSchoolExperienceData.slice(0, 2); const EXPECTED_EXISTING_SCHOOL_EXPERIENCES_LENGTH = EXPECTED_EXISTING_SCHOOL_EXPERIENCES.length; const EXPECTED_NONEXISTING_SCHOOL_EXPERIENCES = cachedSchoolExperienceData.slice(-1); const EXPECTED_SCHOOL_EXPERIENCES = updatedSchoolExperienceData.slice(); const EXPECTED_SCHOOL_EXPERIENCES_LENGTH = EXPECTED_SCHOOL_EXPERIENCES.length; ///////////////////////// //////// test /////////// ///////////////////////// // query mongo to get info const blainerrichardsonCloudDb = await mongo.getConnection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_DB_NAME); let foundItems = await blainerrichardsonCloudDb .collection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_SCHOOL_EXPERIENCES_COLLECTION_NAME) .find({ schoolExperienceId: { $in: cachedSchoolExperienceData.map((item: any) => item.schoolExperienceId) } }) .toArray(); // run assertions expect(foundItems !== undefined).to.be.true; expect(foundItems !== undefined).to.be.true; expect(foundItems instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(foundItems.length === EXPECTED_EXISTING_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const foundItem of foundItems) { expect( EXPECTED_EXISTING_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) !== undefined, ).to.be.true; } for (const foundItem of foundItems) { expect( EXPECTED_NONEXISTING_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) === undefined, ).to.be.true; } // run testee const httpRequest: any = { method: 'POST', url: '/graphql', headers: { 'content-type': 'application/json', authorization: jwt.sign({ userId: cachedUserData[0].userId }), }, payload: { query: `mutation putSchoolExperiences($data: PutSchoolExperiencesInputType!) { putSchoolExperiences(data: $data) { schoolExperiences { schoolExperienceId, schoolName } } }`, variables: { data: { schoolExperiences: cachedSchoolExperienceData.map((item: any) => _.omitBy(_.assign({}, item, { _id: undefined }), _.isUndefined), ), }, }, }, }; const httResponse = await app.inject(httpRequest); // run assertions expect(httResponse !== undefined).to.be.true; expect(httResponse.statusCode !== undefined).to.be.true; expect(httResponse.statusCode === 200).to.be.true; expect(httResponse.body !== undefined).to.be.true; expect(typeof httResponse.body === EXPECTED_TYPE_OF_STRING).to.be.true; // parse JSON body const parsedBody = JSON.parse(httResponse.body); // validate results expect(parsedBody !== undefined).to.be.true; expect(parsedBody.data !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences.length === EXPECTED_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const schoolExperience of parsedBody.data.putSchoolExperiences.schoolExperiences) { expect( EXPECTED_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === schoolExperience.schoolExperienceId, ) !== undefined, ).to.be.true; } // query mongo to get info foundItems = await blainerrichardsonCloudDb .collection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_SCHOOL_EXPERIENCES_COLLECTION_NAME) .find({ schoolExperienceId: { $in: cachedSchoolExperienceData.map((item: any) => item.schoolExperienceId) } }) .toArray(); // run assertions expect(foundItems !== undefined).to.be.true; expect(foundItems !== undefined).to.be.true; expect(foundItems instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(foundItems.length === EXPECTED_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const foundItem of foundItems) { expect( EXPECTED_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) !== undefined, ).to.be.true; } // return explicitly return; } catch (err) { // throw explicitly throw err; } }); }); }); context('({ schoolExperiences: [3 do exist...] })', () => { context('static data', () => { beforeEach(async () => { try { // create the faked data staticSchoolExperienceData = await readStaticSchoolExperienceData(3); staticUserData = await readStaticUserData(3); // load data into datasources cachedSchoolExperienceData = await loadSchoolExperiencesData({ schoolExperiences: staticSchoolExperienceData, }); cachedUserData = await loadUsersData({ users: staticUserData, }); // return explicitly } catch (err) { // throw explicitly throw err; } }); afterEach(async () => { try { // unload data from datasources await unloadSchoolExperiencesData({ schoolExperiences: cachedSchoolExperienceData, }); // reset data holders staticUserData = undefined; cachedUserData = undefined; // return explicitly } catch (err) { // throw explicitly throw err; } }); it('- should replace 1...N school experience instances that exist correlated by schoolExperienceId or insert/create 1...N school experience instances that do not exist correlated by schoolExperienceId', async () => { try { ///////////////////////// //////// setup ////////// ///////////////////////// // update first element to make sure // that things are updated if they // already exist in the backend datastores const updatedSchoolExperienceData = staticSchoolExperienceData .slice() .map((item: any, itemIndex: number) => _.assign({}, item, { workName: `UPDATE ${itemIndex}` })); // none const EXPECTED_ARRAY_CLASS_INSTANCE = Array; const EXPECTED_TYPE_OF_STRING = 'string'; const EXPECTED_EXISTING_SCHOOL_EXPERIENCES = staticSchoolExperienceData.slice(); const EXPECTED_EXISTING_SCHOOL_EXPERIENCES_LENGTH = EXPECTED_EXISTING_SCHOOL_EXPERIENCES.length; const EXPECTED_NONEXISTING_SCHOOL_EXPERIENCES: any[] = []; const EXPECTED_SCHOOL_EXPERIENCES = updatedSchoolExperienceData.slice(); const EXPECTED_SCHOOL_EXPERIENCES_LENGTH = EXPECTED_SCHOOL_EXPERIENCES.length; ///////////////////////// //////// test /////////// ///////////////////////// // query mongo to get info const blainerrichardsonCloudDb = await mongo.getConnection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_DB_NAME); let foundItems = await blainerrichardsonCloudDb .collection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_SCHOOL_EXPERIENCES_COLLECTION_NAME) .find({ schoolExperienceId: { $in: cachedSchoolExperienceData.map((item: any) => item.schoolExperienceId) } }) .toArray(); // run assertions expect(foundItems !== undefined).to.be.true; expect(foundItems !== undefined).to.be.true; expect(foundItems instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(foundItems.length === EXPECTED_EXISTING_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const foundItem of foundItems) { expect( EXPECTED_EXISTING_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) !== undefined, ).to.be.true; } for (const foundItem of foundItems) { expect( EXPECTED_NONEXISTING_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) === undefined, ).to.be.true; } // run testee const httpRequest: any = { method: 'POST', url: '/graphql', headers: { 'content-type': 'application/json', authorization: jwt.sign({ userId: cachedUserData[0].userId }), }, payload: { query: `mutation putSchoolExperiences($data: PutSchoolExperiencesInputType!) { putSchoolExperiences(data: $data) { schoolExperiences { schoolExperienceId, schoolName } } }`, variables: { data: { schoolExperiences: cachedSchoolExperienceData.map((item: any) => _.omitBy(_.assign({}, item, { _id: undefined }), _.isUndefined), ), }, }, }, }; const httResponse = await app.inject(httpRequest); // run assertions expect(httResponse !== undefined).to.be.true; expect(httResponse.statusCode !== undefined).to.be.true; expect(httResponse.statusCode === 200).to.be.true; expect(httResponse.body !== undefined).to.be.true; expect(typeof httResponse.body === EXPECTED_TYPE_OF_STRING).to.be.true; // parse JSON body const parsedBody = JSON.parse(httResponse.body); // validate results expect(parsedBody !== undefined).to.be.true; expect(parsedBody.data !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences !== null).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(parsedBody.data.putSchoolExperiences.schoolExperiences.length === EXPECTED_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const schoolExperience of parsedBody.data.putSchoolExperiences.schoolExperiences) { expect( EXPECTED_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === schoolExperience.schoolExperienceId, ) !== undefined, ).to.be.true; } // query mongo to get info foundItems = await blainerrichardsonCloudDb .collection(e2eTestEnv.MONGO_BLAINERRICARDSON_CLOUD_SCHOOL_EXPERIENCES_COLLECTION_NAME) .find({ schoolExperienceId: { $in: cachedSchoolExperienceData.map((item: any) => item.schoolExperienceId) } }) .toArray(); // run assertions expect(foundItems !== undefined).to.be.true; expect(foundItems !== undefined).to.be.true; expect(foundItems instanceof EXPECTED_ARRAY_CLASS_INSTANCE).to.be.true; expect(foundItems.length === EXPECTED_SCHOOL_EXPERIENCES_LENGTH).to.be.true; for (const foundItem of foundItems) { expect( EXPECTED_SCHOOL_EXPERIENCES.find( (expectedItem: any) => expectedItem.schoolExperienceId === foundItem.schoolExperienceId, ) !== undefined, ).to.be.true; } // return explicitly return; } catch (err) { // throw explicitly throw err; } }); }); }); }); after(async () => { try { // cusom start up functionality await customTearDown(); // return explicitly return; } catch (err) { // throw explicitly throw err; } }); });
customTearDown
dynamics.py
"""DEFINES THE INVERSEDYNAMICS SOLVER, A Solver for solving the joint based model of a dog.""" from scipy import optimize, signal from data.data_loader import C3DData, load_force_plate_data, ForcePlateData, SMALData, get_delay_between, DataSources, \ path_join from vis.utils import * from vis import visualisations from dynamics.footfall_detector import FootfallDetector from tqdm import tqdm # pure constants (no optimisation needed) g = 9.81 freq_forceplate = 100 # Hz foot_joint_labels = ["front left", "front right", "rear left", "rear right"] foot_joint_indices = [0, 9, 23, 20] # for set 2 3r3 class Model: """ID Model, with all parameters derived/optimised""" def __init__(self): # CONSTANTS self.paws = {} self.bone_density = 1950 # Estimate - needs refining! From paper: Development of a neuromusculoskeletal computer model in a chondrodystrophic dog. self.muscle_density = 1060 # From above # params to optimise self.bone_length_definitions = { "normal": lambda l: dict(inner_radius=0.01, outer_radius=0.05, displacement=0), "body": lambda l: dict(inner_radius=l / 20, outer_radius=l / 7, displacement=l / 4 - l / 20), } # Paw parameters. All scaled to be in standard form - exponent in separate dict. self.paw_params_normalised = { "L0_front": 6.9, # 6.9 # in .1mm "L0_rear": 6.9, # in .1mm "k_front": 3.42 * .18, # in kN/m "k_rear": 2.0 * .21, # in kN/m "c_front": 20, "c_rear": 20, "k_rear_prop": 0.85, # k = k_rear * m **.85 "frame_delay": 0 # Used for analysis of paw treadmill forces. Not used for normal ID solver } self.paw_exponents = { "L0_front": -4, "L0_rear": -4, "k_front": 3, "k_rear": 3, "c_front": 0, "c_rear": 0, "k_rear_prop": 0, "frame_delay": 0 } self.calc_paw_params() self.freq_par_data = 200 # weightings used in dynamics calculations self.equation_weighting = { "Inertial": 2, "Rotational": 2, "Leg spring": 0.5, "Paw spring": 1, } def calc_paw_params(self): """Calculates paw parameters (separate function for optimisation purposes)""" for param, val in self.paw_params_normalised.items(): self.paws[param] = val * 10 ** (self.paw_exponents[param]) def edit_paw_param(self, param, val): """Edit paw parameter (separate for optimisation purposes)""" self.paw_params_normalised[param] = val self.calc_paw_params() model = Model() def time_deriv(X, dt): """Finds the time derivative of a given series of data. Always treats the first dimension as time - works for any number of dimensions (n_frames, M, N, O, ...). For all except first and last val, calcs difference over 2 timesteps""" diff = np.zeros_like(X) diff[0] = X[1] - X[0] diff[1:-1] = (X[2:] - X[:-2]) / 2 diff[-1] = X[-1] - X[-2] return diff * 1 / dt def nth_time_deriv(X, dt, n=2):
def get_principal_axes(vector=Vector(1, 0, 0), cardinal=np.identity(3)): """Given a vector, devise a basis of principle axis with any two perpendicular vectors (for application of an axisymmetric object - cylinder) """ i, j, k = cardinal K = vector.unit() # Now find any two perp vectors to K if not K.is_parallel(i): I = K.cross(i).unit() J = K.cross(I).unit() else: I = K.cross(j).unit() J = K.cross(I).unit() return np.array([I, J, K]) def I_cylinder(density, length, radius): mass = density * np.pi * (radius ** 2) * length Ixx, Izz = (length ** 2) / 12 + (radius ** 2) / 4, radius ** 2 / 2 return mass * np.diag([Ixx, Ixx, Izz]) class DoubleCylinder: """An object comprised of a cylinder of given length between two end points, of radius inner_radius and density bone_density, and an outer cylinder that does NOT share the same central axis, of radius outer_radius, displaced by a distance <displacement> normally from the centerline. Cylinder is defined with the centerline vertical (z direction), and the displacement always in the normal closest to the z direction downwards. For InverseDynamics calculations, this object will have a start and end index, which correspond to the joint indices in which the end point data is held. """ def __init__(self, start, end, length, inner_radius, outer_radius, displacement, freq=50.0, name=""): self.name = name self.freq = freq # Frequency, in Hz self.start = start self.end = end self.length = length self.displacement = displacement if outer_radius is None: outer_radius = inner_radius self.inner_mass = model.bone_density * np.pi * inner_radius ** 2 * self.length self.outer_mass = model.muscle_density * np.pi * self.length * (outer_radius ** 2 - inner_radius ** 2) self.mass = self.inner_mass + self.outer_mass I_bone = I_cylinder(model.bone_density, length, inner_radius) I_muscle = I_cylinder(model.muscle_density, length, outer_radius) - I_cylinder(model.muscle_density, length, inner_radius) # By parallel axis theorem, add component of I due to outer radius being displaced from the centerline axis I_axis_displacement = np.zeros((3, 3)) I_axis_displacement[0, 0] = self.outer_mass * displacement ** 2 self.I = I_bone + I_muscle + I_axis_displacement # Inertia tensor in a reference frame in which the bone is lengthwise facing upwards def get_kinematics(self, data): """Given a numpy array of time, data, of shape (n_frames, 2, 3), giving the position data of both ends of the cylinder over time, compute the kinematics of the cylinder""" X = self.X = np.array(data) # positions V = self.V = time_deriv(X, 1 / self.freq) # velocities A = self.A = time_deriv(V, 1 / self.freq) # accelerations self.XG = np.mean(X, axis=1) # average over X self.VG = np.mean(V, axis=1) # average over V self.AG = np.mean(A, axis=1) # average over A # Rotational R = self.R = [Vector(*x[1]) - Vector(*x[0]) for x in X] # Vector from bone start to end in each frame local_axes = [get_principal_axes(r) for r in R] # Get principal axes for each frame # theta_g = (n_frame, 3) of angular rotation about i, j, k for each frame # angular rotation about each axis is defined as 0 for the next vector in the cycle # i.e. angular rotation about i = 0 for a vector parallel to j zero_angles = [[0, 1, 0], [0, 0, 1], [1, 0, 0]] # definition of 'zero angle' vector for i, j, k theta_g = [] # Compute theta_g in local axes first, where K is the unit vector for n_frame in range(len(X) - 1): local_ax = local_axes[n_frame] # representation as a a single rotation theta about an axis e (https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula) a = R[n_frame] # rotation from one frame... b = R[n_frame + 1] # ...to the next if np.array_equal(a, b): theta_g += [[0, 0, 0]] # If no rotation, return 0 else: axis = np.cross(a, b) / (np.linalg.norm(np.cross(a, b))) # unit vector of omega with np.errstate(invalid='raise'): try: alignment = np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) alignment = np.clip(alignment, a_min=-1, a_max=1) # clip between -1 and 1 to deal with rounding errors angle = np.arccos(alignment) # magnitude of theta except: print((np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))) raise ValueError("INVALID ANGLE", a, b) theta_g += [axis * angle] theta_g = np.array(theta_g) self.theta_g = signal.savgol_filter(theta_g, window_length=19, polyorder=2, axis=0) self.omega_g = time_deriv(self.theta_g, dt=1 / self.freq) self.alpha_g = time_deriv(self.omega_g, dt=1 / self.freq) # angular acceleration self.I_fixed = [la.T @ self.I @ la for la in local_axes] # compute I in fixed reference frame at each frame def get_dynamics(self): """Compute dynamics (F_net, Torque_net) at each frame""" self.F_net = [self.mass * a_g for a_g in self.AG] self.tau_net = [I_f @ alpha for (I_f, alpha) in zip(self.I_fixed, self.alpha_g)] class Body(DoubleCylinder): """A unique case of double cylinder, where the (multiple) joints connect at the cylindrical surface at either end. These joint attachments are defined by an angle from the i direction normal to the centerline at initialisation. Dynamics for the body then must be calculated using a separate set of equations. Define the body such that all joints bones go into it rather than out of it (i.e. all input forces are positive on the body) """ def __init__(self, start_joints, end_joints, all_joint_positions, **cylinder_kwaargs): """From the indices given by start_joints and end_joints, identify a cylinder shape that best fits these points on either side, and create that as the cylinder. """ self.start_joints = start_joints self.end_joints = end_joints start_pos = Vector(*np.mean(all_joint_positions[40, start_joints], axis=0)) end_pos = Vector(*np.mean(all_joint_positions[40, end_joints], axis=0)) length = start_pos > end_pos super().__init__(start=None, end=None, length=length, **model.bone_length_definitions["body"](length), **cylinder_kwaargs) def get_centre_of_gravity(self, start: 'Vector', end: 'Vector'): """Calculates the centre of gravity based on the displacement from the centerline.""" centreline_g = 0.5 * (start + end) # to find a normal that is closest to z, find N possible equispaced normals, and see which one has the greatest .k product normal = (start - end).find_normal() N = 20 # number of normals to consider all_normals = [normal.rotate_about((start - end).unit(), angle=(n * 2 * np.pi / N)) for n in range(N)] idx = np.argmax([v.dot(Vector(0, 0, -1)) for v in all_normals]) chosen_normal = all_normals[idx] # choose most downwards normal return centreline_g + self.displacement * chosen_normal def get_kinematics(self, data): """For body, data is of shape (n_frames, 2, 2, 3), where it is split by rear and front. So average across rear and front to get behaviour of centerline, and then run normal get_kinematics""" super().get_kinematics(np.mean(data, axis=2)) def weighted_bound_least_squares(A, b, weights=None, bounds=None, **kwargs): """Completes a least squares solve of the equation A x = b, to solve N unknowns from M equations where A is an M x N matrix, x is an N x 1 vector, and b is an M x 1 vector. Applies weightings to each row to favour certain datapoints. weights is an M x 1 vector. Applies bounds where bounds is an M x 2 array. each tuple in the array gives the LB and UB for the given equation""" if weights is None: weights = np.ones_like(b) # If no weight given, equal weight to all w = np.array(weights) weighted_A, weighted_b = np.array(A) * w[:, np.newaxis], np.array(b) * w # Apply weights to A, b try: solve = optimize.lsq_linear(weighted_A, weighted_b, bounds=list(zip(*bounds)), tol=1e-2) return solve["x"] except np.linalg.LinAlgError as e: out = f"SVD did not converge in Lin Least Sq. Printing params: {A}, {b}" raise ArithmeticError(out) class InverseDynamicsSolver: """Through scipy optimisation, Skeleton finds a set of force data that corresponds to the correct kinematic data. Takes a skeleton, and the relevant bones and joints, and solves the set of forces that correspond to correct kinematics.""" def __init__(self, joint_data, target_bones, body_joints, no_torque_joints=None, no_reaction_joints=None, foot_joints=None, leg_spring_joints=None, model=Model(), freq=50.0, name="output", is_mocap=True): for var in [foot_joints, leg_spring_joints, no_reaction_joints, no_torque_joints]: if var is None: var = [] self.name = name self.freq = freq self.n_frames, self.n_joints, _ = joint_data.shape self.model = model self.is_mocap = is_mocap # Preprocess joint data - basic smoothing if is_mocap: window_length = self.freq // 2 else: window_length = 0.75 * self.freq if window_length % 2 == 0: window_length -= 1 self.T = self.n_frames / self.freq self.smooth = lambda X, p=5: signal.savgol_filter(X, window_length=int(window_length), polyorder=p, axis=0) p = 5 if self.is_mocap else 2 self.unsmoothed_data = joint_data # save unsmoothed data for other uses self.joint_pos = self.smooth(joint_data, p=p) self.joint_vel = time_deriv(self.joint_pos, 1 / freq) self.joint_accel = time_deriv(self.smooth(self.joint_vel), 1 / freq) self.foot_joints = foot_joints self.body_joints = body_joints self.get_foot_joint_from_index = {} # Identify which foot from the index for fj in self.foot_joints: for bone, (j1, j2) in target_bones.items(): if fj in [j1, j2]: self.get_foot_joint_from_index[fj] = bone self.no_torque_joints = no_torque_joints self.no_reaction_joints = no_reaction_joints self.target_bones_dict = target_bones # for use in plotting self.target_bones = [] self.total_mass = 0 for bone, (joint1, joint2) in target_bones.items(): # Calculate length using the initial positions of jointA and B. # Smoothing functions can cause the issues for the first few frames, so take avg of later frames frames = [50, 51, 52, 53, 54, 55, 56] n_averaging = len(frames) length = 0 for frame in frames: posA = Vector(*self.joint_pos[frame, joint1]) posB = Vector(*self.joint_pos[frame, joint2]) if posA.length() == 0 or posB.length() == 0: n_averaging -= 1 else: length += posA > posB length = length / n_averaging # avg of all the frames data taken from if length == 0: print(f"Warning: Error in calculating length of '{bone}'") length = 0.01 b = DoubleCylinder(start=joint1, end=joint2, length=length, name=bone, freq=freq, **self.model.bone_length_definitions["normal"](length)) self.target_bones.append(b) # add bone to list self.total_mass += b.mass self.body = Body(*body_joints, self.joint_pos, freq=freq, name="body") self.body.get_kinematics( np.stack([self.joint_pos[:, body_joints[0]], self.joint_pos[:, body_joints[1]]], axis=1)) self.body.get_dynamics() self.total_mass += self.body.mass # Paw parameters m = self.total_mass paw_d = self.model.paws self.L0_paws = {"front": paw_d["L0_front"] * m, "rear": paw_d["L0_rear"] * m} self.k_paws = {"front": paw_d["k_front"] * m, "rear": paw_d["k_rear"] * m ** paw_d["k_rear_prop"]} self.c_paws = {"front": paw_d["c_front"] * m, "rear": paw_d["c_rear"] * m} # if self.model.equation_weighting['Paw spring'] > 0: self.set_paw_equilibrium() self.get_dynamics() self.leg_spring_joints = leg_spring_joints self.calc_leg_lengths() self.equation_weighting = model.equation_weighting def get_dynamics(self): """Gets dynamics of centre of mass of each bone & body""" for bone in self.target_bones: bone.get_kinematics(self.joint_pos[:, [bone.start, bone.end]]) bone.get_dynamics() body = self.body body.get_kinematics( np.stack([self.joint_pos[:, body.start_joints], self.joint_pos[:, body.end_joints]], axis=1)) body.get_dynamics() def calculate_forces(self, n_frame, report_equations=True): """ Sets up a system of linear equations governing the motion of the skeleton at a given frame. These equations are: - FREE JOINTS: The torques at free joints are zero. Free joints are joints only connected to one bone, on the end of the body eg the feet - INERTIA: On each bone, the sum of the two joint forces is equal to the mass * acceleration of the bone - ROTATION: On each bone, the net torque about the bone is equal to the I * alpha_g of the bone - BODY: The body is set up as a slightly different type of bone, in which it has several joints connected at either end, and its position is dictated by all of those joints. See the code for it below, it has its own set of inertial and rotational equations. This is set up as a least squares problem Ax = b, where A is a matrix of coefficients to multiply the unknowns by, x is the unknowns (in the form [F_1_x, F_1_y, F_1_z, F_2_x, ... T_1, T, ...] b is the result of the equations. A weighting is also applied to each row to weight the least squares problem (eg to priorities free joint equations) The problem also has bounds applied to it. For now, these bounds are simply that foot joint vertical reaction forces are non negative. Improvements: - Replace the current spinal system with a large non axisymmetric cylinder to represent the body - Add a sphere to represent the head """ # Consult report for explanation of system A = [] b = [] weights = [] # Collect weightings for each equation as they are added to the system equation_weighting = self.equation_weighting # Reasonable bounds for each force, and for each torque. Current limits set at 10 * weight for mass, 10 * mass at one metre for torque max_force = 3 * self.total_mass * g max_torque = 3 * self.total_mass * g # bounds can be adjusted further for specific joints (eg no downards reaction at the feet) bounds = [(-max_force, max_force)] * (3 * self.n_joints) + [(-max_torque, max_torque)] * (self.n_joints) def A_row(vals={}): """Returns a row of 0s length 4 * self.n_joints, with other vectors in any indices in vals. vals is a dict of index:vector""" row = [0.0] * 4 * self.n_joints for index, val in vals.items(): row[index] = val return row def add_blank_row(): A.append(A_row({})) b.append(0) weights.append(0) def add_n_blank_rows(n=1): for i in range(n): add_blank_row() null, unit, g_vec = Vector(0, 0, 0), Vector(1, 1, 1), Vector(0, 0, -g) n_joints = self.n_joints def get_index(joint, dimension=0, is_force=True): """Get correct index of D""" return (3 * n_joints * int(not is_force)) + ([1, 3][is_force] * joint) + dimension # dimension = 0 for x, 1 for y, 2 for z # First, add the equations to show that the torques in each of the foot joints are zero for no_torque_joint in self.no_torque_joints: # Set up the equation 1 * tau_{foot_joint} = 0 # BOUNDARY CONDITIONS ARE FIXED, RATHER THAN AN ADDITIONAL EQUATION. SO INCORPORATE THEM INTO BOUNDS bounds[get_index(no_torque_joint, is_force=False)] = (0, 1e-10) for no_reaction_joint in self.no_reaction_joints: # BC : no reactions for dim in [0, 1, 2]: bounds[get_index(no_reaction_joint, dimension=dim, is_force=True)] = (0, 1e-10) for foot_joint in self.foot_joints: ## If the feet are a certain amount off the ground for that foot, also assign the reaction forces to be zero bone_name = self.get_foot_joint_from_index[foot_joint] end = bone_name.split(" ")[1] # get 'front' or 'rear' L0 = self.L0_paws[end] # get stiffness from 'front' or 'rear' in bone name # L0 = self.paw_equilibrium_values[foot_joint] k_paw = self.k_paws[end] c_paw = self.c_paws[end] paw_disp = self.paw_disps[foot_joint][n_frame] paw_off_ground = self.joint_pos[n_frame, foot_joint, 2] >= L0 # BC: no reaction in foot off ground paw_off_ground = paw_disp == 0 if paw_off_ground: # BC: no reaction in foot off ground for dim in [0, 1, 2]: bounds[get_index(foot_joint, dimension=dim, is_force=True)] = (0, 1e-10) add_n_blank_rows(4) # for consistency of number of eqns else: # If paw near ground, add force due to spring height = self.unsmoothed_data[n_frame, foot_joint, 2] eps = L0 - height # min((L0 - height), L0/2) eps_dot = self.joint_vel[n_frame, foot_joint, 2] F_damp = 0 # c_paw * eps_dot if self.model.equation_weighting['Paw spring'] > 0: ## PAW SPRING MODEL eps = paw_disp F_spring = k_paw * eps + c_paw * eps_dot if foot_joint != 20: A.append(A_row({get_index(foot_joint, dimension=2, is_force=True): 1})) b.append(F_spring + F_damp) weights.append(equation_weighting["Paw spring"]) if self.model.equation_weighting['Leg spring'] > 0: ## LEG SPRING MODEL K = 3000 if end == "front" else 2000 for dim in [0, 1, 2]: # component = self.leg_vecs[foot_joint][n_frame][dim] F_spring = self.leg_disps[foot_joint][n_frame] * K # * component A.append(A_row({get_index(foot_joint, dimension=dim, is_force=True): 1})) b.append(F_spring + F_damp) weights.append(equation_weighting["Leg spring"]) # Set bounds for foot joints to only have positive vertical reactions bounds[get_index(foot_joint, dimension=2, is_force=True)] = (0, max_force) bounds[get_index(foot_joint, dimension=1, is_force=True)] = (0, 1e-10) # set Fy=0 for bone in self.target_bones: j_1, j_2 = bone.start, bone.end x_1, x_2 = bone.X[n_frame] # F_1 + F_2 + F_grav = F_net F_net = bone.F_net[n_frame] for dim in [0, 1, 2]: A.append(A_row({get_index(j_1, dim): 1, get_index(j_2, dim): - 1})) b.append((F_net - bone.mass * g_vec)[dim]) weights.append(equation_weighting["Inertial"]) tau_net = bone.tau_net[n_frame] x_g = bone.XG[n_frame] r_1, r_2 = (x_1 - x_g), (x_2 - x_g) # direction of each T is perpendicular to the bones that the joint is on adjacent_1_bone = [b for b in self.target_bones if b.end == j_1 and b != bone] if len(adjacent_1_bone) == 1: # if there is an adjacent bone adj_bone = adjacent_1_bone[0] T_1_dir = Vector(*r_1).cross((adj_bone.X[n_frame, 1] - adj_bone.XG[n_frame])).unit() if len(adjacent_1_bone) == 0 or np.isnan(T_1_dir).any(): # if no adjacent, or if above calc causes error T_1_dir = (0, 1, 0) # Improve later, for now say all torques about y axis adjacent_2_bone = [b for b in self.target_bones if b.start == j_2 and b != bone] if len(adjacent_2_bone) == 1: # if there is an adjacent bone adj_bone = adjacent_2_bone[0] T_2_dir = Vector(*r_2).cross((adj_bone.X[n_frame, 0] - adj_bone.XG[n_frame])).unit() if len(adjacent_2_bone) == 0 or np.isnan(T_2_dir).any(): # if no adjacent, or if above calc causes error T_2_dir = (0, 1, 0) # Improve later, for now say all torques about y axis for dim in [0, 1, 2]: # This loop essentially writes out the following equations into A and b for each dimension (x,y,z): # r1 x F1 + r2 x F2 + T1 + T2 = T_net # The cross product of r = (x,y,z) and F = (Fx, Fy, Fz) yields (Fz*y - Fy*z, ...) # Take the x component, x -> Fz*y - Fy*z # Notice that Fy is negative, and Fz is positive. This is always true, that, for the forces, one lower dimension than the current is positive, and one higher is negative (cyclical relations) # use this below # Get dim above and below, wrapping round for below x and above z dim_below = (dim - 1) % 3 dim_above = (dim + 1) % 3 coeff_dict = { get_index(j_1, dim): 0, # eg no effect of F_x in the x directional torque (not relevant statement, only here for readability) get_index(j_1, dim_above): - r_1[dim_below], # eg multiply - z by Fy in the x direction get_index(j_1, dim_below): r_1[dim_above], # eg multiply y by Fz in the x direction # Reversed polarity for joint 2 as the desired force is - F2 get_index(j_2, dim_above): r_2[dim_below], get_index(j_2, dim_below): - r_2[dim_above], # Add the torques on each joint get_index(j_1, is_force=False): T_1_dir[dim], get_index(j_2, is_force=False): -T_2_dir[dim] } A.append(A_row(coeff_dict)) b.append(tau_net[dim]) weights.append(equation_weighting["Rotational"]) ### SOLVE FORCES ON BODY. Note body defined so all joint forces/torques on it are positive body = self.body F_net = body.F_net[n_frame] # BODY INERTIAL FORCES for dim in [0, 1, 2]: A.append(A_row({get_index(j, dim): 1 for j in self.body.start_joints + self.body.end_joints})) b.append((F_net - body.mass * g_vec)[dim]) weights.append(equation_weighting["Inertial"]) # BODY ROTATIONAL FORCES - same as for bones x_g = body.XG[n_frame] tau_net = body.tau_net[n_frame] # Improve above later, for now say all torques about y axis T_dir = (0, 1, 0) for dim in [0, 1, 2]: coeff_dict = {} for joint in body.start_joints + body.end_joints: x_j = self.joint_pos[n_frame, joint] r_j = (x_j - x_g) # position vector to centre # Get dim above and below, wrapping round for below x and above z dim_below, dim_above = (dim - 1) % 3, (dim + 1) % 3 coeff_dict[get_index(joint, dim_above)] = -r_j[dim_below] # eg multiply - z by Fy in the x direction coeff_dict[get_index(joint, dim_below)] = r_j[dim_above] # eg multiply y by Fz in the x direction coeff_dict[get_index(joint, is_force=False)] = T_dir[dim] # Add pure torque of pin A.append(A_row(coeff_dict)) b.append(tau_net[dim]) weights.append(equation_weighting["Rotational"]) # print each line of the equations defined by A, b, with the final result # Only print variables with both non-zero values, and non-zero coefficients if report_equations: print(f"----Frame {n_frame}----") params = [] for joint in range(self.n_joints): for dim in "xyz": params.append(F"F_{joint}_{dim}") # Add forces by joint for joint in range(self.n_joints): params.append(F"T_{joint}") # Add torques by joint for n, (coeffs, result) in enumerate(zip(A, b)): s = [] for j, (coeff, param) in enumerate(zip(coeffs, params)): if coeff != 0: s.append(f"{round(coeff, 3)} * {param}") # b_actual = np.dot(A[n], D) # pct_error = abs(100 * (b_actual - result) / b_actual) if n <= 7: print(f"{' + '.join(s)} = {round(result, 3)}") # ({round(b_actual, 3)}) [{round(pct_error, 2)}%]") return A, b, weights, bounds def solve_forces(self, report_equations=False, end_frames_disregarded=5, prefix="", save=True): """Solves the forces at each frame for the system, collects them and saves them to .npy files. Note: Currently, due to smoothing, the first 5 and last 5 frames are disregarded""" self.get_dynamics() n_joints = self.n_joints if report_equations: print("Solving system...") print(f"Total mass {round(self.total_mass, 2)} kg.") # If dir doesn't exist, make it dir = path_join(DataSources.dynamics_data, self.name) if self.name not in os.listdir(DataSources.dynamics_data): os.mkdir(dir) forces, torques = [], [] f_shape, t_shape = (self.n_joints, 3), (self.n_joints,) # Add zeros either end due to not being able to calculate for the first or last 2 frames for i in range(end_frames_disregarded): forces.append(np.zeros(f_shape)) torques.append(np.zeros(t_shape)) calc_forces = [] calc_torques = [] progress = tqdm(total=self.n_frames - 2 * end_frames_disregarded) for n_frame in range(end_frames_disregarded, self.n_frames - end_frames_disregarded): A, b, weights, bounds = self.calculate_forces(n_frame, report_equations=report_equations) D = weighted_bound_least_squares(A, b, weights, bounds, rcond=None) f, tau = D[:(3 * n_joints)], D[(3 * n_joints):] f, tau = f.reshape((n_joints, 3)), tau.reshape((n_joints)) calc_forces.append(f) calc_torques.append(tau) progress.update() forces[end_frames_disregarded: - end_frames_disregarded] = calc_forces torques += calc_torques for i in range(end_frames_disregarded): forces.append(np.zeros(f_shape)) torques.append(np.zeros(t_shape)) if save: np.save(path_join(dir, prefix + "forces.npy"), forces) np.save(path_join(dir, prefix + "torques.npy"), torques) return np.array(forces), np.array(torques) def get_com_position(self): """Calculates the position of the centre of mass of the whole system at each timestep""" return sum(b.XG * b.mass for b in self.target_bones + [self.body]) / self.total_mass def return_equations(self, end_frames_disregarded=5): """For each frame, return the equation vector b""" self.get_dynamics() bs = [] for n_frame in range(end_frames_disregarded, self.n_frames - end_frames_disregarded): A, b, weights, bounds = self.calculate_forces(n_frame, report_equations=False) bs.append(b) return np.array(bs) def set_paw_equilibrium(self): """Get paw equilibrium from mocap data by finding the drop of the paw. This method will work for the current dataset, but is likely not robust, so can be replaced with a better method of finding the paw equilibrium at a later date""" if self.is_mocap: paw_z_heights = self.unsmoothed_data[:, self.foot_joints, 2] else: paw_z_heights = self.unsmoothed_data[:, self.foot_joints, 2] self.paw_disps = {} # paw joint: displacement over time, for paw spring model min_contacts_detected = 3 # minimum requirement to use peak detection mode plot = True if plot: fig, axes = plt.subplots(nrows=2, ncols=2) footfall_detector = FootfallDetector(train=False, load=True, name=["smal", "mocap"][self.is_mocap]) for n, paw in enumerate(self.foot_joints): contact_ends_failed = False disp = np.zeros((self.n_frames)) # will give eps - the displacement of the paw from equilibrium # for when the paw is in contact with the ground Z = paw_z_heights[:, n] on_ground = footfall_detector.process_clip(Z) on_ground_idxs = np.where(on_ground > 0)[0] if plot: axes[n // 2, n % 2].plot(Z.mean() * (on_ground), color="red", alpha=0.3) min_footfall_width = 3 # 3 frames long minimum to count as a footfall footfalls = consecutive(on_ground_idxs) trigger_height = np.percentile(np.array([Z[ff].max() for ff in footfalls]), 25) # mean trigger height for footfall in footfalls: if len(footfall) > min_footfall_width: # disp[footfall] = Z[footfall].max() - Z[footfall] # old disp[footfall] = np.clip(trigger_height - Z[footfall], a_min=0, a_max=None) self.paw_disps[paw] = disp if plot: ax = axes[n // 2, n % 2] ax.plot(Z) Z_on_ground = Z.copy() Z_on_ground[disp == 0] = np.nan ax.plot(Z_on_ground, color="green") ax.plot(disp) Z_smoothed = self.joint_pos[:, paw, 2] ax.set_title(n) if plot: plt.show(block=False) plt.draw() plt.pause(1e-8) def view_ground_displacements(self, deriv=0): """Plot and show a graph of vertical displacement against frames for each paw - identifying L0 for each paw""" fig, axes = plt.subplots(nrows=4) for n, j in enumerate(self.foot_joints): label = foot_joint_labels[n] ax = axes[n] if deriv == 0: X = self.joint_pos[:, j, 2] X_unsmoothed = self.unsmoothed_data[:, j, 2] ax.plot(X) ax.plot(X_unsmoothed, alpha=.6) # ax.axhline(self.paw_equilibrium_values[j], ls = "--") ax.axhline(self.L0_paws[label.split(" ")[0]]) elif deriv == 1: ax.plot(self.joint_vel[:, j, 2]) ax.set_title(label) plt.show() def view_com_displacements(self, deriv=0): """Plot and show graph of X, Y, and Z motion of CoM of dog. If deriv > 0, plot that derivative of the displacement""" fig, ax = plt.subplots() com_data = self.get_com_position() if deriv > 0: com_data = nth_time_deriv(com_data, 1 / self.freq, n=deriv) for i in [0, 1, 2]: ax.plot(com_data[:, i], label="xyz"[i]) ax.legend() plt.show() def calc_leg_lengths(self): """Uses the compliant-legged walking model estimation to work out the average length of legs. Assume legs are undeformed while off ground. Work out avg distance from leg to COM""" self.leg_disps = {} # length of leg over time for each paw self.leg_vecs = {} # normalised vector of leg spring direction for each paw plot = True if plot: fig, axes = plt.subplots(nrows=2, ncols=2, sharex="all", sharey="row") for n, paw in enumerate(self.foot_joints): is_front = n < 2 # Assumes order of f left, f right, r left, r right tol = 1e-3 on_ground = self.paw_disps[paw] > tol off_ground = self.paw_disps[paw] <= tol # centre_of_rot = self.body.XG[:]#self.body.X[:, int(is_front)] # centre_of_rot = self.unsmoothed_data[:, self.body_joints[is_front][n%2]] if self.is_mocap: centre_of_rot = self.unsmoothed_data[:, self.leg_spring_joints[n]] paw_pos = self.unsmoothed_data[:, paw] else: centre_of_rot = self.unsmoothed_data[:, self.leg_spring_joints[n]] paw_pos = self.unsmoothed_data[:, paw] X, Z = np.swapaxes(centre_of_rot[:, [0, 2]], 0, 1) # get X, Z position of CoM X_PAW, Z_PAW = np.swapaxes(paw_pos[:, [0, 2]], 0, 1) # get X, Z position of CoM THETA = np.arctan((X_PAW - X) / (Z - Z_PAW)) # angle between spring and vertical L = ((X - X_PAW) ** 2 + (Z - Z_PAW) ** 2) ** .5 L0 = (L).max() z_disp = (L - L0) * np.cos(THETA) x_disp = (L - L0) * np.sin(THETA) # get z displacement by footfall disp = np.zeros(self.n_frames) # if self.is_mocap: for ff in consecutive(np.where(on_ground)[0]): if len(ff) < 3: continue # min width of footfall required disp[ff] = z_disp[ff].max() - z_disp[ff] # else: # disp = -z_disp self.leg_disps[paw] = disp if plot: ax = axes[n // 2, n % 2] # ax.plot(L) ax.plot(L - L0) ax.plot(disp, color="green") if plot: plt.tight_layout() # plt.show() plt.show(block=False) plt.draw() plt.pause(1e-8) def norm_kin_data(kin_data, targ_markers=None): """Normalise kinematic data. If targ_markers given, normalise so these markers are at desired height""" norm_height = 0.4 # 0.635 # fixed to Ally height for now # scale so minimum is at (0,0,0) for dim in [0, 1, 2]: kin_data[:, :, dim] -= kin_data[:, :, dim].min() if targ_markers is None: kin_data = norm_height * kin_data / np.max(kin_data[:, :, 2]) elif targ_markers is not None: height_target = kin_data[:, targ_markers, 2].mean() kin_data = norm_height * kin_data / height_target return kin_data def get_dyn_data(dynamic_src, clip_length, mass, is_mocap=True, target_freq=100): """Loads and returns kinematic data""" force_plate_data, force_plate_tdelay = load_force_plate_data(dynamic_src, is_mocap) raw_dyn_data = force_plate_data raw_dyn_data *= 1 / (mass * 9.81) # resample if requested if target_freq != freq_forceplate: target_frames = int(len(raw_dyn_data) * target_freq / freq_forceplate) dyn_data = signal.resample(raw_dyn_data, target_frames) # this resampling causes a jumpiness for the periods of zero value. Fix that here: tol = 1e-4 for paw in range(dyn_data.shape[1]): # get indices where should be 0 antifootfalls = consecutive(np.where(raw_dyn_data[:, paw] < tol)[0]) min_width = 10 # in frames for aff in antifootfalls: if len(aff) < min_width: continue start, end = aff[0] * target_freq / freq_forceplate, aff[-1] * target_freq / freq_forceplate # ^ start and end indices, in remapped frame dyn_data[int(start):int(end), paw] = 0 # set to 0 freq = target_freq else: freq = freq_forceplate dyn_data = raw_dyn_data frame_delay = int(freq * force_plate_tdelay) n_frames_forceplate = int(clip_length * freq) # number of frames for forceplate to be same time length as mocap if frame_delay == 0: return dyn_data[:n_frames_forceplate] if frame_delay > 0: # crop forceplate data return dyn_data[frame_delay: frame_delay + n_frames_forceplate] # crop forceplate data to match mocap/SMAL data else: # fdelay <0, pad forceplate data return np.pad(dyn_data, ((int(-frame_delay), 0), (0, 0)))[:n_frames_forceplate] kin_src_to_solver_name = lambda s: s.replace("/", " ").replace(" ", "_").replace(".c3d", "") def load_solver(kin_src, clip_length, mocap=True, resample_freq=100): if mocap: joint_data = C3DData(ax=None, src=kin_src, interpolate=True, crop=clip_length, fix_rotations="3 kph" in kin_src) # only fix rotations for 3 kph for now else: joint_data = SMALData(kin_src, freq=30, norm=True, crop=clip_length, smooth=True) joint_data.resample_at(resample_freq) ### TRY RESAMPLING DATA TO 100 Hz target_bones, body_joints, no_torque_joints, leg_spring_joints = joint_data.generate_skeleton_mapping() # Normalise data based on z data, so that the dog is roughly 0.5m high. Also smooth data kin_data = np.array(joint_data.all_data) kin_data = norm_kin_data(kin_data, targ_markers=leg_spring_joints) solver_kwargs = dict(target_bones=target_bones, body_joints=body_joints, no_torque_joints=no_torque_joints, foot_joints=no_torque_joints, leg_spring_joints=leg_spring_joints, freq=joint_data.freq, name=kin_src_to_solver_name(kin_src)) solver = InverseDynamicsSolver(joint_data=kin_data, **solver_kwargs, is_mocap=mocap) print(f"Solver loaded. Mass = {solver.total_mass:.1f} kg.") return solver
"""Recursively get the nth time derivative""" if n == 1: return time_deriv(X, dt) else: return time_deriv(nth_time_deriv(X, dt, n=n - 1), dt)
cld101xlp.py
from lantz import Feat, DictFeat, Action from lantz.errors import InstrumentError from lantz.messagebased import MessageBasedDriver from pint import UnitRegistry from time import sleep class CLD101XLP(MessageBasedDriver): DEFAULTS = { 'COMMON': { 'write_termination': '\n', 'read_termination': '\n' } } COM_DELAY = 0.2 ureg = UnitRegistry() def write(self, *args, **kwargs): super().write(*args, **kwargs) sleep(self.COM_DELAY) return @Feat(read_once=True) def idn(self): return self.query('*IDN?') @Feat() def key_locked(self): return bool(int(self.query('OUTP:PROT:KEYL:TRIP?'))) @Feat(values={'C': 'CEL', 'F': 'FAR', 'K': 'K'}) def temperature_unit(self): self.t_unit = self.query('UNIT:TEMP?') return self.t_unit @temperature_unit.setter def temperature_unit(self, value): self.write('UNIT:TEMP {}'.format(value)) @Feat() def
(self): return float(self.query('MEAS:SCAL:TEMP?')) @Feat() def temperature_setpoint(self): return float(self.query('SOUR2:TEMP?')) @Action() def read_error_queue(self): no_error = "+0,'No error'" error = inst.query('SYST:ERR:NEXT?') while(error != no_error): print(error) error = inst.query('SYST:ERR:NEXT?') @Feat(values={False: '0', True: '1'}) def ld_state(self): return self.query('OUTP1:STAT?') @ld_state.setter def ld_state(self, value): self.write('OUTP1:STAT {}'.format(value)) @Feat(units='A', limits=(0,0.9)) def ld_current_setpoint(self): return float(self.query('SOUR:CURR?')) @Feat(units='A', limits=(0.0, 0.9)) def ld_current(self): return float(self.query('MEAS:CURR?')) @ld_current.setter def ld_current(self, value): inst.write('SOUR:CURR {:.5f}'.format(value)) @DictFeat(units='W', keys={'photodiode', 'pd', 'thermopile', 'tp', 'power meter'}) def ld_power(self, method): query = 'MEAS:POW{}?' ml = method.lower() if ml in {'photodiode', 'pd'}: method_val = 2 elif ml in {'thermopile', 'tp', 'power meter'}: method_val = 3 return float(self.query(query.format(method_val))) @Feat(values={False: '0', True: '1'}) def tec_state(self): return self.query('OUTP2:STAT?') @tec_state.setter def tec_state(self, value): self.write('OUTP2:STAT {}'.format(value)) @Action() def turn_on_seq(self, temp_error=0.05, current_error=0.005*ureg.milliamp): if self.ld_state == 1: print("Laser is already ON!") return #Turn ON sequence: # 1. TEC ON # 2. Wait for temperature == set_temperature # 3. LD ON # 4. Wait for current == set_current # 1. TEC ON self.tec_state = 1 # 2. Wait setpoint = self.temperature_setpoint while(abs(setpoint-self.temperature)>temp_error):pass # 3. LD ON self.ld_state = 1 # 4. Wait setpoint = self.ld_current_setpoint while(abs(setpoint.m-self.ld_current.m)>current_error.m):pass @Action() def turn_off_seq(self, current_error=0.005*ureg.milliamp): #Turn OFF sequence: # 1. LD OFF # 2. Wait for current == 0 # 3. TEC OFF # 1. LD OFF self.ld_state = 0 # 2. Wait while(abs(self.ld_current.m) > current_error.m):pass # 1. TEC OFF self.tec_state = 0 if __name__ == '__main__': import logging import sys from lantz.log import log_to_screen log_to_screen(logging.CRITICAL) #res_name = sys.argv[1] res_names = ['USB0::0x1313::0x804F::SERIALNUMBER::INSTR', 'USB0::0x1313::0x804F::SERIALNUMBER::INSTR'] print('update res_names!') fmt_str = "{:<30}|{:>30}" on_time = 20 for resource in res_names: with CLD101XLP(resource) as inst: # with CLD101XLP(res_name) as inst: print(fmt_str.format("Temperature unit", inst.temperature_unit)) print(fmt_str.format("Device name", inst.query('*IDN?'))) print(fmt_str.format("LD state", inst.ld_state)) print(fmt_str.format("TEC state", inst.tec_state)) print(fmt_str.format("Temp setpoint", inst.temperature_setpoint)) # inst.ld_current = .0885 print(fmt_str.format("LD current", inst.ld_current)) print(fmt_str.format("LD current setpoint", inst.ld_current_setpoint)) print(fmt_str.format("LD state", inst.ld_state)) print(fmt_str.format("TEC state", inst.tec_state)) print(fmt_str.format("LD temperature", inst.temperature)) # # print("Turning on TEC and LD...") # inst.turn_on_seq() # #print(fmt_str.format("LD power (via photodiode)", inst.ld_power['pd'])) # #print(fmt_str.format("LD power (via thermopile)", inst.ld_power['tp'])) print(fmt_str.format("LD state", inst.ld_state)) print(fmt_str.format("TEC state", inst.tec_state)) print(fmt_str.format("LD temperature", inst.temperature)) # print(fmt_str.format("LD current", inst.ld_current)) # print(fmt_str.format("LD current setpoint", inst.ld_current_setpoint)) # # # inst.ld_current = .025 # print(fmt_str.format("LD current", inst.ld_current)) # print(fmt_str.format("LD current setpoint", inst.ld_current_setpoint)) # #print(fmt_str.format("LD power (via photodiode)", inst.ld_power['pd'])) # #print(fmt_str.format("LD power (via thermopile)", inst.ld_power['tp'])) # sleep(on_time) # # print("Turning off TEC and LD...") # inst.turn_off_seq() # print(fmt_str.format("LD state", inst.ld_state)) # print(fmt_str.format("TEC state", inst.tec_state)) # print(fmt_str.format("LD current", inst.ld_current)) # print(fmt_str.format("LD current setpoint", inst.ld_current_setpoint))
temperature
file.go
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package api4 import ( "io" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" "github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/utils" ) const ( FILE_TEAM_ID = "noteam" PREVIEW_IMAGE_TYPE = "image/jpeg" THUMBNAIL_IMAGE_TYPE = "image/jpeg" ) var UNSAFE_CONTENT_TYPES = [...]string{ "application/javascript", "application/ecmascript", "text/javascript", "text/ecmascript", "application/x-javascript", "text/html", } var MEDIA_CONTENT_TYPES = [...]string{ "image/jpeg", "image/png", "image/bmp", "image/gif", "video/avi", "video/mpeg", "video/mp4", "audio/mpeg", "audio/wav", } func (api *API) InitFile() { api.BaseRoutes.Files.Handle("", api.ApiSessionRequired(uploadFile)).Methods("POST") api.BaseRoutes.File.Handle("", api.ApiSessionRequiredTrustRequester(getFile)).Methods("GET") api.BaseRoutes.File.Handle("/thumbnail", api.ApiSessionRequiredTrustRequester(getFileThumbnail)).Methods("GET") api.BaseRoutes.File.Handle("/link", api.ApiSessionRequired(getFileLink)).Methods("GET") api.BaseRoutes.File.Handle("/preview", api.ApiSessionRequiredTrustRequester(getFilePreview)).Methods("GET") api.BaseRoutes.File.Handle("/info", api.ApiSessionRequired(getFileInfo)).Methods("GET") api.BaseRoutes.PublicFile.Handle("", api.ApiHandler(getPublicFile)).Methods("GET") } func uploadFile(c *Context, w http.ResponseWriter, r *http.Request) { defer io.Copy(ioutil.Discard, r.Body) if !*c.App.Config().FileSettings.EnableFileAttachments { c.Err = model.NewAppError("uploadFile", "api.file.attachments.disabled.app_error", nil, "", http.StatusNotImplemented) return } if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize { c.Err = model.NewAppError("uploadFile", "api.file.upload_file.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge) return } now := time.Now() var resStruct *model.FileUploadResponse var appErr *model.AppError if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil && err != http.ErrNotMultipart { http.Error(w, err.Error(), http.StatusInternalServerError) return } else if err == http.ErrNotMultipart { defer r.Body.Close() c.RequireChannelId() c.RequireFilename() if c.Err != nil { return } channelId := c.Params.ChannelId filename := c.Params.Filename if !c.App.SessionHasPermissionToChannel(c.Session, channelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return } resStruct, appErr = c.App.UploadFiles( FILE_TEAM_ID, channelId, c.Session.UserId, []io.ReadCloser{r.Body}, []string{filename}, []string{}, now, ) } else { m := r.MultipartForm props := m.Value if len(props["channel_id"]) == 0 { c.SetInvalidParam("channel_id") return } channelId := props["channel_id"][0] if len(channelId) == 0 { c.SetInvalidParam("channel_id") return } if !c.App.SessionHasPermissionToChannel(c.Session, channelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return } resStruct, appErr = c.App.UploadMultipartFiles( FILE_TEAM_ID, channelId, c.Session.UserId, m.File["files"], m.Value["client_ids"], now, ) } if appErr != nil { c.Err = appErr return } w.WriteHeader(http.StatusCreated) w.Write([]byte(resStruct.ToJson())) } func getFile(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireFileId() if c.Err != nil { return } forceDownload, convErr := strconv.ParseBool(r.URL.Query().Get("download")) if convErr != nil { forceDownload = false } info, err := c.App.GetFileInfo(c.Params.FileId) if err != nil { c.Err = err return } if info.CreatorId != c.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } fileReader, err := c.App.FileReader(info.Path) if err != nil { c.Err = err c.Err.StatusCode = http.StatusNotFound return } defer fileReader.Close() err = writeFileResponse(info.Name, info.MimeType, info.Size, fileReader, forceDownload, w, r) if err != nil { c.Err = err
} } func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireFileId() if c.Err != nil { return } forceDownload, convErr := strconv.ParseBool(r.URL.Query().Get("download")) if convErr != nil { forceDownload = false } info, err := c.App.GetFileInfo(c.Params.FileId) if err != nil { c.Err = err return } if info.CreatorId != c.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } if info.ThumbnailPath == "" { c.Err = model.NewAppError("getFileThumbnail", "api.file.get_file_thumbnail.no_thumbnail.app_error", nil, "file_id="+info.Id, http.StatusBadRequest) return } fileReader, err := c.App.FileReader(info.ThumbnailPath) if err != nil { c.Err = err c.Err.StatusCode = http.StatusNotFound return } defer fileReader.Close() err = writeFileResponse(info.Name, THUMBNAIL_IMAGE_TYPE, 0, fileReader, forceDownload, w, r) if err != nil { c.Err = err return } } func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireFileId() if c.Err != nil { return } if !c.App.Config().FileSettings.EnablePublicLink { c.Err = model.NewAppError("getPublicLink", "api.file.get_public_link.disabled.app_error", nil, "", http.StatusNotImplemented) return } info, err := c.App.GetFileInfo(c.Params.FileId) if err != nil { c.Err = err return } if info.CreatorId != c.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } if len(info.PostId) == 0 { c.Err = model.NewAppError("getPublicLink", "api.file.get_public_link.no_post.app_error", nil, "file_id="+info.Id, http.StatusBadRequest) return } resp := make(map[string]string) resp["link"] = c.App.GeneratePublicLink(c.GetSiteURLHeader(), info) w.Write([]byte(model.MapToJson(resp))) } func getFilePreview(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireFileId() if c.Err != nil { return } forceDownload, convErr := strconv.ParseBool(r.URL.Query().Get("download")) if convErr != nil { forceDownload = false } info, err := c.App.GetFileInfo(c.Params.FileId) if err != nil { c.Err = err return } if info.CreatorId != c.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } if info.PreviewPath == "" { c.Err = model.NewAppError("getFilePreview", "api.file.get_file_preview.no_preview.app_error", nil, "file_id="+info.Id, http.StatusBadRequest) return } fileReader, err := c.App.FileReader(info.PreviewPath) if err != nil { c.Err = err c.Err.StatusCode = http.StatusNotFound } defer fileReader.Close() err = writeFileResponse(info.Name, PREVIEW_IMAGE_TYPE, 0, fileReader, forceDownload, w, r) if err != nil { c.Err = err return } } func getFileInfo(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireFileId() if c.Err != nil { return } info, err := c.App.GetFileInfo(c.Params.FileId) if err != nil { c.Err = err return } if info.CreatorId != c.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } w.Header().Set("Cache-Control", "max-age=2592000, public") w.Write([]byte(info.ToJson())) } func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireFileId() if c.Err != nil { return } if !c.App.Config().FileSettings.EnablePublicLink { c.Err = model.NewAppError("getPublicFile", "api.file.get_public_link.disabled.app_error", nil, "", http.StatusNotImplemented) return } info, err := c.App.GetFileInfo(c.Params.FileId) if err != nil { c.Err = err return } hash := r.URL.Query().Get("h") if len(hash) == 0 { c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "", http.StatusBadRequest) utils.RenderWebAppError(c.App.Config(), w, r, c.Err, c.App.AsymmetricSigningKey()) return } if hash != app.GeneratePublicLinkHash(info.Id, *c.App.Config().FileSettings.PublicLinkSalt) { c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "", http.StatusBadRequest) utils.RenderWebAppError(c.App.Config(), w, r, c.Err, c.App.AsymmetricSigningKey()) return } fileReader, err := c.App.FileReader(info.Path) if err != nil { c.Err = err c.Err.StatusCode = http.StatusNotFound } defer fileReader.Close() err = writeFileResponse(info.Name, info.MimeType, info.Size, fileReader, true, w, r) if err != nil { c.Err = err return } } func writeFileResponse(filename string, contentType string, contentSize int64, fileReader io.Reader, forceDownload bool, w http.ResponseWriter, r *http.Request) *model.AppError { w.Header().Set("Cache-Control", "max-age=2592000, private") w.Header().Set("X-Content-Type-Options", "nosniff") if contentSize > 0 { w.Header().Set("Content-Length", strconv.Itoa(int(contentSize))) } if contentType == "" { contentType = "application/octet-stream" } else { for _, unsafeContentType := range UNSAFE_CONTENT_TYPES { if strings.HasPrefix(contentType, unsafeContentType) { contentType = "text/plain" break } } } w.Header().Set("Content-Type", contentType) var toDownload bool if forceDownload { toDownload = true } else { isMediaType := false for _, mediaContentType := range MEDIA_CONTENT_TYPES { if strings.HasPrefix(contentType, mediaContentType) { isMediaType = true break } } toDownload = !isMediaType } filename = url.PathEscape(filename) if toDownload { w.Header().Set("Content-Disposition", "attachment;filename=\""+filename+"\"; filename*=UTF-8''"+filename) } else { w.Header().Set("Content-Disposition", "inline;filename=\""+filename+"\"; filename*=UTF-8''"+filename) } // prevent file links from being embedded in iframes w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("Content-Security-Policy", "Frame-ancestors 'none'") io.Copy(w, fileReader) return nil }
return
applicationCredential.browser.ts
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license.
import { AccessToken } from "@azure/core-auth"; import { TokenCredentialOptions } from "../client/identityClient"; import { credentialLogger, formatError } from "../util/logging"; import { ChainedTokenCredential } from "./chainedTokenCredential"; const BrowserNotSupportedError = new Error( "ApplicationCredential is not supported in the browser. Use InteractiveBrowserCredential instead." ); const logger = credentialLogger("ApplicationCredential"); /** * Provides a default {@link ChainedTokenCredential} configuration for * applications that will be deployed to Azure. * * Only available in Node.js */ export class ApplicationCredential extends ChainedTokenCredential { /** * Creates an instance of the ApplicationCredential class. * * The ApplicationCredential provides a default {@link ChainedTokenCredential} configuration for * applications that will be deployed to Azure. * * Only available in Node.js * * @param options - Options for configuring the client which makes the authentication request. */ constructor(_tokenCredentialOptions?: TokenCredentialOptions) { super(); logger.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } public getToken(): Promise<AccessToken> { logger.getToken.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } }
verifyJsonPassword.ts
import { createPair } from '@polkadot/keyring/pair'; import { KeyringPair$Json } from '@polkadot/keyring/types'; import { hexToU8a, isHex } from '@polkadot/util'; import { base64Decode, decodeAddress, encodeAddress } from '@polkadot/util-crypto';
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const cryptoType = (Array.isArray(json.encoding.content) ? json.encoding.content[1] as KeypairType : 'ed25519' as KeypairType); const encType = Array.isArray(json.encoding.type) ? json.encoding.type : [json.encoding.type]; const pair = createPair( { toSS58: encodeAddress, type: cryptoType }, { publicKey: decodeAddress(json.address, true) }, json.meta, isHex(json.encoded) ? hexToU8a(json.encoded) : base64Decode(json.encoded), encType ); pair.decodePkcs8(password); } catch (error) { console.error('Decoding JSON failed', error); return false; } return true; } export default verifyJsonPassword;
import { KeypairType } from '@polkadot/util-crypto/types'; function verifyJsonPassword (json: KeyringPair$Json, password: string): boolean { try {
input.rs
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. use std::fmt::Write; /// See [`AddTagsToStreamInput`](crate::input::AddTagsToStreamInput) pub mod add_tags_to_stream_input { /// A builder for [`AddTagsToStreamInput`](crate::input::AddTagsToStreamInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The name of the stream.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } pub fn tags( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.tags.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.tags = Some(hash_map); self } pub fn set_tags( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`AddTagsToStreamInput`](crate::input::AddTagsToStreamInput) pub fn build( self, ) -> std::result::Result< crate::input::AddTagsToStreamInput, smithy_http::operation::BuildError, > { Ok(crate::input::AddTagsToStreamInput { stream_name: self.stream_name, tags: self.tags, }) } } } #[doc(hidden)] pub type AddTagsToStreamInputOperationOutputAlias = crate::operation::AddTagsToStream; #[doc(hidden)] pub type AddTagsToStreamInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl AddTagsToStreamInput { /// Consumes the builder and constructs an Operation<[`AddTagsToStream`](crate::operation::AddTagsToStream)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::AddTagsToStream, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_add_tags_to_stream(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::AddTagsToStream::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "AddTagsToStream", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.AddTagsToStream"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`AddTagsToStreamInput`](crate::input::AddTagsToStreamInput) pub fn builder() -> crate::input::add_tags_to_stream_input::Builder { crate::input::add_tags_to_stream_input::Builder::default() } } /// See [`CreateStreamInput`](crate::input::CreateStreamInput) pub mod create_stream_input { /// A builder for [`CreateStreamInput`](crate::input::CreateStreamInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) shard_count: std::option::Option<i32>, } impl Builder { /// <p>A name to identify the stream. The stream name is scoped to the AWS account used by /// the application that creates the stream. It is also scoped by AWS Region. That is, two /// streams in two different AWS accounts can have the same name. Two streams in the same /// AWS account but in two different Regions can also have the same name.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The number of shards that the stream will use. The throughput of the stream is a /// function of the number of shards; more shards are required for greater provisioned /// throughput.</p> pub fn shard_count(mut self, input: i32) -> Self { self.shard_count = Some(input); self } pub fn set_shard_count(mut self, input: std::option::Option<i32>) -> Self { self.shard_count = input; self } /// Consumes the builder and constructs a [`CreateStreamInput`](crate::input::CreateStreamInput) pub fn build( self, ) -> std::result::Result<crate::input::CreateStreamInput, smithy_http::operation::BuildError> { Ok(crate::input::CreateStreamInput { stream_name: self.stream_name, shard_count: self.shard_count, }) } } } #[doc(hidden)] pub type CreateStreamInputOperationOutputAlias = crate::operation::CreateStream; #[doc(hidden)] pub type CreateStreamInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateStreamInput { /// Consumes the builder and constructs an Operation<[`CreateStream`](crate::operation::CreateStream)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::CreateStream, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_create_stream(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::CreateStream::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "CreateStream", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.CreateStream"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateStreamInput`](crate::input::CreateStreamInput) pub fn builder() -> crate::input::create_stream_input::Builder { crate::input::create_stream_input::Builder::default() } } /// See [`DecreaseStreamRetentionPeriodInput`](crate::input::DecreaseStreamRetentionPeriodInput) pub mod decrease_stream_retention_period_input { /// A builder for [`DecreaseStreamRetentionPeriodInput`](crate::input::DecreaseStreamRetentionPeriodInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) retention_period_hours: std::option::Option<i32>, } impl Builder { /// <p>The name of the stream to modify.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The new retention period of the stream, in hours. Must be less than the current /// retention period.</p> pub fn retention_period_hours(mut self, input: i32) -> Self { self.retention_period_hours = Some(input); self } pub fn set_retention_period_hours(mut self, input: std::option::Option<i32>) -> Self { self.retention_period_hours = input; self } /// Consumes the builder and constructs a [`DecreaseStreamRetentionPeriodInput`](crate::input::DecreaseStreamRetentionPeriodInput) pub fn build( self, ) -> std::result::Result< crate::input::DecreaseStreamRetentionPeriodInput, smithy_http::operation::BuildError, > { Ok(crate::input::DecreaseStreamRetentionPeriodInput { stream_name: self.stream_name, retention_period_hours: self.retention_period_hours, }) } } } #[doc(hidden)] pub type DecreaseStreamRetentionPeriodInputOperationOutputAlias = crate::operation::DecreaseStreamRetentionPeriod; #[doc(hidden)] pub type DecreaseStreamRetentionPeriodInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DecreaseStreamRetentionPeriodInput { /// Consumes the builder and constructs an Operation<[`DecreaseStreamRetentionPeriod`](crate::operation::DecreaseStreamRetentionPeriod)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DecreaseStreamRetentionPeriod, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_decrease_stream_retention_period(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DecreaseStreamRetentionPeriod::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DecreaseStreamRetentionPeriod", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header( "x-amz-target", "Kinesis_20131202.DecreaseStreamRetentionPeriod", ); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DecreaseStreamRetentionPeriodInput`](crate::input::DecreaseStreamRetentionPeriodInput) pub fn builder() -> crate::input::decrease_stream_retention_period_input::Builder { crate::input::decrease_stream_retention_period_input::Builder::default() } } /// See [`DeleteStreamInput`](crate::input::DeleteStreamInput) pub mod delete_stream_input { /// A builder for [`DeleteStreamInput`](crate::input::DeleteStreamInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) enforce_consumer_deletion: std::option::Option<bool>, } impl Builder { /// <p>The name of the stream to delete.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>If this parameter is unset (<code>null</code>) or if you set it to <code>false</code>, /// and the stream has registered consumers, the call to <code>DeleteStream</code> fails /// with a <code>ResourceInUseException</code>. </p> pub fn enforce_consumer_deletion(mut self, input: bool) -> Self { self.enforce_consumer_deletion = Some(input); self } pub fn set_enforce_consumer_deletion(mut self, input: std::option::Option<bool>) -> Self { self.enforce_consumer_deletion = input; self } /// Consumes the builder and constructs a [`DeleteStreamInput`](crate::input::DeleteStreamInput) pub fn build( self, ) -> std::result::Result<crate::input::DeleteStreamInput, smithy_http::operation::BuildError> { Ok(crate::input::DeleteStreamInput { stream_name: self.stream_name, enforce_consumer_deletion: self.enforce_consumer_deletion, }) } } } #[doc(hidden)] pub type DeleteStreamInputOperationOutputAlias = crate::operation::DeleteStream; #[doc(hidden)] pub type DeleteStreamInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteStreamInput { /// Consumes the builder and constructs an Operation<[`DeleteStream`](crate::operation::DeleteStream)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DeleteStream, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_delete_stream(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DeleteStream::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DeleteStream", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.DeleteStream"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteStreamInput`](crate::input::DeleteStreamInput) pub fn builder() -> crate::input::delete_stream_input::Builder { crate::input::delete_stream_input::Builder::default() } } /// See [`DeregisterStreamConsumerInput`](crate::input::DeregisterStreamConsumerInput) pub mod deregister_stream_consumer_input { /// A builder for [`DeregisterStreamConsumerInput`](crate::input::DeregisterStreamConsumerInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_arn: std::option::Option<std::string::String>, pub(crate) consumer_name: std::option::Option<std::string::String>, pub(crate) consumer_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>The ARN of the Kinesis data stream that the consumer is registered with. For more /// information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams">Amazon Resource Names (ARNs) and AWS Service Namespaces</a>.</p> pub fn stream_arn(mut self, input: impl Into<std::string::String>) -> Self { self.stream_arn = Some(input.into()); self } pub fn set_stream_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_arn = input; self } /// <p>The name that you gave to the consumer.</p> pub fn consumer_name(mut self, input: impl Into<std::string::String>) -> Self { self.consumer_name = Some(input.into()); self } pub fn set_consumer_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.consumer_name = input; self } /// <p>The ARN returned by Kinesis Data Streams when you registered the consumer. If you /// don't know the ARN of the consumer that you want to deregister, you can use the /// ListStreamConsumers operation to get a list of the descriptions of all the consumers /// that are currently registered with a given data stream. The description of a consumer /// contains its ARN.</p> pub fn consumer_arn(mut self, input: impl Into<std::string::String>) -> Self { self.consumer_arn = Some(input.into()); self } pub fn set_consumer_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.consumer_arn = input; self } /// Consumes the builder and constructs a [`DeregisterStreamConsumerInput`](crate::input::DeregisterStreamConsumerInput) pub fn build( self, ) -> std::result::Result< crate::input::DeregisterStreamConsumerInput, smithy_http::operation::BuildError, > { Ok(crate::input::DeregisterStreamConsumerInput { stream_arn: self.stream_arn, consumer_name: self.consumer_name, consumer_arn: self.consumer_arn, }) } } } #[doc(hidden)] pub type DeregisterStreamConsumerInputOperationOutputAlias = crate::operation::DeregisterStreamConsumer; #[doc(hidden)] pub type DeregisterStreamConsumerInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeregisterStreamConsumerInput { /// Consumes the builder and constructs an Operation<[`DeregisterStreamConsumer`](crate::operation::DeregisterStreamConsumer)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DeregisterStreamConsumer, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_deregister_stream_consumer(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DeregisterStreamConsumer::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DeregisterStreamConsumer", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.DeregisterStreamConsumer"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeregisterStreamConsumerInput`](crate::input::DeregisterStreamConsumerInput) pub fn builder() -> crate::input::deregister_stream_consumer_input::Builder { crate::input::deregister_stream_consumer_input::Builder::default() } } /// See [`DescribeLimitsInput`](crate::input::DescribeLimitsInput) pub mod describe_limits_input { /// A builder for [`DescribeLimitsInput`](crate::input::DescribeLimitsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`DescribeLimitsInput`](crate::input::DescribeLimitsInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeLimitsInput, smithy_http::operation::BuildError, > { Ok(crate::input::DescribeLimitsInput {}) } } } #[doc(hidden)] pub type DescribeLimitsInputOperationOutputAlias = crate::operation::DescribeLimits; #[doc(hidden)] pub type DescribeLimitsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeLimitsInput { /// Consumes the builder and constructs an Operation<[`DescribeLimits`](crate::operation::DescribeLimits)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DescribeLimits, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_describe_limits(&self).map_err( |err| smithy_http::operation::BuildError::SerializationError(err.into()), )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DescribeLimits::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DescribeLimits", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.DescribeLimits"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeLimitsInput`](crate::input::DescribeLimitsInput) pub fn builder() -> crate::input::describe_limits_input::Builder { crate::input::describe_limits_input::Builder::default() } } /// See [`DescribeStreamInput`](crate::input::DescribeStreamInput) pub mod describe_stream_input { /// A builder for [`DescribeStreamInput`](crate::input::DescribeStreamInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) limit: std::option::Option<i32>, pub(crate) exclusive_start_shard_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the stream to describe.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The maximum number of shards to return in a single call. The default value is 100. /// If you specify a value greater than 100, at most 100 shards are returned.</p> pub fn limit(mut self, input: i32) -> Self { self.limit = Some(input); self } pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self { self.limit = input; self } /// <p>The shard ID of the shard to start with.</p> pub fn exclusive_start_shard_id(mut self, input: impl Into<std::string::String>) -> Self { self.exclusive_start_shard_id = Some(input.into()); self } pub fn set_exclusive_start_shard_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.exclusive_start_shard_id = input; self } /// Consumes the builder and constructs a [`DescribeStreamInput`](crate::input::DescribeStreamInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeStreamInput, smithy_http::operation::BuildError, > { Ok(crate::input::DescribeStreamInput { stream_name: self.stream_name, limit: self.limit, exclusive_start_shard_id: self.exclusive_start_shard_id, }) } } } #[doc(hidden)] pub type DescribeStreamInputOperationOutputAlias = crate::operation::DescribeStream; #[doc(hidden)] pub type DescribeStreamInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeStreamInput { /// Consumes the builder and constructs an Operation<[`DescribeStream`](crate::operation::DescribeStream)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DescribeStream, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_describe_stream(&self).map_err( |err| smithy_http::operation::BuildError::SerializationError(err.into()), )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DescribeStream::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DescribeStream", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.DescribeStream"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeStreamInput`](crate::input::DescribeStreamInput) pub fn builder() -> crate::input::describe_stream_input::Builder { crate::input::describe_stream_input::Builder::default() } } /// See [`DescribeStreamConsumerInput`](crate::input::DescribeStreamConsumerInput) pub mod describe_stream_consumer_input { /// A builder for [`DescribeStreamConsumerInput`](crate::input::DescribeStreamConsumerInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_arn: std::option::Option<std::string::String>, pub(crate) consumer_name: std::option::Option<std::string::String>, pub(crate) consumer_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>The ARN of the Kinesis data stream that the consumer is registered with. For more /// information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams">Amazon Resource Names (ARNs) and AWS Service Namespaces</a>.</p> pub fn stream_arn(mut self, input: impl Into<std::string::String>) -> Self { self.stream_arn = Some(input.into()); self } pub fn set_stream_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_arn = input; self } /// <p>The name that you gave to the consumer.</p> pub fn consumer_name(mut self, input: impl Into<std::string::String>) -> Self { self.consumer_name = Some(input.into()); self } pub fn set_consumer_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.consumer_name = input; self } /// <p>The ARN returned by Kinesis Data Streams when you registered the consumer.</p> pub fn consumer_arn(mut self, input: impl Into<std::string::String>) -> Self { self.consumer_arn = Some(input.into()); self } pub fn set_consumer_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.consumer_arn = input; self } /// Consumes the builder and constructs a [`DescribeStreamConsumerInput`](crate::input::DescribeStreamConsumerInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeStreamConsumerInput, smithy_http::operation::BuildError, > { Ok(crate::input::DescribeStreamConsumerInput { stream_arn: self.stream_arn, consumer_name: self.consumer_name, consumer_arn: self.consumer_arn, }) } } } #[doc(hidden)] pub type DescribeStreamConsumerInputOperationOutputAlias = crate::operation::DescribeStreamConsumer; #[doc(hidden)] pub type DescribeStreamConsumerInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeStreamConsumerInput { /// Consumes the builder and constructs an Operation<[`DescribeStreamConsumer`](crate::operation::DescribeStreamConsumer)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DescribeStreamConsumer, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_describe_stream_consumer(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DescribeStreamConsumer::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DescribeStreamConsumer", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.DescribeStreamConsumer"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeStreamConsumerInput`](crate::input::DescribeStreamConsumerInput) pub fn builder() -> crate::input::describe_stream_consumer_input::Builder { crate::input::describe_stream_consumer_input::Builder::default() } } /// See [`DescribeStreamSummaryInput`](crate::input::DescribeStreamSummaryInput) pub mod describe_stream_summary_input { /// A builder for [`DescribeStreamSummaryInput`](crate::input::DescribeStreamSummaryInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the stream to describe.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// Consumes the builder and constructs a [`DescribeStreamSummaryInput`](crate::input::DescribeStreamSummaryInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeStreamSummaryInput, smithy_http::operation::BuildError, > { Ok(crate::input::DescribeStreamSummaryInput { stream_name: self.stream_name, }) } } } #[doc(hidden)] pub type DescribeStreamSummaryInputOperationOutputAlias = crate::operation::DescribeStreamSummary; #[doc(hidden)] pub type DescribeStreamSummaryInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeStreamSummaryInput { /// Consumes the builder and constructs an Operation<[`DescribeStreamSummary`](crate::operation::DescribeStreamSummary)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DescribeStreamSummary, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_describe_stream_summary(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DescribeStreamSummary::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DescribeStreamSummary", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.DescribeStreamSummary"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeStreamSummaryInput`](crate::input::DescribeStreamSummaryInput) pub fn builder() -> crate::input::describe_stream_summary_input::Builder { crate::input::describe_stream_summary_input::Builder::default() } } /// See [`DisableEnhancedMonitoringInput`](crate::input::DisableEnhancedMonitoringInput) pub mod disable_enhanced_monitoring_input { /// A builder for [`DisableEnhancedMonitoringInput`](crate::input::DisableEnhancedMonitoringInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) shard_level_metrics: std::option::Option<std::vec::Vec<crate::model::MetricsName>>, } impl Builder { /// <p>The name of the Kinesis data stream for which to disable enhanced /// monitoring.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } pub fn shard_level_metrics(mut self, input: impl Into<crate::model::MetricsName>) -> Self { let mut v = self.shard_level_metrics.unwrap_or_default(); v.push(input.into()); self.shard_level_metrics = Some(v); self } pub fn set_shard_level_metrics( mut self, input: std::option::Option<std::vec::Vec<crate::model::MetricsName>>, ) -> Self { self.shard_level_metrics = input; self } /// Consumes the builder and constructs a [`DisableEnhancedMonitoringInput`](crate::input::DisableEnhancedMonitoringInput) pub fn build( self, ) -> std::result::Result< crate::input::DisableEnhancedMonitoringInput, smithy_http::operation::BuildError, > { Ok(crate::input::DisableEnhancedMonitoringInput { stream_name: self.stream_name, shard_level_metrics: self.shard_level_metrics, }) } } } #[doc(hidden)] pub type DisableEnhancedMonitoringInputOperationOutputAlias = crate::operation::DisableEnhancedMonitoring; #[doc(hidden)] pub type DisableEnhancedMonitoringInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DisableEnhancedMonitoringInput { /// Consumes the builder and constructs an Operation<[`DisableEnhancedMonitoring`](crate::operation::DisableEnhancedMonitoring)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DisableEnhancedMonitoring, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_disable_enhanced_monitoring(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DisableEnhancedMonitoring::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DisableEnhancedMonitoring", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.DisableEnhancedMonitoring"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DisableEnhancedMonitoringInput`](crate::input::DisableEnhancedMonitoringInput) pub fn builder() -> crate::input::disable_enhanced_monitoring_input::Builder { crate::input::disable_enhanced_monitoring_input::Builder::default() } } /// See [`EnableEnhancedMonitoringInput`](crate::input::EnableEnhancedMonitoringInput) pub mod enable_enhanced_monitoring_input { /// A builder for [`EnableEnhancedMonitoringInput`](crate::input::EnableEnhancedMonitoringInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) shard_level_metrics: std::option::Option<std::vec::Vec<crate::model::MetricsName>>, } impl Builder { /// <p>The name of the stream for which to enable enhanced monitoring.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } pub fn shard_level_metrics(mut self, input: impl Into<crate::model::MetricsName>) -> Self { let mut v = self.shard_level_metrics.unwrap_or_default(); v.push(input.into()); self.shard_level_metrics = Some(v); self } pub fn set_shard_level_metrics( mut self, input: std::option::Option<std::vec::Vec<crate::model::MetricsName>>, ) -> Self { self.shard_level_metrics = input; self } /// Consumes the builder and constructs a [`EnableEnhancedMonitoringInput`](crate::input::EnableEnhancedMonitoringInput) pub fn build( self, ) -> std::result::Result< crate::input::EnableEnhancedMonitoringInput, smithy_http::operation::BuildError, > { Ok(crate::input::EnableEnhancedMonitoringInput { stream_name: self.stream_name, shard_level_metrics: self.shard_level_metrics, }) } } } #[doc(hidden)] pub type EnableEnhancedMonitoringInputOperationOutputAlias = crate::operation::EnableEnhancedMonitoring; #[doc(hidden)] pub type EnableEnhancedMonitoringInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl EnableEnhancedMonitoringInput { /// Consumes the builder and constructs an Operation<[`EnableEnhancedMonitoring`](crate::operation::EnableEnhancedMonitoring)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::EnableEnhancedMonitoring, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_enable_enhanced_monitoring(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::EnableEnhancedMonitoring::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "EnableEnhancedMonitoring", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.EnableEnhancedMonitoring"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`EnableEnhancedMonitoringInput`](crate::input::EnableEnhancedMonitoringInput) pub fn builder() -> crate::input::enable_enhanced_monitoring_input::Builder { crate::input::enable_enhanced_monitoring_input::Builder::default() } } /// See [`GetRecordsInput`](crate::input::GetRecordsInput) pub mod get_records_input { /// A builder for [`GetRecordsInput`](crate::input::GetRecordsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) shard_iterator: std::option::Option<std::string::String>, pub(crate) limit: std::option::Option<i32>, } impl Builder { /// <p>The position in the shard from which you want to start sequentially reading data /// records. A shard iterator specifies this position using the sequence number of a data /// record in the shard.</p> pub fn shard_iterator(mut self, input: impl Into<std::string::String>) -> Self { self.shard_iterator = Some(input.into()); self } pub fn set_shard_iterator( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.shard_iterator = input; self } /// <p>The maximum number of records to return. Specify a value of up to 10,000. If you /// specify a value that is greater than 10,000, <a>GetRecords</a> throws /// <code>InvalidArgumentException</code>. The default value is 10,000.</p> pub fn limit(mut self, input: i32) -> Self { self.limit = Some(input); self } pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self { self.limit = input; self } /// Consumes the builder and constructs a [`GetRecordsInput`](crate::input::GetRecordsInput) pub fn build( self, ) -> std::result::Result<crate::input::GetRecordsInput, smithy_http::operation::BuildError> { Ok(crate::input::GetRecordsInput { shard_iterator: self.shard_iterator, limit: self.limit, }) } } } #[doc(hidden)] pub type GetRecordsInputOperationOutputAlias = crate::operation::GetRecords; #[doc(hidden)] pub type GetRecordsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetRecordsInput { /// Consumes the builder and constructs an Operation<[`GetRecords`](crate::operation::GetRecords)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::GetRecords, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_get_records(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::GetRecords::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "GetRecords", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.GetRecords"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetRecordsInput`](crate::input::GetRecordsInput) pub fn builder() -> crate::input::get_records_input::Builder { crate::input::get_records_input::Builder::default() } } /// See [`GetShardIteratorInput`](crate::input::GetShardIteratorInput) pub mod get_shard_iterator_input { /// A builder for [`GetShardIteratorInput`](crate::input::GetShardIteratorInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) shard_id: std::option::Option<std::string::String>, pub(crate) shard_iterator_type: std::option::Option<crate::model::ShardIteratorType>, pub(crate) starting_sequence_number: std::option::Option<std::string::String>, pub(crate) timestamp: std::option::Option<smithy_types::Instant>, } impl Builder { /// <p>The name of the Amazon Kinesis data stream.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The shard ID of the Kinesis Data Streams shard to get the iterator for.</p> pub fn shard_id(mut self, input: impl Into<std::string::String>) -> Self { self.shard_id = Some(input.into()); self } pub fn set_shard_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.shard_id = input; self } /// <p>Determines how the shard iterator is used to start reading data records from the /// shard.</p> /// <p>The following are the valid Amazon Kinesis shard iterator types:</p> /// <ul> /// <li> /// <p>AT_SEQUENCE_NUMBER - Start reading from the position denoted by a specific /// sequence number, provided in the value /// <code>StartingSequenceNumber</code>.</p> /// </li> /// <li> /// <p>AFTER_SEQUENCE_NUMBER - Start reading right after the position denoted by a /// specific sequence number, provided in the value /// <code>StartingSequenceNumber</code>.</p> /// </li> /// <li> /// <p>AT_TIMESTAMP - Start reading from the position denoted by a specific time /// stamp, provided in the value <code>Timestamp</code>.</p> /// </li> /// <li> /// <p>TRIM_HORIZON - Start reading at the last untrimmed record in the shard in /// the system, which is the oldest data record in the shard.</p> /// </li> /// <li> /// <p>LATEST - Start reading just after the most recent record in the shard, so /// that you always read the most recent data in the shard.</p> /// </li> /// </ul> pub fn shard_iterator_type(mut self, input: crate::model::ShardIteratorType) -> Self { self.shard_iterator_type = Some(input); self } pub fn set_shard_iterator_type( mut self, input: std::option::Option<crate::model::ShardIteratorType>, ) -> Self { self.shard_iterator_type = input; self } /// <p>The sequence number of the data record in the shard from which to start reading. /// Used with shard iterator type AT_SEQUENCE_NUMBER and AFTER_SEQUENCE_NUMBER.</p> pub fn starting_sequence_number(mut self, input: impl Into<std::string::String>) -> Self { self.starting_sequence_number = Some(input.into()); self } pub fn set_starting_sequence_number( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.starting_sequence_number = input; self } /// <p>The time stamp of the data record from which to start reading. Used with shard /// iterator type AT_TIMESTAMP. A time stamp is the Unix epoch date with precision in /// milliseconds. For example, <code>2016-04-04T19:58:46.480-00:00</code> or /// <code>1459799926.480</code>. If a record with this exact time stamp does not exist, /// the iterator returned is for the next (later) record. If the time stamp is older than /// the current trim horizon, the iterator returned is for the oldest untrimmed data record /// (TRIM_HORIZON).</p> pub fn timestamp(mut self, input: smithy_types::Instant) -> Self { self.timestamp = Some(input); self } pub fn set_timestamp(mut self, input: std::option::Option<smithy_types::Instant>) -> Self { self.timestamp = input; self } /// Consumes the builder and constructs a [`GetShardIteratorInput`](crate::input::GetShardIteratorInput) pub fn build( self, ) -> std::result::Result< crate::input::GetShardIteratorInput, smithy_http::operation::BuildError, > { Ok(crate::input::GetShardIteratorInput { stream_name: self.stream_name, shard_id: self.shard_id, shard_iterator_type: self.shard_iterator_type, starting_sequence_number: self.starting_sequence_number, timestamp: self.timestamp, }) } } } #[doc(hidden)] pub type GetShardIteratorInputOperationOutputAlias = crate::operation::GetShardIterator; #[doc(hidden)] pub type GetShardIteratorInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetShardIteratorInput { /// Consumes the builder and constructs an Operation<[`GetShardIterator`](crate::operation::GetShardIterator)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::GetShardIterator, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_get_shard_iterator(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::GetShardIterator::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "GetShardIterator", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.GetShardIterator"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetShardIteratorInput`](crate::input::GetShardIteratorInput) pub fn builder() -> crate::input::get_shard_iterator_input::Builder { crate::input::get_shard_iterator_input::Builder::default() } } /// See [`IncreaseStreamRetentionPeriodInput`](crate::input::IncreaseStreamRetentionPeriodInput) pub mod increase_stream_retention_period_input { /// A builder for [`IncreaseStreamRetentionPeriodInput`](crate::input::IncreaseStreamRetentionPeriodInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) retention_period_hours: std::option::Option<i32>, } impl Builder { /// <p>The name of the stream to modify.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The new retention period of the stream, in hours. Must be more than the current /// retention period.</p> pub fn retention_period_hours(mut self, input: i32) -> Self { self.retention_period_hours = Some(input); self } pub fn set_retention_period_hours(mut self, input: std::option::Option<i32>) -> Self { self.retention_period_hours = input; self } /// Consumes the builder and constructs a [`IncreaseStreamRetentionPeriodInput`](crate::input::IncreaseStreamRetentionPeriodInput) pub fn build( self, ) -> std::result::Result< crate::input::IncreaseStreamRetentionPeriodInput, smithy_http::operation::BuildError, > { Ok(crate::input::IncreaseStreamRetentionPeriodInput { stream_name: self.stream_name, retention_period_hours: self.retention_period_hours, }) } } } #[doc(hidden)] pub type IncreaseStreamRetentionPeriodInputOperationOutputAlias = crate::operation::IncreaseStreamRetentionPeriod; #[doc(hidden)] pub type IncreaseStreamRetentionPeriodInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl IncreaseStreamRetentionPeriodInput { /// Consumes the builder and constructs an Operation<[`IncreaseStreamRetentionPeriod`](crate::operation::IncreaseStreamRetentionPeriod)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::IncreaseStreamRetentionPeriod, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_increase_stream_retention_period(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::IncreaseStreamRetentionPeriod::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "IncreaseStreamRetentionPeriod", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header( "x-amz-target", "Kinesis_20131202.IncreaseStreamRetentionPeriod", ); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`IncreaseStreamRetentionPeriodInput`](crate::input::IncreaseStreamRetentionPeriodInput) pub fn builder() -> crate::input::increase_stream_retention_period_input::Builder { crate::input::increase_stream_retention_period_input::Builder::default() } } /// See [`ListShardsInput`](crate::input::ListShardsInput) pub mod list_shards_input { /// A builder for [`ListShardsInput`](crate::input::ListShardsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) exclusive_start_shard_id: std::option::Option<std::string::String>, pub(crate) max_results: std::option::Option<i32>, pub(crate) stream_creation_timestamp: std::option::Option<smithy_types::Instant>, pub(crate) shard_filter: std::option::Option<crate::model::ShardFilter>, } impl Builder { /// <p>The name of the data stream whose shards you want to list. </p> /// <p>You cannot specify this parameter if you specify the <code>NextToken</code> /// parameter.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>When the number of shards in the data stream is greater than the default value for /// the <code>MaxResults</code> parameter, or if you explicitly specify a value for /// <code>MaxResults</code> that is less than the number of shards in the data stream, /// the response includes a pagination token named <code>NextToken</code>. You can specify /// this <code>NextToken</code> value in a subsequent call to <code>ListShards</code> to /// list the next set of shards.</p> /// <p>Don't specify <code>StreamName</code> or <code>StreamCreationTimestamp</code> if /// you specify <code>NextToken</code> because the latter unambiguously identifies the /// stream.</p> /// <p>You can optionally specify a value for the <code>MaxResults</code> parameter when /// you specify <code>NextToken</code>. If you specify a <code>MaxResults</code> value that /// is less than the number of shards that the operation returns if you don't specify /// <code>MaxResults</code>, the response will contain a new <code>NextToken</code> /// value. You can use the new <code>NextToken</code> value in a subsequent call to the /// <code>ListShards</code> operation.</p> /// <important> /// <p>Tokens expire after 300 seconds. When you obtain a value for /// <code>NextToken</code> in the response to a call to <code>ListShards</code>, you /// have 300 seconds to use that value. If you specify an expired token in a call to /// <code>ListShards</code>, you get /// <code>ExpiredNextTokenException</code>.</p> /// </important> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// <p>Specify this parameter to indicate that you want to list the shards starting with /// the shard whose ID immediately follows <code>ExclusiveStartShardId</code>.</p> /// <p>If you don't specify this parameter, the default behavior is for /// <code>ListShards</code> to list the shards starting with the first one in the /// stream.</p> /// <p>You cannot specify this parameter if you specify <code>NextToken</code>.</p> pub fn exclusive_start_shard_id(mut self, input: impl Into<std::string::String>) -> Self { self.exclusive_start_shard_id = Some(input.into()); self } pub fn set_exclusive_start_shard_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.exclusive_start_shard_id = input; self } /// <p>The maximum number of shards to return in a single call to <code>ListShards</code>. /// The minimum value you can specify for this parameter is 1, and the maximum is 10,000, /// which is also the default.</p> /// <p>When the number of shards to be listed is greater than the value of /// <code>MaxResults</code>, the response contains a <code>NextToken</code> value that /// you can use in a subsequent call to <code>ListShards</code> to list the next set of /// shards.</p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p>Specify this input parameter to distinguish data streams that have the same name. /// For example, if you create a data stream and then delete it, and you later create /// another data stream with the same name, you can use this input parameter to specify /// which of the two streams you want to list the shards for.</p> /// <p>You cannot specify this parameter if you specify the <code>NextToken</code> /// parameter.</p> pub fn stream_creation_timestamp(mut self, input: smithy_types::Instant) -> Self { self.stream_creation_timestamp = Some(input); self } pub fn set_stream_creation_timestamp( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.stream_creation_timestamp = input; self } pub fn shard_filter(mut self, input: crate::model::ShardFilter) -> Self { self.shard_filter = Some(input); self } pub fn set_shard_filter( mut self, input: std::option::Option<crate::model::ShardFilter>, ) -> Self { self.shard_filter = input; self } /// Consumes the builder and constructs a [`ListShardsInput`](crate::input::ListShardsInput) pub fn build( self, ) -> std::result::Result<crate::input::ListShardsInput, smithy_http::operation::BuildError> { Ok(crate::input::ListShardsInput { stream_name: self.stream_name, next_token: self.next_token, exclusive_start_shard_id: self.exclusive_start_shard_id, max_results: self.max_results, stream_creation_timestamp: self.stream_creation_timestamp, shard_filter: self.shard_filter, }) } } } #[doc(hidden)] pub type ListShardsInputOperationOutputAlias = crate::operation::ListShards; #[doc(hidden)] pub type ListShardsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListShardsInput { /// Consumes the builder and constructs an Operation<[`ListShards`](crate::operation::ListShards)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::ListShards, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_list_shards(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::ListShards::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "ListShards", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.ListShards"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListShardsInput`](crate::input::ListShardsInput) pub fn builder() -> crate::input::list_shards_input::Builder { crate::input::list_shards_input::Builder::default() } } /// See [`ListStreamConsumersInput`](crate::input::ListStreamConsumersInput) pub mod list_stream_consumers_input { /// A builder for [`ListStreamConsumersInput`](crate::input::ListStreamConsumersInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_arn: std::option::Option<std::string::String>, pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) max_results: std::option::Option<i32>, pub(crate) stream_creation_timestamp: std::option::Option<smithy_types::Instant>, } impl Builder { /// <p>The ARN of the Kinesis data stream for which you want to list the registered /// consumers. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams">Amazon Resource Names (ARNs) and AWS Service Namespaces</a>.</p> pub fn stream_arn(mut self, input: impl Into<std::string::String>) -> Self { self.stream_arn = Some(input.into()); self } pub fn set_stream_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_arn = input; self } /// <p>When the number of consumers that are registered with the data stream is greater than /// the default value for the <code>MaxResults</code> parameter, or if you explicitly /// specify a value for <code>MaxResults</code> that is less than the number of consumers /// that are registered with the data stream, the response includes a pagination token named /// <code>NextToken</code>. You can specify this <code>NextToken</code> value in a /// subsequent call to <code>ListStreamConsumers</code> to list the next set of registered /// consumers.</p> /// <p>Don't specify <code>StreamName</code> or <code>StreamCreationTimestamp</code> if you /// specify <code>NextToken</code> because the latter unambiguously identifies the /// stream.</p> /// <p>You can optionally specify a value for the <code>MaxResults</code> parameter when you /// specify <code>NextToken</code>. If you specify a <code>MaxResults</code> value that is /// less than the number of consumers that the operation returns if you don't specify /// <code>MaxResults</code>, the response will contain a new <code>NextToken</code> /// value. You can use the new <code>NextToken</code> value in a subsequent call to the /// <code>ListStreamConsumers</code> operation to list the next set of consumers.</p> /// <important> /// <p>Tokens expire after 300 seconds. When you obtain a value for /// <code>NextToken</code> in the response to a call to /// <code>ListStreamConsumers</code>, you have 300 seconds to use that value. If you /// specify an expired token in a call to <code>ListStreamConsumers</code>, you get /// <code>ExpiredNextTokenException</code>.</p> /// </important> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// <p>The maximum number of consumers that you want a single call of /// <code>ListStreamConsumers</code> to return.</p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p>Specify this input parameter to distinguish data streams that have the same name. For /// example, if you create a data stream and then delete it, and you later create another /// data stream with the same name, you can use this input parameter to specify which of the /// two streams you want to list the consumers for. </p> /// <p>You can't specify this parameter if you specify the NextToken parameter. </p> pub fn stream_creation_timestamp(mut self, input: smithy_types::Instant) -> Self { self.stream_creation_timestamp = Some(input); self } pub fn set_stream_creation_timestamp( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.stream_creation_timestamp = input; self } /// Consumes the builder and constructs a [`ListStreamConsumersInput`](crate::input::ListStreamConsumersInput) pub fn build( self, ) -> std::result::Result< crate::input::ListStreamConsumersInput, smithy_http::operation::BuildError, > { Ok(crate::input::ListStreamConsumersInput { stream_arn: self.stream_arn, next_token: self.next_token, max_results: self.max_results, stream_creation_timestamp: self.stream_creation_timestamp, }) } } } #[doc(hidden)] pub type ListStreamConsumersInputOperationOutputAlias = crate::operation::ListStreamConsumers; #[doc(hidden)] pub type ListStreamConsumersInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListStreamConsumersInput { /// Consumes the builder and constructs an Operation<[`ListStreamConsumers`](crate::operation::ListStreamConsumers)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::ListStreamConsumers, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_list_stream_consumers(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::ListStreamConsumers::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "ListStreamConsumers", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError>
fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListStreamConsumersInput`](crate::input::ListStreamConsumersInput) pub fn builder() -> crate::input::list_stream_consumers_input::Builder { crate::input::list_stream_consumers_input::Builder::default() } } /// See [`ListStreamsInput`](crate::input::ListStreamsInput) pub mod list_streams_input { /// A builder for [`ListStreamsInput`](crate::input::ListStreamsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) limit: std::option::Option<i32>, pub(crate) exclusive_start_stream_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The maximum number of streams to list.</p> pub fn limit(mut self, input: i32) -> Self { self.limit = Some(input); self } pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self { self.limit = input; self } /// <p>The name of the stream to start the list with.</p> pub fn exclusive_start_stream_name( mut self, input: impl Into<std::string::String>, ) -> Self { self.exclusive_start_stream_name = Some(input.into()); self } pub fn set_exclusive_start_stream_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.exclusive_start_stream_name = input; self } /// Consumes the builder and constructs a [`ListStreamsInput`](crate::input::ListStreamsInput) pub fn build( self, ) -> std::result::Result<crate::input::ListStreamsInput, smithy_http::operation::BuildError> { Ok(crate::input::ListStreamsInput { limit: self.limit, exclusive_start_stream_name: self.exclusive_start_stream_name, }) } } } #[doc(hidden)] pub type ListStreamsInputOperationOutputAlias = crate::operation::ListStreams; #[doc(hidden)] pub type ListStreamsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListStreamsInput { /// Consumes the builder and constructs an Operation<[`ListStreams`](crate::operation::ListStreams)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::ListStreams, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_list_streams(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::ListStreams::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "ListStreams", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.ListStreams"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListStreamsInput`](crate::input::ListStreamsInput) pub fn builder() -> crate::input::list_streams_input::Builder { crate::input::list_streams_input::Builder::default() } } /// See [`ListTagsForStreamInput`](crate::input::ListTagsForStreamInput) pub mod list_tags_for_stream_input { /// A builder for [`ListTagsForStreamInput`](crate::input::ListTagsForStreamInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) exclusive_start_tag_key: std::option::Option<std::string::String>, pub(crate) limit: std::option::Option<i32>, } impl Builder { /// <p>The name of the stream.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The key to use as the starting point for the list of tags. If this parameter is /// set, <code>ListTagsForStream</code> gets all tags that occur after /// <code>ExclusiveStartTagKey</code>. </p> pub fn exclusive_start_tag_key(mut self, input: impl Into<std::string::String>) -> Self { self.exclusive_start_tag_key = Some(input.into()); self } pub fn set_exclusive_start_tag_key( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.exclusive_start_tag_key = input; self } /// <p>The number of tags to return. If this number is less than the total number of tags /// associated with the stream, <code>HasMoreTags</code> is set to <code>true</code>. To /// list additional tags, set <code>ExclusiveStartTagKey</code> to the last key in the /// response.</p> pub fn limit(mut self, input: i32) -> Self { self.limit = Some(input); self } pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self { self.limit = input; self } /// Consumes the builder and constructs a [`ListTagsForStreamInput`](crate::input::ListTagsForStreamInput) pub fn build( self, ) -> std::result::Result< crate::input::ListTagsForStreamInput, smithy_http::operation::BuildError, > { Ok(crate::input::ListTagsForStreamInput { stream_name: self.stream_name, exclusive_start_tag_key: self.exclusive_start_tag_key, limit: self.limit, }) } } } #[doc(hidden)] pub type ListTagsForStreamInputOperationOutputAlias = crate::operation::ListTagsForStream; #[doc(hidden)] pub type ListTagsForStreamInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListTagsForStreamInput { /// Consumes the builder and constructs an Operation<[`ListTagsForStream`](crate::operation::ListTagsForStream)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::ListTagsForStream, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_list_tags_for_stream(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::ListTagsForStream::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "ListTagsForStream", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.ListTagsForStream"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListTagsForStreamInput`](crate::input::ListTagsForStreamInput) pub fn builder() -> crate::input::list_tags_for_stream_input::Builder { crate::input::list_tags_for_stream_input::Builder::default() } } /// See [`MergeShardsInput`](crate::input::MergeShardsInput) pub mod merge_shards_input { /// A builder for [`MergeShardsInput`](crate::input::MergeShardsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) shard_to_merge: std::option::Option<std::string::String>, pub(crate) adjacent_shard_to_merge: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the stream for the merge.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The shard ID of the shard to combine with the adjacent shard for the /// merge.</p> pub fn shard_to_merge(mut self, input: impl Into<std::string::String>) -> Self { self.shard_to_merge = Some(input.into()); self } pub fn set_shard_to_merge( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.shard_to_merge = input; self } /// <p>The shard ID of the adjacent shard for the merge.</p> pub fn adjacent_shard_to_merge(mut self, input: impl Into<std::string::String>) -> Self { self.adjacent_shard_to_merge = Some(input.into()); self } pub fn set_adjacent_shard_to_merge( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.adjacent_shard_to_merge = input; self } /// Consumes the builder and constructs a [`MergeShardsInput`](crate::input::MergeShardsInput) pub fn build( self, ) -> std::result::Result<crate::input::MergeShardsInput, smithy_http::operation::BuildError> { Ok(crate::input::MergeShardsInput { stream_name: self.stream_name, shard_to_merge: self.shard_to_merge, adjacent_shard_to_merge: self.adjacent_shard_to_merge, }) } } } #[doc(hidden)] pub type MergeShardsInputOperationOutputAlias = crate::operation::MergeShards; #[doc(hidden)] pub type MergeShardsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl MergeShardsInput { /// Consumes the builder and constructs an Operation<[`MergeShards`](crate::operation::MergeShards)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::MergeShards, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_merge_shards(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::MergeShards::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "MergeShards", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.MergeShards"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`MergeShardsInput`](crate::input::MergeShardsInput) pub fn builder() -> crate::input::merge_shards_input::Builder { crate::input::merge_shards_input::Builder::default() } } /// See [`PutRecordInput`](crate::input::PutRecordInput) pub mod put_record_input { /// A builder for [`PutRecordInput`](crate::input::PutRecordInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) data: std::option::Option<smithy_types::Blob>, pub(crate) partition_key: std::option::Option<std::string::String>, pub(crate) explicit_hash_key: std::option::Option<std::string::String>, pub(crate) sequence_number_for_ordering: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the stream to put the data record into.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The data blob to put into the record, which is base64-encoded when the blob is /// serialized. When the data blob (the payload before base64-encoding) is added to the /// partition key size, the total size must not exceed the maximum record size (1 /// MiB).</p> pub fn data(mut self, input: smithy_types::Blob) -> Self { self.data = Some(input); self } pub fn set_data(mut self, input: std::option::Option<smithy_types::Blob>) -> Self { self.data = input; self } /// <p>Determines which shard in the stream the data record is assigned to. Partition keys /// are Unicode strings with a maximum length limit of 256 characters for each key. Amazon /// Kinesis Data Streams uses the partition key as input to a hash function that maps the /// partition key and associated data to a specific shard. Specifically, an MD5 hash /// function is used to map partition keys to 128-bit integer values and to map associated /// data records to shards. As a result of this hashing mechanism, all data records with the /// same partition key map to the same shard within the stream.</p> pub fn partition_key(mut self, input: impl Into<std::string::String>) -> Self { self.partition_key = Some(input.into()); self } pub fn set_partition_key( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.partition_key = input; self } /// <p>The hash value used to explicitly determine the shard the data record is assigned /// to by overriding the partition key hash.</p> pub fn explicit_hash_key(mut self, input: impl Into<std::string::String>) -> Self { self.explicit_hash_key = Some(input.into()); self } pub fn set_explicit_hash_key( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.explicit_hash_key = input; self } /// <p>Guarantees strictly increasing sequence numbers, for puts from the same client and /// to the same partition key. Usage: set the <code>SequenceNumberForOrdering</code> of /// record <i>n</i> to the sequence number of record <i>n-1</i> /// (as returned in the result when putting record <i>n-1</i>). If this /// parameter is not set, records are coarsely ordered based on arrival time.</p> pub fn sequence_number_for_ordering( mut self, input: impl Into<std::string::String>, ) -> Self { self.sequence_number_for_ordering = Some(input.into()); self } pub fn set_sequence_number_for_ordering( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.sequence_number_for_ordering = input; self } /// Consumes the builder and constructs a [`PutRecordInput`](crate::input::PutRecordInput) pub fn build( self, ) -> std::result::Result<crate::input::PutRecordInput, smithy_http::operation::BuildError> { Ok(crate::input::PutRecordInput { stream_name: self.stream_name, data: self.data, partition_key: self.partition_key, explicit_hash_key: self.explicit_hash_key, sequence_number_for_ordering: self.sequence_number_for_ordering, }) } } } #[doc(hidden)] pub type PutRecordInputOperationOutputAlias = crate::operation::PutRecord; #[doc(hidden)] pub type PutRecordInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutRecordInput { /// Consumes the builder and constructs an Operation<[`PutRecord`](crate::operation::PutRecord)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::PutRecord, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_put_record(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new(request, crate::operation::PutRecord::new()) .with_metadata(smithy_http::operation::Metadata::new( "PutRecord", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.PutRecord"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutRecordInput`](crate::input::PutRecordInput) pub fn builder() -> crate::input::put_record_input::Builder { crate::input::put_record_input::Builder::default() } } /// See [`PutRecordsInput`](crate::input::PutRecordsInput) pub mod put_records_input { /// A builder for [`PutRecordsInput`](crate::input::PutRecordsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) records: std::option::Option<std::vec::Vec<crate::model::PutRecordsRequestEntry>>, pub(crate) stream_name: std::option::Option<std::string::String>, } impl Builder { pub fn records(mut self, input: impl Into<crate::model::PutRecordsRequestEntry>) -> Self { let mut v = self.records.unwrap_or_default(); v.push(input.into()); self.records = Some(v); self } pub fn set_records( mut self, input: std::option::Option<std::vec::Vec<crate::model::PutRecordsRequestEntry>>, ) -> Self { self.records = input; self } /// <p>The stream name associated with the request.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// Consumes the builder and constructs a [`PutRecordsInput`](crate::input::PutRecordsInput) pub fn build( self, ) -> std::result::Result<crate::input::PutRecordsInput, smithy_http::operation::BuildError> { Ok(crate::input::PutRecordsInput { records: self.records, stream_name: self.stream_name, }) } } } #[doc(hidden)] pub type PutRecordsInputOperationOutputAlias = crate::operation::PutRecords; #[doc(hidden)] pub type PutRecordsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutRecordsInput { /// Consumes the builder and constructs an Operation<[`PutRecords`](crate::operation::PutRecords)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::PutRecords, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_put_records(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::PutRecords::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "PutRecords", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.PutRecords"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutRecordsInput`](crate::input::PutRecordsInput) pub fn builder() -> crate::input::put_records_input::Builder { crate::input::put_records_input::Builder::default() } } /// See [`RegisterStreamConsumerInput`](crate::input::RegisterStreamConsumerInput) pub mod register_stream_consumer_input { /// A builder for [`RegisterStreamConsumerInput`](crate::input::RegisterStreamConsumerInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_arn: std::option::Option<std::string::String>, pub(crate) consumer_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The ARN of the Kinesis data stream that you want to register the consumer with. For /// more info, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams">Amazon Resource Names (ARNs) and AWS Service Namespaces</a>.</p> pub fn stream_arn(mut self, input: impl Into<std::string::String>) -> Self { self.stream_arn = Some(input.into()); self } pub fn set_stream_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_arn = input; self } /// <p>For a given Kinesis data stream, each consumer must have a unique name. However, /// consumer names don't have to be unique across data streams.</p> pub fn consumer_name(mut self, input: impl Into<std::string::String>) -> Self { self.consumer_name = Some(input.into()); self } pub fn set_consumer_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.consumer_name = input; self } /// Consumes the builder and constructs a [`RegisterStreamConsumerInput`](crate::input::RegisterStreamConsumerInput) pub fn build( self, ) -> std::result::Result< crate::input::RegisterStreamConsumerInput, smithy_http::operation::BuildError, > { Ok(crate::input::RegisterStreamConsumerInput { stream_arn: self.stream_arn, consumer_name: self.consumer_name, }) } } } #[doc(hidden)] pub type RegisterStreamConsumerInputOperationOutputAlias = crate::operation::RegisterStreamConsumer; #[doc(hidden)] pub type RegisterStreamConsumerInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl RegisterStreamConsumerInput { /// Consumes the builder and constructs an Operation<[`RegisterStreamConsumer`](crate::operation::RegisterStreamConsumer)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::RegisterStreamConsumer, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_register_stream_consumer(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::RegisterStreamConsumer::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "RegisterStreamConsumer", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.RegisterStreamConsumer"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`RegisterStreamConsumerInput`](crate::input::RegisterStreamConsumerInput) pub fn builder() -> crate::input::register_stream_consumer_input::Builder { crate::input::register_stream_consumer_input::Builder::default() } } /// See [`RemoveTagsFromStreamInput`](crate::input::RemoveTagsFromStreamInput) pub mod remove_tags_from_stream_input { /// A builder for [`RemoveTagsFromStreamInput`](crate::input::RemoveTagsFromStreamInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) tag_keys: std::option::Option<std::vec::Vec<std::string::String>>, } impl Builder { /// <p>The name of the stream.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } pub fn tag_keys(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.tag_keys.unwrap_or_default(); v.push(input.into()); self.tag_keys = Some(v); self } pub fn set_tag_keys( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.tag_keys = input; self } /// Consumes the builder and constructs a [`RemoveTagsFromStreamInput`](crate::input::RemoveTagsFromStreamInput) pub fn build( self, ) -> std::result::Result< crate::input::RemoveTagsFromStreamInput, smithy_http::operation::BuildError, > { Ok(crate::input::RemoveTagsFromStreamInput { stream_name: self.stream_name, tag_keys: self.tag_keys, }) } } } #[doc(hidden)] pub type RemoveTagsFromStreamInputOperationOutputAlias = crate::operation::RemoveTagsFromStream; #[doc(hidden)] pub type RemoveTagsFromStreamInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl RemoveTagsFromStreamInput { /// Consumes the builder and constructs an Operation<[`RemoveTagsFromStream`](crate::operation::RemoveTagsFromStream)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::RemoveTagsFromStream, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_remove_tags_from_stream(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::RemoveTagsFromStream::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "RemoveTagsFromStream", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.RemoveTagsFromStream"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`RemoveTagsFromStreamInput`](crate::input::RemoveTagsFromStreamInput) pub fn builder() -> crate::input::remove_tags_from_stream_input::Builder { crate::input::remove_tags_from_stream_input::Builder::default() } } /// See [`SplitShardInput`](crate::input::SplitShardInput) pub mod split_shard_input { /// A builder for [`SplitShardInput`](crate::input::SplitShardInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) shard_to_split: std::option::Option<std::string::String>, pub(crate) new_starting_hash_key: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the stream for the shard split.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The shard ID of the shard to split.</p> pub fn shard_to_split(mut self, input: impl Into<std::string::String>) -> Self { self.shard_to_split = Some(input.into()); self } pub fn set_shard_to_split( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.shard_to_split = input; self } /// <p>A hash key value for the starting hash key of one of the child shards created by /// the split. The hash key range for a given shard constitutes a set of ordered contiguous /// positive integers. The value for <code>NewStartingHashKey</code> must be in the range of /// hash keys being mapped into the shard. The <code>NewStartingHashKey</code> hash key /// value and all higher hash key values in hash key range are distributed to one of the /// child shards. All the lower hash key values in the range are distributed to the other /// child shard.</p> pub fn new_starting_hash_key(mut self, input: impl Into<std::string::String>) -> Self { self.new_starting_hash_key = Some(input.into()); self } pub fn set_new_starting_hash_key( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.new_starting_hash_key = input; self } /// Consumes the builder and constructs a [`SplitShardInput`](crate::input::SplitShardInput) pub fn build( self, ) -> std::result::Result<crate::input::SplitShardInput, smithy_http::operation::BuildError> { Ok(crate::input::SplitShardInput { stream_name: self.stream_name, shard_to_split: self.shard_to_split, new_starting_hash_key: self.new_starting_hash_key, }) } } } #[doc(hidden)] pub type SplitShardInputOperationOutputAlias = crate::operation::SplitShard; #[doc(hidden)] pub type SplitShardInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl SplitShardInput { /// Consumes the builder and constructs an Operation<[`SplitShard`](crate::operation::SplitShard)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::SplitShard, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_split_shard(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::SplitShard::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "SplitShard", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.SplitShard"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`SplitShardInput`](crate::input::SplitShardInput) pub fn builder() -> crate::input::split_shard_input::Builder { crate::input::split_shard_input::Builder::default() } } /// See [`StartStreamEncryptionInput`](crate::input::StartStreamEncryptionInput) pub mod start_stream_encryption_input { /// A builder for [`StartStreamEncryptionInput`](crate::input::StartStreamEncryptionInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) encryption_type: std::option::Option<crate::model::EncryptionType>, pub(crate) key_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the stream for which to start encrypting records.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The encryption type to use. The only valid value is <code>KMS</code>.</p> pub fn encryption_type(mut self, input: crate::model::EncryptionType) -> Self { self.encryption_type = Some(input); self } pub fn set_encryption_type( mut self, input: std::option::Option<crate::model::EncryptionType>, ) -> Self { self.encryption_type = input; self } /// <p>The GUID for the customer-managed AWS KMS key to use for encryption. This value can /// be a globally unique identifier, a fully specified Amazon Resource Name (ARN) to either /// an alias or a key, or an alias name prefixed by "alias/".You can also use a master key /// owned by Kinesis Data Streams by specifying the alias /// <code>aws/kinesis</code>.</p> /// <ul> /// <li> /// <p>Key ARN example: /// <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code> /// </p> /// </li> /// <li> /// <p>Alias ARN example: /// <code>arn:aws:kms:us-east-1:123456789012:alias/MyAliasName</code> /// </p> /// </li> /// <li> /// <p>Globally unique key ID example: /// <code>12345678-1234-1234-1234-123456789012</code> /// </p> /// </li> /// <li> /// <p>Alias name example: <code>alias/MyAliasName</code> /// </p> /// </li> /// <li> /// <p>Master key owned by Kinesis Data Streams: /// <code>alias/aws/kinesis</code> /// </p> /// </li> /// </ul> pub fn key_id(mut self, input: impl Into<std::string::String>) -> Self { self.key_id = Some(input.into()); self } pub fn set_key_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.key_id = input; self } /// Consumes the builder and constructs a [`StartStreamEncryptionInput`](crate::input::StartStreamEncryptionInput) pub fn build( self, ) -> std::result::Result< crate::input::StartStreamEncryptionInput, smithy_http::operation::BuildError, > { Ok(crate::input::StartStreamEncryptionInput { stream_name: self.stream_name, encryption_type: self.encryption_type, key_id: self.key_id, }) } } } #[doc(hidden)] pub type StartStreamEncryptionInputOperationOutputAlias = crate::operation::StartStreamEncryption; #[doc(hidden)] pub type StartStreamEncryptionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl StartStreamEncryptionInput { /// Consumes the builder and constructs an Operation<[`StartStreamEncryption`](crate::operation::StartStreamEncryption)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::StartStreamEncryption, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_start_stream_encryption(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::StartStreamEncryption::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "StartStreamEncryption", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.StartStreamEncryption"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`StartStreamEncryptionInput`](crate::input::StartStreamEncryptionInput) pub fn builder() -> crate::input::start_stream_encryption_input::Builder { crate::input::start_stream_encryption_input::Builder::default() } } /// See [`StopStreamEncryptionInput`](crate::input::StopStreamEncryptionInput) pub mod stop_stream_encryption_input { /// A builder for [`StopStreamEncryptionInput`](crate::input::StopStreamEncryptionInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) encryption_type: std::option::Option<crate::model::EncryptionType>, pub(crate) key_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the stream on which to stop encrypting records.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The encryption type. The only valid value is <code>KMS</code>.</p> pub fn encryption_type(mut self, input: crate::model::EncryptionType) -> Self { self.encryption_type = Some(input); self } pub fn set_encryption_type( mut self, input: std::option::Option<crate::model::EncryptionType>, ) -> Self { self.encryption_type = input; self } /// <p>The GUID for the customer-managed AWS KMS key to use for encryption. This value can /// be a globally unique identifier, a fully specified Amazon Resource Name (ARN) to either /// an alias or a key, or an alias name prefixed by "alias/".You can also use a master key /// owned by Kinesis Data Streams by specifying the alias /// <code>aws/kinesis</code>.</p> /// <ul> /// <li> /// <p>Key ARN example: /// <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code> /// </p> /// </li> /// <li> /// <p>Alias ARN example: /// <code>arn:aws:kms:us-east-1:123456789012:alias/MyAliasName</code> /// </p> /// </li> /// <li> /// <p>Globally unique key ID example: /// <code>12345678-1234-1234-1234-123456789012</code> /// </p> /// </li> /// <li> /// <p>Alias name example: <code>alias/MyAliasName</code> /// </p> /// </li> /// <li> /// <p>Master key owned by Kinesis Data Streams: /// <code>alias/aws/kinesis</code> /// </p> /// </li> /// </ul> pub fn key_id(mut self, input: impl Into<std::string::String>) -> Self { self.key_id = Some(input.into()); self } pub fn set_key_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.key_id = input; self } /// Consumes the builder and constructs a [`StopStreamEncryptionInput`](crate::input::StopStreamEncryptionInput) pub fn build( self, ) -> std::result::Result< crate::input::StopStreamEncryptionInput, smithy_http::operation::BuildError, > { Ok(crate::input::StopStreamEncryptionInput { stream_name: self.stream_name, encryption_type: self.encryption_type, key_id: self.key_id, }) } } } #[doc(hidden)] pub type StopStreamEncryptionInputOperationOutputAlias = crate::operation::StopStreamEncryption; #[doc(hidden)] pub type StopStreamEncryptionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl StopStreamEncryptionInput { /// Consumes the builder and constructs an Operation<[`StopStreamEncryption`](crate::operation::StopStreamEncryption)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::StopStreamEncryption, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_stop_stream_encryption(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::StopStreamEncryption::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "StopStreamEncryption", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.StopStreamEncryption"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`StopStreamEncryptionInput`](crate::input::StopStreamEncryptionInput) pub fn builder() -> crate::input::stop_stream_encryption_input::Builder { crate::input::stop_stream_encryption_input::Builder::default() } } /// See [`UpdateShardCountInput`](crate::input::UpdateShardCountInput) pub mod update_shard_count_input { /// A builder for [`UpdateShardCountInput`](crate::input::UpdateShardCountInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) stream_name: std::option::Option<std::string::String>, pub(crate) target_shard_count: std::option::Option<i32>, pub(crate) scaling_type: std::option::Option<crate::model::ScalingType>, } impl Builder { /// <p>The name of the stream.</p> pub fn stream_name(mut self, input: impl Into<std::string::String>) -> Self { self.stream_name = Some(input.into()); self } pub fn set_stream_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.stream_name = input; self } /// <p>The new number of shards. This value has the following default limits. By default, /// you cannot do the following: </p> /// <ul> /// <li> /// <p>Set this value to more than double your current shard count for a /// stream.</p> /// </li> /// <li> /// <p>Set this value below half your current shard count for a stream.</p> /// </li> /// <li> /// <p>Set this value to more than 500 shards in a stream (the default limit for /// shard count per stream is 500 per account per region), unless you request a /// limit increase.</p> /// </li> /// <li> /// <p>Scale a stream with more than 500 shards down unless you set this value to /// less than 500 shards.</p> /// </li> /// </ul> pub fn target_shard_count(mut self, input: i32) -> Self { self.target_shard_count = Some(input); self } pub fn set_target_shard_count(mut self, input: std::option::Option<i32>) -> Self { self.target_shard_count = input; self } /// <p>The scaling type. Uniform scaling creates shards of equal size.</p> pub fn scaling_type(mut self, input: crate::model::ScalingType) -> Self { self.scaling_type = Some(input); self } pub fn set_scaling_type( mut self, input: std::option::Option<crate::model::ScalingType>, ) -> Self { self.scaling_type = input; self } /// Consumes the builder and constructs a [`UpdateShardCountInput`](crate::input::UpdateShardCountInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdateShardCountInput, smithy_http::operation::BuildError, > { Ok(crate::input::UpdateShardCountInput { stream_name: self.stream_name, target_shard_count: self.target_shard_count, scaling_type: self.scaling_type, }) } } } #[doc(hidden)] pub type UpdateShardCountInputOperationOutputAlias = crate::operation::UpdateShardCount; #[doc(hidden)] pub type UpdateShardCountInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdateShardCountInput { /// Consumes the builder and constructs an Operation<[`UpdateShardCount`](crate::operation::UpdateShardCount)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::UpdateShardCount, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_update_shard_count(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request .config_mut() .insert(aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), )); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.config_mut().insert(signing_config); request .config_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.config_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.config_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.config_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::UpdateShardCount::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "UpdateShardCount", "kinesis", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.UpdateShardCount"); self.update_http_builder(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdateShardCountInput`](crate::input::UpdateShardCountInput) pub fn builder() -> crate::input::update_shard_count_input::Builder { crate::input::update_shard_count_input::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateShardCountInput { /// <p>The name of the stream.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The new number of shards. This value has the following default limits. By default, /// you cannot do the following: </p> /// <ul> /// <li> /// <p>Set this value to more than double your current shard count for a /// stream.</p> /// </li> /// <li> /// <p>Set this value below half your current shard count for a stream.</p> /// </li> /// <li> /// <p>Set this value to more than 500 shards in a stream (the default limit for /// shard count per stream is 500 per account per region), unless you request a /// limit increase.</p> /// </li> /// <li> /// <p>Scale a stream with more than 500 shards down unless you set this value to /// less than 500 shards.</p> /// </li> /// </ul> pub target_shard_count: std::option::Option<i32>, /// <p>The scaling type. Uniform scaling creates shards of equal size.</p> pub scaling_type: std::option::Option<crate::model::ScalingType>, } impl std::fmt::Debug for UpdateShardCountInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateShardCountInput"); formatter.field("stream_name", &self.stream_name); formatter.field("target_shard_count", &self.target_shard_count); formatter.field("scaling_type", &self.scaling_type); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct StopStreamEncryptionInput { /// <p>The name of the stream on which to stop encrypting records.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The encryption type. The only valid value is <code>KMS</code>.</p> pub encryption_type: std::option::Option<crate::model::EncryptionType>, /// <p>The GUID for the customer-managed AWS KMS key to use for encryption. This value can /// be a globally unique identifier, a fully specified Amazon Resource Name (ARN) to either /// an alias or a key, or an alias name prefixed by "alias/".You can also use a master key /// owned by Kinesis Data Streams by specifying the alias /// <code>aws/kinesis</code>.</p> /// <ul> /// <li> /// <p>Key ARN example: /// <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code> /// </p> /// </li> /// <li> /// <p>Alias ARN example: /// <code>arn:aws:kms:us-east-1:123456789012:alias/MyAliasName</code> /// </p> /// </li> /// <li> /// <p>Globally unique key ID example: /// <code>12345678-1234-1234-1234-123456789012</code> /// </p> /// </li> /// <li> /// <p>Alias name example: <code>alias/MyAliasName</code> /// </p> /// </li> /// <li> /// <p>Master key owned by Kinesis Data Streams: /// <code>alias/aws/kinesis</code> /// </p> /// </li> /// </ul> pub key_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for StopStreamEncryptionInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("StopStreamEncryptionInput"); formatter.field("stream_name", &self.stream_name); formatter.field("encryption_type", &self.encryption_type); formatter.field("key_id", &self.key_id); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct StartStreamEncryptionInput { /// <p>The name of the stream for which to start encrypting records.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The encryption type to use. The only valid value is <code>KMS</code>.</p> pub encryption_type: std::option::Option<crate::model::EncryptionType>, /// <p>The GUID for the customer-managed AWS KMS key to use for encryption. This value can /// be a globally unique identifier, a fully specified Amazon Resource Name (ARN) to either /// an alias or a key, or an alias name prefixed by "alias/".You can also use a master key /// owned by Kinesis Data Streams by specifying the alias /// <code>aws/kinesis</code>.</p> /// <ul> /// <li> /// <p>Key ARN example: /// <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code> /// </p> /// </li> /// <li> /// <p>Alias ARN example: /// <code>arn:aws:kms:us-east-1:123456789012:alias/MyAliasName</code> /// </p> /// </li> /// <li> /// <p>Globally unique key ID example: /// <code>12345678-1234-1234-1234-123456789012</code> /// </p> /// </li> /// <li> /// <p>Alias name example: <code>alias/MyAliasName</code> /// </p> /// </li> /// <li> /// <p>Master key owned by Kinesis Data Streams: /// <code>alias/aws/kinesis</code> /// </p> /// </li> /// </ul> pub key_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for StartStreamEncryptionInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("StartStreamEncryptionInput"); formatter.field("stream_name", &self.stream_name); formatter.field("encryption_type", &self.encryption_type); formatter.field("key_id", &self.key_id); formatter.finish() } } /// <p>Represents the input for <code>SplitShard</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SplitShardInput { /// <p>The name of the stream for the shard split.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The shard ID of the shard to split.</p> pub shard_to_split: std::option::Option<std::string::String>, /// <p>A hash key value for the starting hash key of one of the child shards created by /// the split. The hash key range for a given shard constitutes a set of ordered contiguous /// positive integers. The value for <code>NewStartingHashKey</code> must be in the range of /// hash keys being mapped into the shard. The <code>NewStartingHashKey</code> hash key /// value and all higher hash key values in hash key range are distributed to one of the /// child shards. All the lower hash key values in the range are distributed to the other /// child shard.</p> pub new_starting_hash_key: std::option::Option<std::string::String>, } impl std::fmt::Debug for SplitShardInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SplitShardInput"); formatter.field("stream_name", &self.stream_name); formatter.field("shard_to_split", &self.shard_to_split); formatter.field("new_starting_hash_key", &self.new_starting_hash_key); formatter.finish() } } /// <p>Represents the input for <code>RemoveTagsFromStream</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RemoveTagsFromStreamInput { /// <p>The name of the stream.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>A list of tag keys. Each corresponding tag is removed from the stream.</p> pub tag_keys: std::option::Option<std::vec::Vec<std::string::String>>, } impl std::fmt::Debug for RemoveTagsFromStreamInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RemoveTagsFromStreamInput"); formatter.field("stream_name", &self.stream_name); formatter.field("tag_keys", &self.tag_keys); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RegisterStreamConsumerInput { /// <p>The ARN of the Kinesis data stream that you want to register the consumer with. For /// more info, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams">Amazon Resource Names (ARNs) and AWS Service Namespaces</a>.</p> pub stream_arn: std::option::Option<std::string::String>, /// <p>For a given Kinesis data stream, each consumer must have a unique name. However, /// consumer names don't have to be unique across data streams.</p> pub consumer_name: std::option::Option<std::string::String>, } impl std::fmt::Debug for RegisterStreamConsumerInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RegisterStreamConsumerInput"); formatter.field("stream_arn", &self.stream_arn); formatter.field("consumer_name", &self.consumer_name); formatter.finish() } } /// <p>A <code>PutRecords</code> request.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutRecordsInput { /// <p>The records associated with the request.</p> pub records: std::option::Option<std::vec::Vec<crate::model::PutRecordsRequestEntry>>, /// <p>The stream name associated with the request.</p> pub stream_name: std::option::Option<std::string::String>, } impl std::fmt::Debug for PutRecordsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutRecordsInput"); formatter.field("records", &self.records); formatter.field("stream_name", &self.stream_name); formatter.finish() } } /// <p>Represents the input for <code>PutRecord</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutRecordInput { /// <p>The name of the stream to put the data record into.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The data blob to put into the record, which is base64-encoded when the blob is /// serialized. When the data blob (the payload before base64-encoding) is added to the /// partition key size, the total size must not exceed the maximum record size (1 /// MiB).</p> pub data: std::option::Option<smithy_types::Blob>, /// <p>Determines which shard in the stream the data record is assigned to. Partition keys /// are Unicode strings with a maximum length limit of 256 characters for each key. Amazon /// Kinesis Data Streams uses the partition key as input to a hash function that maps the /// partition key and associated data to a specific shard. Specifically, an MD5 hash /// function is used to map partition keys to 128-bit integer values and to map associated /// data records to shards. As a result of this hashing mechanism, all data records with the /// same partition key map to the same shard within the stream.</p> pub partition_key: std::option::Option<std::string::String>, /// <p>The hash value used to explicitly determine the shard the data record is assigned /// to by overriding the partition key hash.</p> pub explicit_hash_key: std::option::Option<std::string::String>, /// <p>Guarantees strictly increasing sequence numbers, for puts from the same client and /// to the same partition key. Usage: set the <code>SequenceNumberForOrdering</code> of /// record <i>n</i> to the sequence number of record <i>n-1</i> /// (as returned in the result when putting record <i>n-1</i>). If this /// parameter is not set, records are coarsely ordered based on arrival time.</p> pub sequence_number_for_ordering: std::option::Option<std::string::String>, } impl std::fmt::Debug for PutRecordInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutRecordInput"); formatter.field("stream_name", &self.stream_name); formatter.field("data", &self.data); formatter.field("partition_key", &self.partition_key); formatter.field("explicit_hash_key", &self.explicit_hash_key); formatter.field( "sequence_number_for_ordering", &self.sequence_number_for_ordering, ); formatter.finish() } } /// <p>Represents the input for <code>MergeShards</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct MergeShardsInput { /// <p>The name of the stream for the merge.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The shard ID of the shard to combine with the adjacent shard for the /// merge.</p> pub shard_to_merge: std::option::Option<std::string::String>, /// <p>The shard ID of the adjacent shard for the merge.</p> pub adjacent_shard_to_merge: std::option::Option<std::string::String>, } impl std::fmt::Debug for MergeShardsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("MergeShardsInput"); formatter.field("stream_name", &self.stream_name); formatter.field("shard_to_merge", &self.shard_to_merge); formatter.field("adjacent_shard_to_merge", &self.adjacent_shard_to_merge); formatter.finish() } } /// <p>Represents the input for <code>ListTagsForStream</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListTagsForStreamInput { /// <p>The name of the stream.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The key to use as the starting point for the list of tags. If this parameter is /// set, <code>ListTagsForStream</code> gets all tags that occur after /// <code>ExclusiveStartTagKey</code>. </p> pub exclusive_start_tag_key: std::option::Option<std::string::String>, /// <p>The number of tags to return. If this number is less than the total number of tags /// associated with the stream, <code>HasMoreTags</code> is set to <code>true</code>. To /// list additional tags, set <code>ExclusiveStartTagKey</code> to the last key in the /// response.</p> pub limit: std::option::Option<i32>, } impl std::fmt::Debug for ListTagsForStreamInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListTagsForStreamInput"); formatter.field("stream_name", &self.stream_name); formatter.field("exclusive_start_tag_key", &self.exclusive_start_tag_key); formatter.field("limit", &self.limit); formatter.finish() } } /// <p>Represents the input for <code>ListStreams</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListStreamsInput { /// <p>The maximum number of streams to list.</p> pub limit: std::option::Option<i32>, /// <p>The name of the stream to start the list with.</p> pub exclusive_start_stream_name: std::option::Option<std::string::String>, } impl std::fmt::Debug for ListStreamsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListStreamsInput"); formatter.field("limit", &self.limit); formatter.field( "exclusive_start_stream_name", &self.exclusive_start_stream_name, ); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListStreamConsumersInput { /// <p>The ARN of the Kinesis data stream for which you want to list the registered /// consumers. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams">Amazon Resource Names (ARNs) and AWS Service Namespaces</a>.</p> pub stream_arn: std::option::Option<std::string::String>, /// <p>When the number of consumers that are registered with the data stream is greater than /// the default value for the <code>MaxResults</code> parameter, or if you explicitly /// specify a value for <code>MaxResults</code> that is less than the number of consumers /// that are registered with the data stream, the response includes a pagination token named /// <code>NextToken</code>. You can specify this <code>NextToken</code> value in a /// subsequent call to <code>ListStreamConsumers</code> to list the next set of registered /// consumers.</p> /// <p>Don't specify <code>StreamName</code> or <code>StreamCreationTimestamp</code> if you /// specify <code>NextToken</code> because the latter unambiguously identifies the /// stream.</p> /// <p>You can optionally specify a value for the <code>MaxResults</code> parameter when you /// specify <code>NextToken</code>. If you specify a <code>MaxResults</code> value that is /// less than the number of consumers that the operation returns if you don't specify /// <code>MaxResults</code>, the response will contain a new <code>NextToken</code> /// value. You can use the new <code>NextToken</code> value in a subsequent call to the /// <code>ListStreamConsumers</code> operation to list the next set of consumers.</p> /// <important> /// <p>Tokens expire after 300 seconds. When you obtain a value for /// <code>NextToken</code> in the response to a call to /// <code>ListStreamConsumers</code>, you have 300 seconds to use that value. If you /// specify an expired token in a call to <code>ListStreamConsumers</code>, you get /// <code>ExpiredNextTokenException</code>.</p> /// </important> pub next_token: std::option::Option<std::string::String>, /// <p>The maximum number of consumers that you want a single call of /// <code>ListStreamConsumers</code> to return.</p> pub max_results: std::option::Option<i32>, /// <p>Specify this input parameter to distinguish data streams that have the same name. For /// example, if you create a data stream and then delete it, and you later create another /// data stream with the same name, you can use this input parameter to specify which of the /// two streams you want to list the consumers for. </p> /// <p>You can't specify this parameter if you specify the NextToken parameter. </p> pub stream_creation_timestamp: std::option::Option<smithy_types::Instant>, } impl std::fmt::Debug for ListStreamConsumersInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListStreamConsumersInput"); formatter.field("stream_arn", &self.stream_arn); formatter.field("next_token", &self.next_token); formatter.field("max_results", &self.max_results); formatter.field("stream_creation_timestamp", &self.stream_creation_timestamp); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListShardsInput { /// <p>The name of the data stream whose shards you want to list. </p> /// <p>You cannot specify this parameter if you specify the <code>NextToken</code> /// parameter.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>When the number of shards in the data stream is greater than the default value for /// the <code>MaxResults</code> parameter, or if you explicitly specify a value for /// <code>MaxResults</code> that is less than the number of shards in the data stream, /// the response includes a pagination token named <code>NextToken</code>. You can specify /// this <code>NextToken</code> value in a subsequent call to <code>ListShards</code> to /// list the next set of shards.</p> /// <p>Don't specify <code>StreamName</code> or <code>StreamCreationTimestamp</code> if /// you specify <code>NextToken</code> because the latter unambiguously identifies the /// stream.</p> /// <p>You can optionally specify a value for the <code>MaxResults</code> parameter when /// you specify <code>NextToken</code>. If you specify a <code>MaxResults</code> value that /// is less than the number of shards that the operation returns if you don't specify /// <code>MaxResults</code>, the response will contain a new <code>NextToken</code> /// value. You can use the new <code>NextToken</code> value in a subsequent call to the /// <code>ListShards</code> operation.</p> /// <important> /// <p>Tokens expire after 300 seconds. When you obtain a value for /// <code>NextToken</code> in the response to a call to <code>ListShards</code>, you /// have 300 seconds to use that value. If you specify an expired token in a call to /// <code>ListShards</code>, you get /// <code>ExpiredNextTokenException</code>.</p> /// </important> pub next_token: std::option::Option<std::string::String>, /// <p>Specify this parameter to indicate that you want to list the shards starting with /// the shard whose ID immediately follows <code>ExclusiveStartShardId</code>.</p> /// <p>If you don't specify this parameter, the default behavior is for /// <code>ListShards</code> to list the shards starting with the first one in the /// stream.</p> /// <p>You cannot specify this parameter if you specify <code>NextToken</code>.</p> pub exclusive_start_shard_id: std::option::Option<std::string::String>, /// <p>The maximum number of shards to return in a single call to <code>ListShards</code>. /// The minimum value you can specify for this parameter is 1, and the maximum is 10,000, /// which is also the default.</p> /// <p>When the number of shards to be listed is greater than the value of /// <code>MaxResults</code>, the response contains a <code>NextToken</code> value that /// you can use in a subsequent call to <code>ListShards</code> to list the next set of /// shards.</p> pub max_results: std::option::Option<i32>, /// <p>Specify this input parameter to distinguish data streams that have the same name. /// For example, if you create a data stream and then delete it, and you later create /// another data stream with the same name, you can use this input parameter to specify /// which of the two streams you want to list the shards for.</p> /// <p>You cannot specify this parameter if you specify the <code>NextToken</code> /// parameter.</p> pub stream_creation_timestamp: std::option::Option<smithy_types::Instant>, pub shard_filter: std::option::Option<crate::model::ShardFilter>, } impl std::fmt::Debug for ListShardsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListShardsInput"); formatter.field("stream_name", &self.stream_name); formatter.field("next_token", &self.next_token); formatter.field("exclusive_start_shard_id", &self.exclusive_start_shard_id); formatter.field("max_results", &self.max_results); formatter.field("stream_creation_timestamp", &self.stream_creation_timestamp); formatter.field("shard_filter", &self.shard_filter); formatter.finish() } } /// <p>Represents the input for <a>IncreaseStreamRetentionPeriod</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct IncreaseStreamRetentionPeriodInput { /// <p>The name of the stream to modify.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The new retention period of the stream, in hours. Must be more than the current /// retention period.</p> pub retention_period_hours: std::option::Option<i32>, } impl std::fmt::Debug for IncreaseStreamRetentionPeriodInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("IncreaseStreamRetentionPeriodInput"); formatter.field("stream_name", &self.stream_name); formatter.field("retention_period_hours", &self.retention_period_hours); formatter.finish() } } /// <p>Represents the input for <code>GetShardIterator</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetShardIteratorInput { /// <p>The name of the Amazon Kinesis data stream.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The shard ID of the Kinesis Data Streams shard to get the iterator for.</p> pub shard_id: std::option::Option<std::string::String>, /// <p>Determines how the shard iterator is used to start reading data records from the /// shard.</p> /// <p>The following are the valid Amazon Kinesis shard iterator types:</p> /// <ul> /// <li> /// <p>AT_SEQUENCE_NUMBER - Start reading from the position denoted by a specific /// sequence number, provided in the value /// <code>StartingSequenceNumber</code>.</p> /// </li> /// <li> /// <p>AFTER_SEQUENCE_NUMBER - Start reading right after the position denoted by a /// specific sequence number, provided in the value /// <code>StartingSequenceNumber</code>.</p> /// </li> /// <li> /// <p>AT_TIMESTAMP - Start reading from the position denoted by a specific time /// stamp, provided in the value <code>Timestamp</code>.</p> /// </li> /// <li> /// <p>TRIM_HORIZON - Start reading at the last untrimmed record in the shard in /// the system, which is the oldest data record in the shard.</p> /// </li> /// <li> /// <p>LATEST - Start reading just after the most recent record in the shard, so /// that you always read the most recent data in the shard.</p> /// </li> /// </ul> pub shard_iterator_type: std::option::Option<crate::model::ShardIteratorType>, /// <p>The sequence number of the data record in the shard from which to start reading. /// Used with shard iterator type AT_SEQUENCE_NUMBER and AFTER_SEQUENCE_NUMBER.</p> pub starting_sequence_number: std::option::Option<std::string::String>, /// <p>The time stamp of the data record from which to start reading. Used with shard /// iterator type AT_TIMESTAMP. A time stamp is the Unix epoch date with precision in /// milliseconds. For example, <code>2016-04-04T19:58:46.480-00:00</code> or /// <code>1459799926.480</code>. If a record with this exact time stamp does not exist, /// the iterator returned is for the next (later) record. If the time stamp is older than /// the current trim horizon, the iterator returned is for the oldest untrimmed data record /// (TRIM_HORIZON).</p> pub timestamp: std::option::Option<smithy_types::Instant>, } impl std::fmt::Debug for GetShardIteratorInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetShardIteratorInput"); formatter.field("stream_name", &self.stream_name); formatter.field("shard_id", &self.shard_id); formatter.field("shard_iterator_type", &self.shard_iterator_type); formatter.field("starting_sequence_number", &self.starting_sequence_number); formatter.field("timestamp", &self.timestamp); formatter.finish() } } /// <p>Represents the input for <a>GetRecords</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetRecordsInput { /// <p>The position in the shard from which you want to start sequentially reading data /// records. A shard iterator specifies this position using the sequence number of a data /// record in the shard.</p> pub shard_iterator: std::option::Option<std::string::String>, /// <p>The maximum number of records to return. Specify a value of up to 10,000. If you /// specify a value that is greater than 10,000, <a>GetRecords</a> throws /// <code>InvalidArgumentException</code>. The default value is 10,000.</p> pub limit: std::option::Option<i32>, } impl std::fmt::Debug for GetRecordsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetRecordsInput"); formatter.field("shard_iterator", &self.shard_iterator); formatter.field("limit", &self.limit); formatter.finish() } } /// <p>Represents the input for <a>EnableEnhancedMonitoring</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct EnableEnhancedMonitoringInput { /// <p>The name of the stream for which to enable enhanced monitoring.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>List of shard-level metrics to enable.</p> /// <p>The following are the valid shard-level metrics. The value "<code>ALL</code>" /// enables every metric.</p> /// <ul> /// <li> /// <p> /// <code>IncomingBytes</code> /// </p> /// </li> /// <li> /// <p> /// <code>IncomingRecords</code> /// </p> /// </li> /// <li> /// <p> /// <code>OutgoingBytes</code> /// </p> /// </li> /// <li> /// <p> /// <code>OutgoingRecords</code> /// </p> /// </li> /// <li> /// <p> /// <code>WriteProvisionedThroughputExceeded</code> /// </p> /// </li> /// <li> /// <p> /// <code>ReadProvisionedThroughputExceeded</code> /// </p> /// </li> /// <li> /// <p> /// <code>IteratorAgeMilliseconds</code> /// </p> /// </li> /// <li> /// <p> /// <code>ALL</code> /// </p> /// </li> /// </ul> /// <p>For more information, see <a href="https://docs.aws.amazon.com/kinesis/latest/dev/monitoring-with-cloudwatch.html">Monitoring the Amazon /// Kinesis Data Streams Service with Amazon CloudWatch</a> in the <i>Amazon /// Kinesis Data Streams Developer Guide</i>.</p> pub shard_level_metrics: std::option::Option<std::vec::Vec<crate::model::MetricsName>>, } impl std::fmt::Debug for EnableEnhancedMonitoringInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("EnableEnhancedMonitoringInput"); formatter.field("stream_name", &self.stream_name); formatter.field("shard_level_metrics", &self.shard_level_metrics); formatter.finish() } } /// <p>Represents the input for <a>DisableEnhancedMonitoring</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DisableEnhancedMonitoringInput { /// <p>The name of the Kinesis data stream for which to disable enhanced /// monitoring.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>List of shard-level metrics to disable.</p> /// <p>The following are the valid shard-level metrics. The value "<code>ALL</code>" /// disables every metric.</p> /// <ul> /// <li> /// <p> /// <code>IncomingBytes</code> /// </p> /// </li> /// <li> /// <p> /// <code>IncomingRecords</code> /// </p> /// </li> /// <li> /// <p> /// <code>OutgoingBytes</code> /// </p> /// </li> /// <li> /// <p> /// <code>OutgoingRecords</code> /// </p> /// </li> /// <li> /// <p> /// <code>WriteProvisionedThroughputExceeded</code> /// </p> /// </li> /// <li> /// <p> /// <code>ReadProvisionedThroughputExceeded</code> /// </p> /// </li> /// <li> /// <p> /// <code>IteratorAgeMilliseconds</code> /// </p> /// </li> /// <li> /// <p> /// <code>ALL</code> /// </p> /// </li> /// </ul> /// <p>For more information, see <a href="https://docs.aws.amazon.com/kinesis/latest/dev/monitoring-with-cloudwatch.html">Monitoring the Amazon /// Kinesis Data Streams Service with Amazon CloudWatch</a> in the <i>Amazon /// Kinesis Data Streams Developer Guide</i>.</p> pub shard_level_metrics: std::option::Option<std::vec::Vec<crate::model::MetricsName>>, } impl std::fmt::Debug for DisableEnhancedMonitoringInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DisableEnhancedMonitoringInput"); formatter.field("stream_name", &self.stream_name); formatter.field("shard_level_metrics", &self.shard_level_metrics); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeStreamSummaryInput { /// <p>The name of the stream to describe.</p> pub stream_name: std::option::Option<std::string::String>, } impl std::fmt::Debug for DescribeStreamSummaryInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeStreamSummaryInput"); formatter.field("stream_name", &self.stream_name); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeStreamConsumerInput { /// <p>The ARN of the Kinesis data stream that the consumer is registered with. For more /// information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams">Amazon Resource Names (ARNs) and AWS Service Namespaces</a>.</p> pub stream_arn: std::option::Option<std::string::String>, /// <p>The name that you gave to the consumer.</p> pub consumer_name: std::option::Option<std::string::String>, /// <p>The ARN returned by Kinesis Data Streams when you registered the consumer.</p> pub consumer_arn: std::option::Option<std::string::String>, } impl std::fmt::Debug for DescribeStreamConsumerInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeStreamConsumerInput"); formatter.field("stream_arn", &self.stream_arn); formatter.field("consumer_name", &self.consumer_name); formatter.field("consumer_arn", &self.consumer_arn); formatter.finish() } } /// <p>Represents the input for <code>DescribeStream</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeStreamInput { /// <p>The name of the stream to describe.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The maximum number of shards to return in a single call. The default value is 100. /// If you specify a value greater than 100, at most 100 shards are returned.</p> pub limit: std::option::Option<i32>, /// <p>The shard ID of the shard to start with.</p> pub exclusive_start_shard_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for DescribeStreamInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeStreamInput"); formatter.field("stream_name", &self.stream_name); formatter.field("limit", &self.limit); formatter.field("exclusive_start_shard_id", &self.exclusive_start_shard_id); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeLimitsInput {} impl std::fmt::Debug for DescribeLimitsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeLimitsInput"); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeregisterStreamConsumerInput { /// <p>The ARN of the Kinesis data stream that the consumer is registered with. For more /// information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams">Amazon Resource Names (ARNs) and AWS Service Namespaces</a>.</p> pub stream_arn: std::option::Option<std::string::String>, /// <p>The name that you gave to the consumer.</p> pub consumer_name: std::option::Option<std::string::String>, /// <p>The ARN returned by Kinesis Data Streams when you registered the consumer. If you /// don't know the ARN of the consumer that you want to deregister, you can use the /// ListStreamConsumers operation to get a list of the descriptions of all the consumers /// that are currently registered with a given data stream. The description of a consumer /// contains its ARN.</p> pub consumer_arn: std::option::Option<std::string::String>, } impl std::fmt::Debug for DeregisterStreamConsumerInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeregisterStreamConsumerInput"); formatter.field("stream_arn", &self.stream_arn); formatter.field("consumer_name", &self.consumer_name); formatter.field("consumer_arn", &self.consumer_arn); formatter.finish() } } /// <p>Represents the input for <a>DeleteStream</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteStreamInput { /// <p>The name of the stream to delete.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>If this parameter is unset (<code>null</code>) or if you set it to <code>false</code>, /// and the stream has registered consumers, the call to <code>DeleteStream</code> fails /// with a <code>ResourceInUseException</code>. </p> pub enforce_consumer_deletion: std::option::Option<bool>, } impl std::fmt::Debug for DeleteStreamInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteStreamInput"); formatter.field("stream_name", &self.stream_name); formatter.field("enforce_consumer_deletion", &self.enforce_consumer_deletion); formatter.finish() } } /// <p>Represents the input for <a>DecreaseStreamRetentionPeriod</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DecreaseStreamRetentionPeriodInput { /// <p>The name of the stream to modify.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The new retention period of the stream, in hours. Must be less than the current /// retention period.</p> pub retention_period_hours: std::option::Option<i32>, } impl std::fmt::Debug for DecreaseStreamRetentionPeriodInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DecreaseStreamRetentionPeriodInput"); formatter.field("stream_name", &self.stream_name); formatter.field("retention_period_hours", &self.retention_period_hours); formatter.finish() } } /// <p>Represents the input for <code>CreateStream</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateStreamInput { /// <p>A name to identify the stream. The stream name is scoped to the AWS account used by /// the application that creates the stream. It is also scoped by AWS Region. That is, two /// streams in two different AWS accounts can have the same name. Two streams in the same /// AWS account but in two different Regions can also have the same name.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>The number of shards that the stream will use. The throughput of the stream is a /// function of the number of shards; more shards are required for greater provisioned /// throughput.</p> pub shard_count: std::option::Option<i32>, } impl std::fmt::Debug for CreateStreamInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateStreamInput"); formatter.field("stream_name", &self.stream_name); formatter.field("shard_count", &self.shard_count); formatter.finish() } } /// <p>Represents the input for <code>AddTagsToStream</code>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct AddTagsToStreamInput { /// <p>The name of the stream.</p> pub stream_name: std::option::Option<std::string::String>, /// <p>A set of up to 10 key-value pairs to use to create the tags.</p> pub tags: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl std::fmt::Debug for AddTagsToStreamInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("AddTagsToStreamInput"); formatter.field("stream_name", &self.stream_name); formatter.field("tags", &self.tags); formatter.finish() } }
{ let builder = http::request::Builder::new(); let builder = builder.header("Content-Type", "application/x-amz-json-1.1"); let builder = builder.header("x-amz-target", "Kinesis_20131202.ListStreamConsumers"); self.update_http_builder(builder) }
dice-one-icon.js
(function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports', '../createIcon'], factory); } else if (typeof exports !== "undefined") { factory(exports, require('../createIcon')); } else { var mod = { exports: {} }; factory(mod.exports, global.createIcon); global.diceOneIcon = mod.exports; } })(this, function (exports, _createIcon) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createIcon2 = _interopRequireDefault(_createIcon); function
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DiceOneIcon = (0, _createIcon2.default)({ name: 'DiceOneIcon', height: 512, width: 448, svgPath: 'M384 32H64C28.65 32 0 60.65 0 96v320c0 35.35 28.65 64 64 64h320c35.35 0 64-28.65 64-64V96c0-35.35-28.65-64-64-64zM224 288c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32z', yOffset: '', xOffset: '', transform: '' }); /* This file is generated by createIcons.js any changes will be lost. */ exports.default = DiceOneIcon; });
_interopRequireDefault
test_functions.py
import math import operator from datetime import date, datetime from operator import methodcaller import pandas as pd import pandas.testing as tm import pytest from pytest import param import ibis import ibis.expr.datatypes as dt import ibis.expr.types as ir from ibis import literal as L clickhouse_driver = pytest.importorskip('clickhouse_driver') pytestmark = pytest.mark.clickhouse @pytest.mark.parametrize( ('to_type', 'expected'), [ ('int8', 'CAST(`double_col` AS Int8)'), ('int16', 'CAST(`double_col` AS Int16)'), ('float', 'CAST(`double_col` AS Float32)'), # alltypes.double_col is non-nullable (dt.Double(nullable=False), '`double_col`'), ], ) def test_cast_double_col(alltypes, translate, to_type, expected): expr = alltypes.double_col.cast(to_type) assert translate(expr) == expected @pytest.mark.parametrize( ('to_type', 'expected'), [ ('int8', 'CAST(`string_col` AS Int8)'), ('int16', 'CAST(`string_col` AS Int16)'), (dt.String(nullable=False), '`string_col`'), ('timestamp', 'CAST(`string_col` AS DateTime)'), ('date', 'CAST(`string_col` AS Date)'), ], ) def test_cast_string_col(alltypes, translate, to_type, expected): expr = alltypes.string_col.cast(to_type) assert translate(expr) == expected @pytest.mark.xfail( raises=AssertionError, reason='Clickhouse doesn\'t have decimal type' ) def test_decimal_cast(): assert False @pytest.mark.parametrize( 'column', [ 'index', 'Unnamed: 0', 'id', 'bool_col', 'tinyint_col', 'smallint_col', 'int_col', 'bigint_col', 'float_col', 'double_col', 'date_string_col', 'string_col', 'timestamp_col', 'year', 'month', ], ) def test_noop_cast(alltypes, translate, column): col = alltypes[column] result = col.cast(col.type()) assert result.equals(col) assert translate(result) == '`{}`'.format(column) def test_timestamp_cast_noop(alltypes, translate): target = dt.Timestamp(nullable=False) result1 = alltypes.timestamp_col.cast(target) result2 = alltypes.int_col.cast(target) assert isinstance(result1, ir.TimestampColumn) assert isinstance(result2, ir.TimestampColumn) assert translate(result1) == '`timestamp_col`' assert translate(result2) == 'CAST(`int_col` AS DateTime)' def test_timestamp_now(con, translate): expr = ibis.now() # now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') assert translate(expr) == 'now()' # assert con.execute(expr) == now @pytest.mark.parametrize( ('unit', 'expected'), [ ('y', '2009-01-01'), param('m', '2009-05-01', marks=pytest.mark.xfail), ('d', '2009-05-17'), ('w', '2009-05-11'), ('h', '2009-05-17 12:00:00'), ('minute', '2009-05-17 12:34:00'), ], ) def test_timestamp_truncate(con, translate, unit, expected): stamp = ibis.timestamp('2009-05-17 12:34:56') expr = stamp.truncate(unit) assert con.execute(expr) == pd.Timestamp(expected) @pytest.mark.parametrize( ('func', 'expected'), [ (methodcaller('year'), 2015), (methodcaller('month'), 9), (methodcaller('day'), 1), (methodcaller('hour'), 14), (methodcaller('minute'), 48), (methodcaller('second'), 5), ], ) def test_simple_datetime_operations(con, func, expected): value = ibis.timestamp('2015-09-01 14:48:05.359') with pytest.raises(ValueError): con.execute(func(value)) value = ibis.timestamp('2015-09-01 14:48:05') con.execute(func(value)) == expected @pytest.mark.parametrize(('value', 'expected'), [(0, None), (5.5, 5.5)]) def test_nullifzero(con, value, expected): result = con.execute(L(value).nullifzero()) if expected is None: assert pd.isnull(result) else: assert result == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L(None).isnull(), True), (L(1).isnull(), False), (L(None).notnull(), False), (L(1).notnull(), True), ], ) def test_isnull_notnull(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (ibis.coalesce(5, None, 4), 5), (ibis.coalesce(ibis.NA, 4, ibis.NA), 4), (ibis.coalesce(ibis.NA, ibis.NA, 3.14), 3.14), ], ) def test_coalesce(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (ibis.NA.fillna(5), 5), (L(5).fillna(10), 5), (L(5).nullif(5), None), (L(10).nullif(5), 10), ], ) def test_fillna_nullif(con, expr, expected): result = con.execute(expr) if expected is None: assert pd.isnull(result) else: assert result == expected @pytest.mark.parametrize( ('value', 'expected'), [ (L('foo_bar'), 'String'), (L(5), 'UInt8'), (L(1.2345), 'Float64'), (L(datetime(2015, 9, 1, hour=14, minute=48, second=5)), 'DateTime'), (L(date(2015, 9, 1)), 'Date'), param( ibis.NA, 'Null', marks=pytest.mark.xfail( raises=AssertionError, reason=( 'Client/server version mismatch not handled in the ' 'clickhouse driver' ), ), ), ], ) def test_typeof(con, value, expected): assert con.execute(value.typeof()) == expected @pytest.mark.parametrize(('value', 'expected'), [('foo_bar', 7), ('', 0)]) def test_string_length(con, value, expected): assert con.execute(L(value).length()) == expected @pytest.mark.parametrize( ('op', 'expected'), [ (methodcaller('substr', 0, 3), 'foo'), (methodcaller('substr', 4, 3), 'bar'), (methodcaller('substr', 1), 'oo_bar'), ], ) def test_string_substring(con, op, expected): value = L('foo_bar') assert con.execute(op(value)) == expected def test_string_column_substring(con, alltypes, translate): expr = alltypes.string_col.substr(2) assert translate(expr) == 'substring(`string_col`, 2 + 1)' assert len(con.execute(expr)) expr = alltypes.string_col.substr(0, 3) assert translate(expr) == 'substring(`string_col`, 0 + 1, 3)' assert len(con.execute(expr)) def test_string_reverse(con): assert con.execute(L('foo').reverse()) == 'oof' def test_string_upper(con): assert con.execute(L('foo').upper()) == 'FOO' def test_string_lower(con): assert con.execute(L('FOO').lower()) == 'foo' def test_string_lenght(con): assert con.execute(L('FOO').length()) == 3 @pytest.mark.parametrize( ('value', 'op', 'expected'), [ (L('foobar'), methodcaller('contains', 'bar'), True), (L('foobar'), methodcaller('contains', 'foo'), True), (L('foobar'), methodcaller('contains', 'baz'), False), (L('100%'), methodcaller('contains', '%'), True), (L('a_b_c'), methodcaller('contains', '_'), True), ], ) def test_string_contains(con, op, value, expected): assert con.execute(op(value)) == expected # TODO: clickhouse-driver escaping bug def test_re_replace(con, translate): expr1 = L('Hello, World!').re_replace('.', '\\\\0\\\\0') expr2 = L('Hello, World!').re_replace('^', 'here: ') assert con.execute(expr1) == 'HHeelllloo,, WWoorrlldd!!' assert con.execute(expr2) == 'here: Hello, World!' @pytest.mark.parametrize( ('value', 'expected'), [(L('a'), 0), (L('b'), 1), (L('d'), -1)], # TODO: what's the expected? ) def test_find_in_set(con, value, expected, translate): vals = list('abc') expr = value.find_in_set(vals) assert con.execute(expr) == expected def test_string_column_find_in_set(con, alltypes, translate): s = alltypes.string_col vals = list('abc') expr = s.find_in_set(vals) assert translate(expr) == "indexOf(['a','b','c'], `string_col`) - 1" assert len(con.execute(expr)) @pytest.mark.parametrize( ('url', 'extract', 'expected'), [ (L('https://www.cloudera.com'), 'HOST', 'www.cloudera.com'), (L('https://www.cloudera.com'), 'PROTOCOL', 'https'), ( L('https://www.youtube.com/watch?v=kEuEcWfewf8&t=10'), 'PATH', '/watch', ), ( L('https://www.youtube.com/watch?v=kEuEcWfewf8&t=10'), 'QUERY', 'v=kEuEcWfewf8&t=10', ), ], ) def test_parse_url(con, translate, url, extract, expected): expr = url.parse_url(extract) assert con.execute(expr) == expected def test_parse_url_query_parameter(con, translate): url = L('https://www.youtube.com/watch?v=kEuEcWfewf8&t=10') expr = url.parse_url('QUERY', 't') assert con.execute(expr) == '10' expr = url.parse_url('QUERY', 'v') assert con.execute(expr) == 'kEuEcWfewf8' @pytest.mark.parametrize( ('expr', 'expected'), [ (L('foobar').find('bar'), 3), (L('foobar').find('baz'), -1), (L('foobar').like('%bar'), True), (L('foobar').like('foo%'), True), (L('foobar').like('%baz%'), False), (L('foobar').like(['%bar']), True), (L('foobar').like(['foo%']), True), (L('foobar').like(['%baz%']), False), (L('foobar').like(['%bar', 'foo%']), True), (L('foobarfoo').replace('foo', 'H'), 'HbarH'), ], ) def test_string_find_like(con, expr, expected): assert con.execute(expr) == expected def test_string_column_like(con, alltypes, translate): expr = alltypes.string_col.like('foo%') assert translate(expr) == "`string_col` LIKE 'foo%'" assert len(con.execute(expr)) expr = alltypes.string_col.like(['foo%', '%bar']) expected = "`string_col` LIKE 'foo%' OR `string_col` LIKE '%bar'" assert translate(expr) == expected assert len(con.execute(expr)) def test_string_column_find(con, alltypes, translate): s = alltypes.string_col expr = s.find('a') assert translate(expr) == "position(`string_col`, 'a') - 1" assert len(con.execute(expr)) expr = s.find(s) assert translate(expr) == "position(`string_col`, `string_col`) - 1" assert len(con.execute(expr)) @pytest.mark.parametrize( ('call', 'expected'), [ (methodcaller('log'), 'log(`double_col`)'), (methodcaller('log2'), 'log2(`double_col`)'), (methodcaller('log10'), 'log10(`double_col`)'), (methodcaller('round'), 'round(`double_col`)'), (methodcaller('round', 0), 'round(`double_col`, 0)'), (methodcaller('round', 2), 'round(`double_col`, 2)'), (methodcaller('exp'), 'exp(`double_col`)'), (methodcaller('abs'), 'abs(`double_col`)'), (methodcaller('ceil'), 'ceil(`double_col`)'), (methodcaller('floor'), 'floor(`double_col`)'), (methodcaller('sqrt'), 'sqrt(`double_col`)'), ( methodcaller('sign'), 'intDivOrZero(`double_col`, abs(`double_col`))', ), ], ) def test_translate_math_functions(con, alltypes, translate, call, expected): expr = call(alltypes.double_col) assert translate(expr) == expected assert len(con.execute(expr)) @pytest.mark.parametrize( ('expr', 'expected'), [ (L(-5).abs(), 5), (L(5).abs(), 5), (L(5.5).round(), 6.0), (L(5.556).round(2), 5.56), (L(5.556).ceil(), 6.0), (L(5.556).floor(), 5.0), (L(5.556).exp(), math.exp(5.556)), (L(5.556).sign(), 1), (L(-5.556).sign(), -1),
(L(5.556).sqrt(), math.sqrt(5.556)), (L(5.556).log(2), math.log(5.556, 2)), (L(5.556).ln(), math.log(5.556)), (L(5.556).log2(), math.log(5.556, 2)), (L(5.556).log10(), math.log10(5.556)), ], ) def test_math_functions(con, expr, expected, translate): assert con.execute(expr) == expected def test_greatest(con, alltypes, translate): expr = ibis.greatest(alltypes.int_col, 10) assert translate(expr) == "greatest(`int_col`, 10)" assert len(con.execute(expr)) expr = ibis.greatest(alltypes.int_col, alltypes.bigint_col) assert translate(expr) == "greatest(`int_col`, `bigint_col`)" assert len(con.execute(expr)) def test_least(con, alltypes, translate): expr = ibis.least(alltypes.int_col, 10) assert translate(expr) == "least(`int_col`, 10)" assert len(con.execute(expr)) expr = ibis.least(alltypes.int_col, alltypes.bigint_col) assert translate(expr) == "least(`int_col`, `bigint_col`)" assert len(con.execute(expr)) # TODO: clickhouse-driver escaping bug @pytest.mark.parametrize( ('expr', 'expected'), [ (L('abcd').re_search('[a-z]'), True), (L('abcd').re_search(r'[\\d]+'), False), (L('1222').re_search(r'[\\d]+'), True), ], ) def test_regexp(con, expr, expected): assert con.execute(expr) == expected @pytest.mark.parametrize( ('expr', 'expected'), [ (L('abcd').re_extract('([a-z]+)', 0), 'abcd'), # (L('abcd').re_extract('(ab)(cd)', 1), 'cd'), # valid group number but no match => empty string (L('abcd').re_extract(r'(\\d)', 0), ''), # match but not a valid group number => NULL # (L('abcd').re_extract('abcd', 3), None), ], ) def test_regexp_extract(con, expr, expected, translate): assert con.execute(expr) == expected def test_column_regexp_extract(con, alltypes, translate): expected = r"extractAll(`string_col`, '[\d]+')[3 + 1]" expr = alltypes.string_col.re_extract(r'[\d]+', 3) assert translate(expr) == expected assert len(con.execute(expr)) def test_column_regexp_replace(con, alltypes, translate): expected = r"replaceRegexpAll(`string_col`, '[\d]+', 'aaa')" expr = alltypes.string_col.re_replace(r'[\d]+', 'aaa') assert translate(expr) == expected assert len(con.execute(expr)) def test_numeric_builtins_work(con, alltypes, df, translate): expr = alltypes.double_col result = expr.execute() expected = df.double_col.fillna(0) tm.assert_series_equal(result, expected) def test_null_column(alltypes, translate): t = alltypes nrows = t.count().execute() expr = t.mutate(na_column=ibis.NA).na_column result = expr.execute() expected = pd.Series([None] * nrows, name='na_column') tm.assert_series_equal(result, expected) @pytest.mark.parametrize( ('attr', 'expected'), [ (operator.methodcaller('year'), {2009, 2010}), (operator.methodcaller('month'), set(range(1, 13))), (operator.methodcaller('day'), set(range(1, 32))), ], ) def test_date_extract_field(db, alltypes, attr, expected): t = alltypes expr = attr(t.timestamp_col.cast('date')).distinct() result = expr.execute().astype(int) assert set(result) == expected def test_timestamp_from_integer(con, alltypes, translate): # timestamp_col has datetime type expr = alltypes.int_col.to_timestamp() assert translate(expr) == 'toDateTime(`int_col`)' assert len(con.execute(expr)) def test_count_distinct_with_filter(alltypes): expr = alltypes.string_col.nunique( where=alltypes.string_col.cast('int64') > 1 ) result = expr.execute() expected = alltypes.string_col.execute() expected = expected[expected.astype('int64') > 1].nunique() assert result == expected
(L(0).sign(), 0),
pkplatform_test.py
# -*- coding: utf-8 -*- u"""pytest for `pykern.pkplatform` :copyright: Copyright (c) 2015 Bivio Software, Inc. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import pytest def test_conformance1(): """Verify the platforms based on other calls""" import re import sys import platform from pykern import pkplatform if platform.system() == 'Linux': assert pkplatform.is_linux() assert pkplatform.is_unix() assert not pkplatform.is_darwin() assert not pkplatform.is_windows() elif platform.system().startswith('CYGWIN'): assert not pkplatform.is_linux() assert pkplatform.is_unix() assert not pkplatform.is_darwin() assert pkplatform.is_windows() elif platform.system() == 'Windows': assert not pkplatform.is_linux() assert not pkplatform.is_unix() assert not pkplatform.is_darwin() assert pkplatform.is_windows() elif platform.system() == 'Darwin': assert not pkplatform.is_linux() assert pkplatform.is_unix() assert pkplatform.is_darwin() assert not pkplatform.is_windows() else:
assert not pkplatform.is_windows() assert not pkplatform.is_darwin() assert not pkplatform.is_linux() # Not sure if it would be unix
requires.py
from charms.reactive import ( Endpoint, set_flag, clear_flag ) from charms.reactive import ( when, when_not ) class ContainerRuntimeRequires(Endpoint):
@when_not('endpoint.{endpoint_name}.joined') def broken(self): clear_flag(self.expand_name('endpoint.{endpoint_name}.available')) def set_config(self, name, binary_path): """ Set the configuration to be published. :param name: String name of runtime :param binary_path: String runtime executable :return: None """ for relation in self.relations: relation.to_publish.update({ 'name': name, 'binary_path': binary_path })
@when('endpoint.{endpoint_name}.changed') def changed(self): set_flag(self.expand_name('endpoint.{endpoint_name}.available'))
useUpdateThumbnail.ts
import gql from 'graphql-tag'; import { useMutation } from '@apollo/react-hooks'; import { useCallback } from 'react'; const UPDATE_THUMBNAIL = gql` mutation UpdateThumbnail($url: String) { update_thumbnail(url: $url) { id thumbnail } } `; export default function useUpdateThumbnail() { const [updateThumbnail] = useMutation(UPDATE_THUMBNAIL); const update = useCallback( (url: string | null) => { return updateThumbnail({ variables: { url, },
); return update; }
}); }, [updateThumbnail],
prec.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast; use ast::*; use parse::token::*; use parse::token::Token; use core::prelude::*; /// Unary operators have higher precedence than binary pub static unop_prec: uint = 100u; /** * Precedence of the `as` operator, which is a binary operator * but is not represented in the precedence table. */ pub static as_prec: uint = 11u; /** * Maps a token to a record specifying the corresponding binary * operator and its precedence */ pub fn token_to_binop(tok: Token) -> Option<ast::binop> { match tok { BINOP(STAR) => Some(mul), BINOP(SLASH) => Some(div), BINOP(PERCENT) => Some(rem), // 'as' sits between here with 11 BINOP(PLUS) => Some(add), BINOP(MINUS) => Some(subtract), BINOP(SHL) => Some(shl), BINOP(SHR) => Some(shr),
BINOP(AND) => Some(bitand), BINOP(CARET) => Some(bitxor), BINOP(OR) => Some(bitor), LT => Some(lt), LE => Some(le), GE => Some(ge), GT => Some(gt), EQEQ => Some(eq), NE => Some(ne), ANDAND => Some(and), OROR => Some(or), _ => None } }
command_join.go
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package app import ( "strings" goi18n "github.com/mattermost/go-i18n/i18n" "github.com/blastbao/mattermost-server/model" ) type JoinProvider struct { } const ( CMD_JOIN = "join" ) func init() { RegisterCommandProvider(&JoinProvider{}) } func (me *JoinProvider) GetTrigger() string { return CMD_JOIN } func (me *JoinProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ Trigger: CMD_JOIN, AutoComplete: true, AutoCompleteDesc: T("api.command_join.desc"), AutoCompleteHint: T("api.command_join.hint"), DisplayName: T("api.command_join.name"), } } func (me *JoinProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { channelName := message if strings.HasPrefix(message, "~") { channelName = message[1:] } channel, err := a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true) if err != nil { return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } if channel.Name != channelName { return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_join.missing.app_error")} } switch channel.Type { case model.CHANNEL_OPEN: if !a.SessionHasPermissionToChannel(args.Session, channel.Id, model.PERMISSION_JOIN_PUBLIC_CHANNELS) { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } case model.CHANNEL_PRIVATE: if !a.SessionHasPermissionToChannel(args.Session, channel.Id, model.PERMISSION_READ_CHANNEL) { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } default: return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } if err = a.JoinChannel(channel, args.UserId); err != nil
team, err := a.GetTeam(channel.TeamId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + channel.Name} }
{ return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} }
timelord_launcher.py
import asyncio import logging import pathlib import signal import socket import time from typing import Dict, List import pkg_resources from hddcoin.util.hddcoin_logging import initialize_logging from hddcoin.util.config import load_config from hddcoin.util.default_root import DEFAULT_ROOT_PATH from hddcoin.util.setproctitle import setproctitle active_processes: List = [] stopped = False lock = asyncio.Lock() log = logging.getLogger(__name__) async def kill_processes(): global stopped global active_processes async with lock: stopped = True for process in active_processes: try: process.kill() except ProcessLookupError: pass def
() -> pathlib.Path: p = pathlib.Path(pkg_resources.get_distribution("chiavdf").location) / "vdf_client" if p.is_file(): return p raise FileNotFoundError("can't find vdf_client binary") async def spawn_process(host: str, port: int, counter: int): global stopped global active_processes path_to_vdf_client = find_vdf_client() first_10_seconds = True start_time = time.time() while not stopped: try: dirname = path_to_vdf_client.parent basename = path_to_vdf_client.name resolved = socket.gethostbyname(host) proc = await asyncio.create_subprocess_shell( f"{basename} {resolved} {port} {counter}", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env={"PATH": dirname}, ) except Exception as e: log.warning(f"Exception while spawning process {counter}: {(e)}") continue async with lock: active_processes.append(proc) stdout, stderr = await proc.communicate() if stdout: log.info(f"VDF client {counter}: {stdout.decode().rstrip()}") if stderr: if first_10_seconds: if time.time() - start_time > 10: first_10_seconds = False else: log.error(f"VDF client {counter}: {stderr.decode().rstrip()}") log.info(f"Process number {counter} ended.") async with lock: if proc in active_processes: active_processes.remove(proc) await asyncio.sleep(0.1) async def spawn_all_processes(config: Dict, net_config: Dict): await asyncio.sleep(5) hostname = net_config["self_hostname"] if "host" not in config else config["host"] port = config["port"] process_count = config["process_count"] awaitables = [spawn_process(hostname, port, i) for i in range(process_count)] await asyncio.gather(*awaitables) def main(): root_path = DEFAULT_ROOT_PATH setproctitle("hddcoin_timelord_launcher") net_config = load_config(root_path, "config.yaml") config = net_config["timelord_launcher"] initialize_logging("TLauncher", config["logging"], root_path) def signal_received(): asyncio.create_task(kill_processes()) loop = asyncio.get_event_loop() try: loop.add_signal_handler(signal.SIGINT, signal_received) loop.add_signal_handler(signal.SIGTERM, signal_received) except NotImplementedError: log.info("signal handlers unsupported") try: loop.run_until_complete(spawn_all_processes(config, net_config)) finally: log.info("Launcher fully closed.") loop.close() if __name__ == "__main__": main()
find_vdf_client
getty.py
from gettybase import Session import unicodedata import os class Getty(): def __init__(self): try: self.s = Session(os.environ['getty_system_id'], os.environ['getty_system_pass'], os.environ['getty_user_name'], os.environ['getty_user_pass']) except KeyError: exit('Missing Getty API keys') def search(self, terms): return self.s.search(terms, items=5, from_item=1) def
(self, item): print type(item) print item output = self.s.buy(item, 1024 * 1024) return output def findAndReturn(self, terms, needed): images = [] items = self.search(terms) for i, item in enumerate(items): if i >= needed: break url = self.buy(unicodedata.normalize('NFKD', item['image_id']).encode('ascii', 'ignore')) # noqa images.append(url) return images if __name__ == '__main__': g = Getty() g.findAndReturn('ice, cold', 3)
buy
arcana_gl.ts
<TS language="gl" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Create a new address</source> <translation>Crear unha nova dirección</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Novo</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar a dirección seleccionada ao cartafol</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copiar</translation> </message> <message> <source>C&amp;lose</source> <translation>&amp;Pechar</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Borrar a dirección actualmente seleccionada da listaxe</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar os datos da pestaña actual a un arquivo.</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Borrar</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Diálogo de Contrasinal</translation> </message> <message> <source>Enter passphrase</source> <translation>Introduce contrasinal</translation> </message> <message> <source>New passphrase</source> <translation>Novo contrasinal</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repite novo contrasinal</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>ArcanaGUI</name> <message> <source>Sign &amp;message...</source> <translation>&amp;Asinar mensaxe...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Sincronizando coa rede...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Vista xeral</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Amosar vista xeral do moedeiro</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transacciones</translation> </message> <message> <source>Browse transaction history</source> <translation>Navegar historial de transaccións</translation> </message> <message> <source>E&amp;xit</source> <translation>&amp;Saír</translation> </message> <message> <source>Quit application</source> <translation>Saír da aplicación</translation> </message> <message> <source>About &amp;Qt</source> <translation>Acerca de &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Amosar información acerca de Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opcións...</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Encriptar Moedeiro...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>Copia de &amp;Seguridade do Moedeiro...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambiar contrasinal...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Direccións para recibir</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Reindexando bloques no disco...</translation> </message> <message> <source>Send coins to a Arcana address</source> <translation>Enviar moedas a unha dirección Arcana</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Facer copia de seguridade do moedeiro noutra localización</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Cambiar o contrasinal empregado para a encriptación do moedeiro</translation> </message> <message> <source>&amp;Debug window</source> <translation>Ventana de &amp;Depuración</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Abrir consola de depuración e diagnóstico</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensaxe...</translation> </message> <message> <source>Arcana</source> <translation>Arcana</translation> </message> <message> <source>Wallet</source> <translation>Moedeiro</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Recibir</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Amosar/Agachar</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Amosar ou agachar a ventana principal</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Encriptar as claves privadas que pertencen ao teu moedeiro</translation> </message> <message> <source>Sign messages with your Arcana addresses to prove you own them</source> <translation>Asina mensaxes coas túas direccións Arcana para probar que te pertencen</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Arcana addresses</source> <translation>Verificar mensaxes para asegurar que foron asinados con direccións Arcana dadas.</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Arquivo</translation> </message> <message> <source>&amp;Settings</source> <translation>Axus&amp;tes</translation> </message> <message> <source>&amp;Help</source> <translation>A&amp;xuda</translation> </message> <message> <source>Tabs toolbar</source> <translation>Barra de ferramentas</translation> </message> <message> <source>Request payments (generates QR codes and arcana: URIs)</source> <translation>Solicitar pagos (xenera códigos QR e arcana: URIs)</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Amosar a listaxe de direccións e etiquetas para enviar empregadas</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Amosar a listaxe de etiquetas e direccións para recibir empregadas</translation> </message> <message> <source>Open a arcana: URI or payment request</source> <translation>Abrir un arcana: URI ou solicitude de pago</translation> </message> <message> <source>&amp;Command-line options</source> <translation>Opcións da liña de comandos</translation> </message> <message> <source>%1 behind</source> <translation>%1 detrás</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>O último bloque recibido foi xerado fai %1.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>As transaccións despois desta non serán todavía visibles.</translation> </message> <message> <source>Error</source> <translation>Erro</translation> </message> <message> <source>Warning</source> <translation>Precaución</translation> </message> <message> <source>Information</source> <translation>Información</translation> </message> <message> <source>Up to date</source> <translation>Actualizado</translation> </message> <message> <source>Catching up...</source> <translation>Poñendo ao día...</translation> </message> <message> <source>Sent transaction</source> <translation>Transacción enviada</translation> </message> <message> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>O moedeiro está &lt;b&gt;encriptado&lt;/b&gt; e actualmente &lt;b&gt;desbloqueado&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>O moedeiro está &lt;b&gt;encriptado&lt;/b&gt; e actualmente &lt;b&gt;bloqueado&lt;/b&gt;</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Quantity:</source> <translation>Cantidade:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Importe:</translation> </message> <message> <source>Fee:</source> <translation>Pago:</translation> </message> <message> <source>Change:</source> <translation>Cambiar:</translation> </message> <message> <source>(un)select all</source> <translation>(des)selecciona todo</translation> </message> <message> <source>Tree mode</source> <translation>Modo árbore</translation> </message> <message> <source>List mode</source> <translation>Modo lista</translation> </message> <message> <source>Amount</source> <translation>Cantidade</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Confirmations</source> <translation>Confirmacións</translation> </message> <message> <source>Confirmed</source> <translation>Confirmado</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Modificar Dirección</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>A etiqueta asociada con esta entrada da listaxe de direccións</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>A dirección asociada con esta entrada na listaxe de dirección. Esta so pode ser modificada por direccións para enviar.</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Dirección</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>Crearáse un novo directorio de datos.</translation> </message> <message> <source>name</source> <translation>nome</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>O directorio xa existe. Engade %1 se queres crear un novo directorio aquí.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>A ruta xa existe e non é un directorio.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Non se pode crear directorio de datos aquí</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>versión</translation> </message> <message> <source>Command-line options</source> <translation>Opcións da liña de comandos</translation> </message> <message> <source>Usage:</source> <translation>Emprego:</translation> </message> <message> <source>command-line options</source> <translation>opcións da liña de comandos</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Benvido</translation> </message> <message> <source>Use the default data directory</source> <translation>Empregar o directorio de datos por defecto</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Empregar un directorio de datos personalizado</translation> </message> <message> <source>Error</source> <translation>Erro</translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>Formulario</translation> </message> <message> <source>Last block time</source> <translation>Hora do último bloque</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Abrir URI</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Abrir solicitude de pago dende URI ou ficheiro</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>Seleccionar ficheiro de solicitude de pago</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opcións</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Restaurar todas as opcións de cliente ás por defecto</translation> </message> <message> <source>&amp;Reset Options</source> <translation>Opcións de &amp;Restaurar</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Rede</translation> </message> <message> <source>W&amp;allet</source> <translation>Moedeiro</translation> </message> <message> <source>Automatically open the Arcana client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Abrir automáticamente o porto do cliente Arcana no router. Esto so funciona se o teu router soporta UPnP e está habilitado.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Mapear porto empregando &amp;UPnP</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>&amp;IP do Proxy:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Porto:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Porto do proxy (exemplo: 9050)</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Xanela</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Amosar so un icono na bandexa tras minimiza-la xanela.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar á bandexa en lugar de á barra de tarefas.</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar ao pechar</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Visualización</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>&amp;Linguaxe de interface de usuario:</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unidade na que amosar as cantidades:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Escolle a unidade de subdivisión por defecto para amosar na interface e ao enviar moedas.</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <source>default</source> <translation>por defecto</translation> </message> <message> <source>Confirm options reset</source> <translation>Confirmar opcións de restaurar</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>A dirección de proxy suministrada é inválida.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulario</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Arcana network after a connection is established, but this process has not completed yet.</source> <translation>A información amosada por estar desactualizada. O teu moedeiro sincronízase automáticamente coa rede Arcana despois de que se estableza unha conexión, pero este proceso non está todavía rematado.</translation> </message> <message> <source>Your current spendable balance</source> <translation>O teu balance actualmente dispoñible</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Total de transaccións que aínda teñen que ser confirmadas, e non contan todavía dentro do balance gastable</translation> </message> <message> <source>Immature:</source> <translation>Inmaduro:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>O balance minado todavía non madurou</translation> </message> <message> <source>Total:</source> <translation>Total:</translation> </message> <message> <source>Your current total balance</source> <translation>O teu balance actual total</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Cantidade</translation> </message> <message> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <source>N/A</source> <translation>N/A</translation> </message> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>N/A</translation> </message> <message> <source>Client version</source> <translation>Versión do cliente</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Información</translation> </message> <message> <source>Debug window</source> <translation>Ventana de Depuración</translation> </message> <message> <source>Startup time</source> <translation>Tempo de arranque</translation> </message> <message> <source>Network</source> <translation>Rede</translation> </message> <message> <source>Number of connections</source> <translation>Número de conexións</translation> </message> <message> <source>Block chain</source> <translation>Cadea de bloques</translation> </message> <message> <source>Current number of blocks</source> <translation>Número actual de bloques</translation> </message> <message> <source>Last block time</source> <translation>Hora do último bloque</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;Tráfico de Rede</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Limpar</translation> </message> <message> <source>Totals</source> <translation>Totais</translation> </message> <message> <source>In:</source> <translation>Dentro:</translation> </message> <message> <source>Out:</source> <translation>Fóra:</translation> </message> <message> <source>Debug log file</source> <translation>Arquivo de log de depuración</translation> </message> <message> <source>Clear console</source> <translation>Limpar consola</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Emprega as flechas arriba e abaixo para navegar polo historial, e &lt;b&gt;Ctrl-L&lt;/b&gt; para limpar a pantalla.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Escribe &lt;b&gt;axuda&lt;/b&gt; para unha vista xeral dos comandos dispoñibles.</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> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Cantidade:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Mensaxe:</translation> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation>Reutilizar unha das direccións para recibir previas. Reutilizar direccións ten problemas de seguridade e privacidade. Non empregues esto agás que antes se fixese unha solicitude de rexeneración dun pago.</translation> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation>R&amp;eutilizar unha dirección para recibir existente (non recomendado)</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Limpar tódolos campos do formulario</translation> </message> <message> <source>Clear</source> <translation>Limpar</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Solicitar pago</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>Código QR</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Copiar &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>Copiar &amp;Dirección</translation> </message> <message> <source>&amp;Save Image...</source> <translation>&amp;Gardar Imaxe...</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Moedas Enviadas</translation> </message> <message> <source>Insufficient funds!</source> <translation>Fondos insuficientes</translation> </message> <message> <source>Quantity:</source> <translation>Cantidade:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Importe:</translation> </message> <message> <source>Fee:</source> <translation>Pago:</translation> </message> <message> <source>Change:</source> <translation>Cambiar:</translation> </message> <message> <source>Transaction Fee:</source> <translation>Tarifa de transacción:</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Enviar a múltiples receptores á vez</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Engadir &amp;Receptor</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Limpar tódolos campos do formulario</translation> </message> <message> <source>Clear &amp;All</source> <translation>Limpar &amp;Todo</translation> </message> <message> <source>Balance:</source> <translation>Balance:</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirmar a acción de envío</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;Enviar</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>&amp;Cantidade:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Pagar &amp;A:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <source>Choose previously used address</source> <translation>Escoller dirección previamente empregada</translation> </message> <message> <source>This is a normal payment.</source> <translation>Este é un pago normal</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección dende portapapeis</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Eliminar esta entrada</translation> </message> <message> <source>Message:</source> <translation>Mensaxe:</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Introduce unha etiqueta para esta dirección para engadila á listaxe de direccións empregadas</translation> </message> <message> <source>Pay To:</source> <translation>Pagar A:</translation> </message> <message> <source>Memo:</source> <translation>Memo:</translation> </message> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Sinaturas - Asinar / Verificar unha Mensaxe</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Asinar Mensaxe</translation> </message> <message> <source>Choose previously used address</source> <translation>Escoller dirección previamente empregada</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección dende portapapeis</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 a mensaxe que queres asinar aquí</translation> </message> <message> <source>Signature</source> <translation>Sinatura</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Copiar a sinatura actual ao portapapeis do sistema</translation> </message> <message> <source>Sign the message to prove you own this Arcana address</source> <translation>Asina a mensaxe para probar que posees esta dirección Arcana</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Asinar &amp;Mensaxe</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Restaurar todos os campos de sinatura de mensaxe</translation> </message> <message> <source>Clear &amp;All</source> <translation>Limpar &amp;Todo</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensaxe</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified Arcana address</source> <translation>Verificar a mensaxe para asegurar que foi asinada coa dirección Arcana especificada</translation> </message> <message> <source>Verify &amp;Message</source> <translation>Verificar &amp;Mensaxe</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Restaurar todos os campos de verificación de mensaxe</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> </context> <context> <name>TransactionDescDialog</name> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Este panel amosa unha descripción detallada da transacción</translation> </message> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context>
</message> <message> <source>Specify data directory</source> <translation>Especificar directorio de datos</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Conectar a nodo para recuperar direccións de pares, e desconectar</translation> </message> <message> <source>Specify your own public address</source> <translation>Especificar a túa propia dirección pública</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>Aceptar liña de comandos e comandos JSON-RPC</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Executar no fondo como un demo e aceptar comandos</translation> </message> <message> <source>Arcana Core</source> <translation>Core de Arcana</translation> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Enlazar a unha dirección dada e escoitar sempre nela. Emprega a notación [host]:post para IPv6</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Executar comando cando unha transacción do moedeiro cambia (%s no comando é substituído por TxID)</translation> </message> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;categoría&gt; pode ser:</translation> </message> <message> <source>Block creation options:</source> <translation>Opcións de creación de bloque:</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Detectada base de datos de bloques corrupta.</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Queres reconstruír a base de datos de bloques agora?</translation> </message> <message> <source>Error initializing block database</source> <translation>Erro inicializando a base de datos de bloques</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Erro inicializando entorno de base de datos de moedeiro %s!</translation> </message> <message> <source>Error loading block database</source> <translation>Erro cargando base de datos do bloque</translation> </message> <message> <source>Error opening block database</source> <translation>Erro abrindo base de datos de bloques</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Erro: Espacio en disco escaso!</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Fallou escoitar en calquera porto. Emprega -listen=0 se queres esto.</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Bloque genesis incorrecto o no existente. Datadir erróneo para a rede?</translation> </message> <message> <source>Invalid -onion address: '%s'</source> <translation>Dirección -onion inválida: '%s'</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>Non hai suficientes descritores de arquivo dispoñibles.</translation> </message> <message> <source>Specify wallet file (within data directory)</source> <translation>Especificar arquivo do moedeiro (dentro do directorio de datos)</translation> </message> <message> <source>Verifying blocks...</source> <translation>Verificando bloques...</translation> </message> <message> <source>Verifying wallet...</source> <translation>Verificando moedeiro...</translation> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation>O moedeiro %s reside fóra do directorio de datos %s</translation> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation>Executar comando cando se recibe unha alerta relevante ou vemos un fork realmente longo (%s no cmd é substituído pola mensaxe)</translation> </message> <message> <source>Information</source> <translation>Información</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar traza/información de depuración á consola en lugar de ao arquivo debug.log</translation> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Recortar o arquivo debug.log ao arrancar o cliente (por defecto: 1 cando no-debug)</translation> </message> <message> <source>Signing transaction failed</source> <translation>Fallou a sinatura da transacción</translation> </message> <message> <source>Transaction amount too small</source> <translation>A cantidade da transacción é demasiado pequena</translation> </message> <message> <source>Transaction too large</source> <translation>A transacción é demasiado grande</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Nome de usuario para conexións JSON-RPC</translation> </message> <message> <source>Warning</source> <translation>Precaución</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Contrasinal para conexións JSON-RPC</translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executar comando cando o mellor bloque cambie (%s no comando é sustituído polo hash do bloque)</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir lookup de DNS para -addnote, -seednote e -connect</translation> </message> <message> <source>Loading addresses...</source> <translation>Cargando direccións...</translation> </message> <message> <source>Invalid -proxy address: '%s'</source> <translation>Dirección -proxy inválida: '%s'</translation> </message> <message> <source>Unknown network specified in -onlynet: '%s'</source> <translation>Rede descoñecida especificada en -onlynet: '%s'</translation> </message> <message> <source>Insufficient funds</source> <translation>Fondos insuficientes</translation> </message> <message> <source>Loading block index...</source> <translation>Cargando índice de bloques...</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Engadir un nodo ao que conectarse e tentar manter a conexión aberta</translation> </message> <message> <source>Loading wallet...</source> <translation>Cargando moedeiro...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Non se pode desactualizar o moedeiro</translation> </message> <message> <source>Cannot write default address</source> <translation>Non se pode escribir a dirección por defecto</translation> </message> <message> <source>Rescanning...</source> <translation>Rescaneando...</translation> </message> <message> <source>Done loading</source> <translation>Carga completa</translation> </message> <message> <source>Error</source> <translation>Erro</translation> </message> </context> </TS>
<name>arcana-core</name> <message> <source>Options:</source> <translation>Opcións:</translation>
logcore.go
package logcore import ( "fmt" "io/ioutil" "log" "os" ) type CeruleanInstance struct { dataDir string configFile string config CeruleanConfig msgBuffer MsgBuffer shardCollection DbShardCollection earliestTime uint32 } func (ci CeruleanInstance) getConfigFileName() string { return fmt.Sprintf("%s/%s", ci.dataDir, ci.configFile) } func (ci CeruleanInstance) getShardsDir() string { return fmt.Sprintf("%s/%s", ci.dataDir, "shards") } func NewCeruleanInstance(dataDir string) *CeruleanInstance { var err error instance := CeruleanInstance{ dataDir: dataDir, configFile: "ceruleanlog.json", config: NewCeruleanConfig(), } instance.msgBuffer = NewMsgBuffer(&instance) st, err := os.Stat(dataDir) if os.IsNotExist(err) { err = os.MkdirAll(dataDir, 0755) if err != nil { log.Panicln(err) } err = WriteCeruleanConfig(instance.getConfigFileName(), instance.config) if err != nil { log.Panicln(err) } err = os.MkdirAll(instance.getShardsDir(), 0755) if err != nil { log.Panicln(err) } log.Println("Initialised data directory", dataDir) } else if !st.IsDir() { log.Panicln("Not a directory:", dataDir) } instance.shardCollection, err = NewDbShardCollection(&instance) if err != nil { log.Panicln(err) } if readConfig, err := ReadCeruleanConfig(instance.getConfigFileName()); err == nil { instance.config = readConfig } else { err = WriteCeruleanConfig(instance.getConfigFileName(), instance.config) } return &instance } func (ci *CeruleanInstance) getShardsInDir() (shards []spanNameID, err error) { files, err := ioutil.ReadDir(ci.getShardsDir()) if err != nil { return nil, err } shards = []spanNameID{} for _, f := range files { if !f.IsDir() { continue } } return } func (ci *CeruleanInstance) Committer() { ci.msgBuffer.committer() } func (ci *CeruleanInstance) AddMessage(msg BasicGelfMessage) (err error) { return ci.msgBuffer.addMessage(msg) } func (ci *CeruleanInstance) Query(timeFrom, timeTo, limit uint32, query string) (result DbShardQueryResult, err error) { result, err = ci.shardCollection.Query(timeFrom, timeTo, limit, query) return
}
StatusLine.py
import sys import time from cleversheep3.TTY_Utils import RichTerm, registerForWinch class Status: """A fairly general purpose status line for a simple terminal. """ def __init__(self, startActive=True): self.setTerm(RichTerm.RichTerminal(sys.stdout)) self.spinner = None self.prevLine = None self.leftFields = [] self.leftFieldsByName = {} self.rightFields = [] self.rightFieldsByName = {} self.prevTime = time.time() self.updateInterval = 0.1 self.killed = True self.active = startActive registerForWinch(lambda: self.onWinch()) def onWinch(self): h, self.w = self.term.getDims(force=1) def setTerm(self, term): self.term = term h, self.w = self.term.getDims() def stop(self): self.kill() self.active = False def start(self): self.active = True def addLeftField(self, name, w): if name not in self.leftFieldsByName: self.leftFieldsByName[name] = len(self.leftFields) self.leftFields.append((w, "")) addField = addLeftField def addRightField(self, name, w): if name not in self.rightFieldsByName: self.rightFieldsByName[name] = len(self.rightFields) self.rightFields.append((w, "")) def setField(self, name, text): if text: text = text.splitlines()[0] try: idx = self.leftFieldsByName[name] w, _ = self.leftFields[idx] self.leftFields[idx] = w, text except KeyError: idx = self.rightFieldsByName[name] w, _ = self.rightFields[idx] self.rightFields[idx] = w, text self.update() def addSpinner(self, seq=r'\|/-'): def chars(): while True: for c in seq: yield c def s(): cc = chars() c = next(cc) t = time.time() while True: if time.time() - t > 0.1: t = time.time() c = next(cc) yield c self.spinner = s() def
(self): ww = self.w - 2 rline = "" lline = "" for w, text in self.rightFields: bar = "" if rline: bar = "|" rline = "%-*.*s%s%s" % (w, w, text, bar, rline) lline = "" if self.spinner: lline += "%s " % next(self.spinner) for w, text in self.leftFields: if lline: lline += "|" if w is not None: lline += "%-*.*s" % (w, w, text) else: lline += "%s" % (text,) l = len(lline) + len(rline) if l > ww: rline = rline.rstrip() l = len(lline) + len(rline) if l > ww: lline = lline.rstrip() l = len(lline) + len(rline) while len(lline) > len(rline) and l > ww: lline = lline[:-1] l = len(lline) + len(rline) while len(rline) > len(lline) and l > ww: rline = rline[1:] l = len(lline) + len(rline) while l > ww: lline = lline[:-1] rline = rline[1:] l = len(lline) + len(rline) if lline and rline: pad = " " * (ww - len(lline) - len(rline) - 1) line = "%s%s|%s" % (lline, pad, rline) elif rline: pad = " " * (ww - len(lline) - len(rline)) line = "%s%s%s" % (lline, pad, rline) else: line = lline return line def update(self, force=False): if not (self.active and self.term.isatty()): return if not force and time.time() - self.prevTime < self.updateInterval: return self.prevTime = time.time() self.line = self.buildLine() if self.line != self.prevLine: self.term.write("\r%s" % self.line) self.term.flush() self.prevLine = self.line self.killed = False def kill(self): if not (self.active and self.term.isatty()): return if self.killed: return self.term.write("\r%s\r" % (" " * (self.w - 1))) self.term.flush() self.prevLine = None self.killed = True
buildLine
apisix.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 scaffold import ( "fmt" "strings" "github.com/gruntwork-io/terratest/modules/k8s" ginkgo "github.com/onsi/ginkgo/v2" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var ( _apisixConfigMap = ` kind: ConfigMap apiVersion: v1 metadata: name: apisix-gw-config.yaml data: config.yaml: | %s ` _apisixDeployment = ` apiVersion: apps/v1 kind: Deployment metadata: name: apisix-deployment-e2e-test spec: replicas: 1 selector: matchLabels: app: apisix-deployment-e2e-test strategy: rollingUpdate: maxSurge: 50% maxUnavailable: 1 type: RollingUpdate template: metadata: labels: app: apisix-deployment-e2e-test spec: terminationGracePeriodSeconds: 0 containers: - livenessProbe: failureThreshold: 3 initialDelaySeconds: 1 periodSeconds: 2 successThreshold: 1 tcpSocket: port: 9080 timeoutSeconds: 2 readinessProbe: failureThreshold: 3 initialDelaySeconds: 1 periodSeconds: 2 successThreshold: 1 tcpSocket: port: 9080 timeoutSeconds: 2 image: "localhost:5000/apache/apisix:dev" imagePullPolicy: IfNotPresent name: apisix-deployment-e2e-test ports: - containerPort: 9080 name: "http" protocol: "TCP" - containerPort: 9180 name: "http-admin" protocol: "TCP" - containerPort: 9443 name: "https" protocol: "TCP" volumeMounts: - mountPath: /usr/local/apisix/conf/config.yaml name: apisix-config-yaml-configmap subPath: config.yaml volumes: - configMap: name: apisix-gw-config.yaml name: apisix-config-yaml-configmap ` _apisixService = ` apiVersion: v1 kind: Service metadata: name: apisix-service-e2e-test spec: selector: app: apisix-deployment-e2e-test ports: - name: http port: 9080 protocol: TCP targetPort: 9080 - name: http-admin port: 9180 protocol: TCP targetPort: 9180 - name: https port: 9443 protocol: TCP targetPort: 9443 - name: tcp port: 9100 protocol: TCP targetPort: 9100 - name: udp port: 9200 protocol: UDP targetPort: 9200 - name: http-control port: 9090 protocol: TCP targetPort: 9090 type: NodePort ` ) func (s *Scaffold) newAPISIX() (*corev1.Service, error) { data, err := s.renderConfig(s.opts.APISIXConfigPath) if err != nil { return nil, err } data = indent(data) configData := fmt.Sprintf(_apisixConfigMap, data) if err := k8s.KubectlApplyFromStringE(s.t, s.kubectlOptions, configData); err != nil { return nil, err } if err := k8s.KubectlApplyFromStringE(s.t, s.kubectlOptions, s.FormatRegistry(_apisixDeployment)); err != nil { return nil, err } if err := k8s.KubectlApplyFromStringE(s.t, s.kubectlOptions, _apisixService); err != nil { return nil, err } svc, err := k8s.GetServiceE(s.t, s.kubectlOptions, "apisix-service-e2e-test") if err != nil { return nil, err } return svc, nil } func indent(data string) string { list := strings.Split(data, "\n") for i := 0; i < len(list); i++ { list[i] = " " + list[i] } return strings.Join(list, "\n") } func (s *Scaffold) waitAllAPISIXPodsAvailable() error { opts := metav1.ListOptions{ LabelSelector: "app=apisix-deployment-e2e-test", } condFunc := func() (bool, error) { items, err := k8s.ListPodsE(s.t, s.kubectlOptions, opts) if err != nil { return false, err } if len(items) == 0 { ginkgo.GinkgoT().Log("no apisix pods created") return false, nil } for _, item := range items { foundPodReady := false for _, cond := range item.Status.Conditions { if cond.Type != corev1.PodReady { continue } foundPodReady = true if cond.Status != "True" { return false, nil } } if !foundPodReady
} return true, nil } return waitExponentialBackoff(condFunc) }
{ return false, nil }
InstanceData.js
// COPYRIGHT © 2018 Esri // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // This material is licensed for use under the Esri Master License // Agreement (MLA), and is bound by the terms of that agreement. // You may redistribute and use this code without modification, // provided you adhere to the terms of the MLA and include this // copyright notice. // // See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english // // For additional information, contact: // Environmental Systems Research Institute, Inc. // Attn: Contracts and Legal Services Department // 380 New York Street // Redlands, California, USA 92373 // USA
// // email: [email protected] // // See http://js.arcgis.com/4.10/esri/copyright.txt for details. define(["require","exports","../../../../../core/tsSupport/extendsHelper","../../../../../core/libs/gl-matrix-2/gl-matrix","../../../support/Evented","../../../support/mathUtils","../../../support/buffer/BufferView","../../../support/buffer/InterleavedLayout","../../../../webgl/Util"],function(t,e,i,r,o,a,n,s,f){function l(t){var e=s.newLayout().mat4f64("localTransform").mat4f64("globalTransform").vec4f64("boundingSphere").vec3f64("modelOrigin").mat3f("model").mat3f("modelNormal").f32("modelScaleFactor");return t.indexOf("color")>=0&&(e=e.vec4f("color")),t.indexOf("featureAttribute")>=0&&(e=e.vec4f("featureAttribute")),e=e.u8("state").u8("lodLevel").alignTo(4)}Object.defineProperty(e,"__esModule",{value:!0});var c,u=f.assert;!function(t){t[t.ALLOCATED=1]="ALLOCATED",t[t.ACTIVE=2]="ACTIVE",t[t.VISIBLE=4]="VISIBLE",t[t.HIGHLIGHT=8]="HIGHLIGHT",t[t.HIGHLIGHT_ACTIVE=16]="HIGHLIGHT_ACTIVE",t[t.REMOVE=32]="REMOVE",t[t.TRANSFORM_CHANGED=64]="TRANSFORM_CHANGED"}(c=e.StateFlags||(e.StateFlags={}));var h=function(){function t(t){this.localTransform=t.getField("localTransform",n.BufferViewMat4f64),this.globalTransform=t.getField("globalTransform",n.BufferViewMat4f64),this.modelOrigin=t.getField("modelOrigin",n.BufferViewVec3f64),this.model=t.getField("model",n.BufferViewMat3f),this.modelNormal=t.getField("modelNormal",n.BufferViewMat3f),this.modelScaleFactor=t.getField("modelScaleFactor",n.BufferViewFloat),this.boundingSphere=t.getField("boundingSphere",n.BufferViewVec4f64),this.color=t.getField("color",n.BufferViewVec4f),this.featureAttribute=t.getField("featureAttribute",n.BufferViewVec4f),this.state=t.getField("state",n.BufferViewUint8),this.lodLevel=t.getField("lodLevel",n.BufferViewUint8)}return t}();e.View=h;var p=function(t){function e(e,i){var r=t.call(this)||this;return r._capacity=0,r._size=0,r._next=0,r._layout=l(e),r._shaderTransformation=i,r}return i(e,t),Object.defineProperty(e.prototype,"capacity",{get:function(){return this._capacity},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"buffer",{get:function(){return this._buffer.buffer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"view",{get:function(){return this._view},enumerable:!0,configurable:!0}),e.prototype.addInstance=function(){this._size+1>this._capacity&&this.grow();var t=this.findSlot();return this._view.state.set(t,c.ALLOCATED),this._size++,this.emit("instance-added",{index:t}),t},e.prototype.removeInstance=function(t){var e=this._view.state;u(t>=0&&t<this._capacity&&e.get(t)&c.ALLOCATED,"invalid instance handle"),this.getStateFlag(t,c.ACTIVE)?this.setStateFlags(t,c.REMOVE):this.freeInstance(t),this.emit("instance-removed",{index:t})},e.prototype.freeInstance=function(t){var e=this._view.state;u(t>=0&&t<this._capacity&&e.get(t)&c.ALLOCATED,"invalid instance handle"),e.set(t,0),this._size--},e.prototype.setLocalTransform=function(t,e,i){void 0===i&&(i=!0),this._view.localTransform.setMat(t,e),i&&this.updateModelTransform(t)},e.prototype.getLocalTransform=function(t,e){this._view.localTransform.getMat(t,e)},e.prototype.setGlobalTransform=function(t,e,i){void 0===i&&(i=!0),this._view.globalTransform.setMat(t,e),i&&this.updateModelTransform(t)},e.prototype.getGlobalTransform=function(t,e){this._view.globalTransform.getMat(t,e)},e.prototype.updateModelTransform=function(t){var e=this._view,i=m,o=v;e.localTransform.getMat(t,_),e.globalTransform.getMat(t,y);var n=r.mat4.multiply(y,y,_);r.vec3.set(i,n[12],n[13],n[14]),e.modelOrigin.setVec(t,i),r.mat3.fromMat4(o,n),e.model.setMat(t,o),e.modelScaleFactor.set(t,a.maxScale(n)),r.mat3.invert(o,o),r.mat3.transpose(o,o),e.modelNormal.setMat(t,o),this.setStateFlags(t,c.TRANSFORM_CHANGED),this.emit("instance-transform-changed",{index:t})},e.prototype.getModelTransform=function(t,e){var i=this._view;i.model.getMat(t,v),i.modelOrigin.getVec(t,m),e[0]=v[0],e[1]=v[1],e[2]=v[2],e[3]=0,e[4]=v[3],e[5]=v[4],e[6]=v[5],e[7]=0,e[8]=v[6],e[9]=v[7],e[10]=v[8],e[11]=0,e[12]=m[0],e[13]=m[1],e[14]=m[2],e[15]=1},e.prototype.applyShaderTransformation=function(t,e){this._shaderTransformation&&this._shaderTransformation.applyTransform(this,t,e)},e.prototype.getCombinedModelTransform=function(t,e){return this.getModelTransform(t,e),this._shaderTransformation&&this._shaderTransformation.applyTransform(this,t,e),e},e.prototype.getCombinedLocalTransform=function(t,e){return this._view.localTransform.getMat(t,e),this._shaderTransformation&&this._shaderTransformation.applyTransform(this,t,e),e},e.prototype.getCombinedScaleFactor=function(t){var e=this._view.modelScaleFactor.get(t);return this._shaderTransformation&&(e*=this._shaderTransformation.scaleFactor(this,t)),e},e.prototype.getModel=function(t,e){this._view.model.getMat(t,e)},e.prototype.getScaleFactor=function(t){return this._view.modelScaleFactor.get(t)},e.prototype.setFeatureAttribute=function(t,e){this._view.featureAttribute.setVec(t,e)},e.prototype.getFeatureAttribute=function(t,e){this._view.featureAttribute.getVec(t,e)},e.prototype.setColor=function(t,e){this._view.color.setVec(t,e)},e.prototype.getColor=function(t,e){this._view.color.getVec(t,e)},e.prototype.setVisible=function(t,e){e!==this.getVisible(t)&&(this.setStateFlag(t,c.VISIBLE,e),this.emit("instance-visibility-changed",{index:t}))},e.prototype.getVisible=function(t){return this.getStateFlag(t,c.VISIBLE)},e.prototype.setHighlight=function(t,e){e!==this.getHighlight(t)&&(this.setStateFlag(t,c.HIGHLIGHT,e),this.emit("instance-highlight-changed",{index:t}))},e.prototype.getHighlight=function(t){return this.getStateFlag(t,c.HIGHLIGHT)},e.prototype.getState=function(t){return this._view.state.get(t)},e.prototype.getLodLevel=function(t){return this._view.lodLevel.get(t)},e.prototype.countFlags=function(t){for(var e=0,i=0;i<this._capacity;++i){this.getState(i)&t&&++e}return e},e.prototype.setStateFlags=function(t,e){var i=this._view.state;e=i.get(t)|e,i.set(t,e)},e.prototype.clearStateFlags=function(t,e){var i=this._view.state;e=i.get(t)&~e,i.set(t,e)},e.prototype.setStateFlag=function(t,e,i){i?this.setStateFlags(t,e):this.clearStateFlags(t,e)},e.prototype.getStateFlag=function(t,e){return!!(this._view.state.get(t)&e)},e.prototype.grow=function(){var t=Math.max(g,Math.floor(this._capacity*d)),e=this._layout.createBuffer(t);if(this._buffer){var i=new Uint8Array(this._buffer.buffer);new Uint8Array(e.buffer).set(i)}this._capacity=t,this._buffer=e,this._view=new h(this._buffer)},e.prototype.findSlot=function(){for(var t=this._view.state,e=this._next;t.get(e)&c.ALLOCATED;)e=(e+1)%this._capacity;return this._next=(e+1)%this._capacity,e},e}(o.Evented);e.InstanceData=p;var g=1024,d=2,m=r.vec3f64.create(),v=r.mat3f64.create(),_=r.mat4f64.create(),y=r.mat4f64.create()});
utils.js
//아직 안쓰임
example-1.js
const map = new Map(); map.set('name', 'John'); map.set('age', 25); console.log(map.get('name'));
console.log(map.get('sex'));
syntax_serialize_generated.rs
/** * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * */ use super::{serialize::WithContext, syntax::Syntax, syntax_variant_generated::*}; use serde::{ser::SerializeStruct, Serialize, Serializer}; impl<'a, T, V> Serialize for WithContext<'a, Syntax<'a, T, V>> where T: 'a, WithContext<'a, T>: Serialize, { fn
<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { match self.1.children { SyntaxVariant::Missing => { let mut ss = s.serialize_struct("", 1)?; ss.serialize_field("kind", "missing")?; ss.end() } SyntaxVariant::Token(ref t) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "token")?; ss.serialize_field("token", &self.with(t))?; ss.end() } SyntaxVariant::SyntaxList(l) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "list")?; ss.serialize_field("elements", &self.with(l))?; ss.end() } SyntaxVariant::EndOfFile (EndOfFileChildren{token} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "end_of_file")?; ss.serialize_field("end_of_file_token", &self.with(token))?; ss.end() } SyntaxVariant::Script (ScriptChildren{declarations} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "script")?; ss.serialize_field("script_declarations", &self.with(declarations))?; ss.end() } SyntaxVariant::QualifiedName (QualifiedNameChildren{parts} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "qualified_name")?; ss.serialize_field("qualified_name_parts", &self.with(parts))?; ss.end() } SyntaxVariant::SimpleTypeSpecifier (SimpleTypeSpecifierChildren{specifier} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "simple_type_specifier")?; ss.serialize_field("simple_type_specifier", &self.with(specifier))?; ss.end() } SyntaxVariant::LiteralExpression (LiteralExpressionChildren{expression} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "literal")?; ss.serialize_field("literal_expression", &self.with(expression))?; ss.end() } SyntaxVariant::PrefixedStringExpression (PrefixedStringExpressionChildren{name,str} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "prefixed_string")?; ss.serialize_field("prefixed_string_name", &self.with(name))?; ss.serialize_field("prefixed_string_str", &self.with(str))?; ss.end() } SyntaxVariant::PrefixedCodeExpression (PrefixedCodeExpressionChildren{prefix,left_backtick,expression,right_backtick} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "prefixed_code")?; ss.serialize_field("prefixed_code_prefix", &self.with(prefix))?; ss.serialize_field("prefixed_code_left_backtick", &self.with(left_backtick))?; ss.serialize_field("prefixed_code_expression", &self.with(expression))?; ss.serialize_field("prefixed_code_right_backtick", &self.with(right_backtick))?; ss.end() } SyntaxVariant::VariableExpression (VariableExpressionChildren{expression} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "variable")?; ss.serialize_field("variable_expression", &self.with(expression))?; ss.end() } SyntaxVariant::PipeVariableExpression (PipeVariableExpressionChildren{expression} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "pipe_variable")?; ss.serialize_field("pipe_variable_expression", &self.with(expression))?; ss.end() } SyntaxVariant::FileAttributeSpecification (FileAttributeSpecificationChildren{left_double_angle,keyword,colon,attributes,right_double_angle} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "file_attribute_specification")?; ss.serialize_field("file_attribute_specification_left_double_angle", &self.with(left_double_angle))?; ss.serialize_field("file_attribute_specification_keyword", &self.with(keyword))?; ss.serialize_field("file_attribute_specification_colon", &self.with(colon))?; ss.serialize_field("file_attribute_specification_attributes", &self.with(attributes))?; ss.serialize_field("file_attribute_specification_right_double_angle", &self.with(right_double_angle))?; ss.end() } SyntaxVariant::EnumDeclaration (EnumDeclarationChildren{attribute_spec,keyword,name,colon,base,type_,left_brace,use_clauses,enumerators,right_brace} ) => { let mut ss = s.serialize_struct("", 11)?; ss.serialize_field("kind", "enum_declaration")?; ss.serialize_field("enum_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("enum_keyword", &self.with(keyword))?; ss.serialize_field("enum_name", &self.with(name))?; ss.serialize_field("enum_colon", &self.with(colon))?; ss.serialize_field("enum_base", &self.with(base))?; ss.serialize_field("enum_type", &self.with(type_))?; ss.serialize_field("enum_left_brace", &self.with(left_brace))?; ss.serialize_field("enum_use_clauses", &self.with(use_clauses))?; ss.serialize_field("enum_enumerators", &self.with(enumerators))?; ss.serialize_field("enum_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::EnumUse (EnumUseChildren{keyword,names,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "enum_use")?; ss.serialize_field("enum_use_keyword", &self.with(keyword))?; ss.serialize_field("enum_use_names", &self.with(names))?; ss.serialize_field("enum_use_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::Enumerator (EnumeratorChildren{name,equal,value,semicolon} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "enumerator")?; ss.serialize_field("enumerator_name", &self.with(name))?; ss.serialize_field("enumerator_equal", &self.with(equal))?; ss.serialize_field("enumerator_value", &self.with(value))?; ss.serialize_field("enumerator_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::EnumClassDeclaration (EnumClassDeclarationChildren{attribute_spec,modifiers,enum_keyword,class_keyword,name,colon,base,extends,extends_list,left_brace,elements,right_brace} ) => { let mut ss = s.serialize_struct("", 13)?; ss.serialize_field("kind", "enum_class_declaration")?; ss.serialize_field("enum_class_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("enum_class_modifiers", &self.with(modifiers))?; ss.serialize_field("enum_class_enum_keyword", &self.with(enum_keyword))?; ss.serialize_field("enum_class_class_keyword", &self.with(class_keyword))?; ss.serialize_field("enum_class_name", &self.with(name))?; ss.serialize_field("enum_class_colon", &self.with(colon))?; ss.serialize_field("enum_class_base", &self.with(base))?; ss.serialize_field("enum_class_extends", &self.with(extends))?; ss.serialize_field("enum_class_extends_list", &self.with(extends_list))?; ss.serialize_field("enum_class_left_brace", &self.with(left_brace))?; ss.serialize_field("enum_class_elements", &self.with(elements))?; ss.serialize_field("enum_class_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::EnumClassEnumerator (EnumClassEnumeratorChildren{modifiers,type_,name,initializer,semicolon} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "enum_class_enumerator")?; ss.serialize_field("enum_class_enumerator_modifiers", &self.with(modifiers))?; ss.serialize_field("enum_class_enumerator_type", &self.with(type_))?; ss.serialize_field("enum_class_enumerator_name", &self.with(name))?; ss.serialize_field("enum_class_enumerator_initializer", &self.with(initializer))?; ss.serialize_field("enum_class_enumerator_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::RecordDeclaration (RecordDeclarationChildren{attribute_spec,modifier,keyword,name,extends_keyword,extends_opt,left_brace,fields,right_brace} ) => { let mut ss = s.serialize_struct("", 10)?; ss.serialize_field("kind", "record_declaration")?; ss.serialize_field("record_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("record_modifier", &self.with(modifier))?; ss.serialize_field("record_keyword", &self.with(keyword))?; ss.serialize_field("record_name", &self.with(name))?; ss.serialize_field("record_extends_keyword", &self.with(extends_keyword))?; ss.serialize_field("record_extends_opt", &self.with(extends_opt))?; ss.serialize_field("record_left_brace", &self.with(left_brace))?; ss.serialize_field("record_fields", &self.with(fields))?; ss.serialize_field("record_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::RecordField (RecordFieldChildren{type_,name,init,semi} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "record_field")?; ss.serialize_field("record_field_type", &self.with(type_))?; ss.serialize_field("record_field_name", &self.with(name))?; ss.serialize_field("record_field_init", &self.with(init))?; ss.serialize_field("record_field_semi", &self.with(semi))?; ss.end() } SyntaxVariant::AliasDeclaration (AliasDeclarationChildren{attribute_spec,keyword,name,generic_parameter,constraint,equal,type_,semicolon} ) => { let mut ss = s.serialize_struct("", 9)?; ss.serialize_field("kind", "alias_declaration")?; ss.serialize_field("alias_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("alias_keyword", &self.with(keyword))?; ss.serialize_field("alias_name", &self.with(name))?; ss.serialize_field("alias_generic_parameter", &self.with(generic_parameter))?; ss.serialize_field("alias_constraint", &self.with(constraint))?; ss.serialize_field("alias_equal", &self.with(equal))?; ss.serialize_field("alias_type", &self.with(type_))?; ss.serialize_field("alias_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ContextAliasDeclaration (ContextAliasDeclarationChildren{attribute_spec,keyword,name,generic_parameter,as_constraint,equal,context,semicolon} ) => { let mut ss = s.serialize_struct("", 9)?; ss.serialize_field("kind", "context_alias_declaration")?; ss.serialize_field("ctx_alias_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("ctx_alias_keyword", &self.with(keyword))?; ss.serialize_field("ctx_alias_name", &self.with(name))?; ss.serialize_field("ctx_alias_generic_parameter", &self.with(generic_parameter))?; ss.serialize_field("ctx_alias_as_constraint", &self.with(as_constraint))?; ss.serialize_field("ctx_alias_equal", &self.with(equal))?; ss.serialize_field("ctx_alias_context", &self.with(context))?; ss.serialize_field("ctx_alias_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::PropertyDeclaration (PropertyDeclarationChildren{attribute_spec,modifiers,type_,declarators,semicolon} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "property_declaration")?; ss.serialize_field("property_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("property_modifiers", &self.with(modifiers))?; ss.serialize_field("property_type", &self.with(type_))?; ss.serialize_field("property_declarators", &self.with(declarators))?; ss.serialize_field("property_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::PropertyDeclarator (PropertyDeclaratorChildren{name,initializer} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "property_declarator")?; ss.serialize_field("property_name", &self.with(name))?; ss.serialize_field("property_initializer", &self.with(initializer))?; ss.end() } SyntaxVariant::NamespaceDeclaration (NamespaceDeclarationChildren{header,body} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "namespace_declaration")?; ss.serialize_field("namespace_header", &self.with(header))?; ss.serialize_field("namespace_body", &self.with(body))?; ss.end() } SyntaxVariant::NamespaceDeclarationHeader (NamespaceDeclarationHeaderChildren{keyword,name} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "namespace_declaration_header")?; ss.serialize_field("namespace_keyword", &self.with(keyword))?; ss.serialize_field("namespace_name", &self.with(name))?; ss.end() } SyntaxVariant::NamespaceBody (NamespaceBodyChildren{left_brace,declarations,right_brace} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "namespace_body")?; ss.serialize_field("namespace_left_brace", &self.with(left_brace))?; ss.serialize_field("namespace_declarations", &self.with(declarations))?; ss.serialize_field("namespace_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::NamespaceEmptyBody (NamespaceEmptyBodyChildren{semicolon} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "namespace_empty_body")?; ss.serialize_field("namespace_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::NamespaceUseDeclaration (NamespaceUseDeclarationChildren{keyword,kind,clauses,semicolon} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "namespace_use_declaration")?; ss.serialize_field("namespace_use_keyword", &self.with(keyword))?; ss.serialize_field("namespace_use_kind", &self.with(kind))?; ss.serialize_field("namespace_use_clauses", &self.with(clauses))?; ss.serialize_field("namespace_use_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::NamespaceGroupUseDeclaration (NamespaceGroupUseDeclarationChildren{keyword,kind,prefix,left_brace,clauses,right_brace,semicolon} ) => { let mut ss = s.serialize_struct("", 8)?; ss.serialize_field("kind", "namespace_group_use_declaration")?; ss.serialize_field("namespace_group_use_keyword", &self.with(keyword))?; ss.serialize_field("namespace_group_use_kind", &self.with(kind))?; ss.serialize_field("namespace_group_use_prefix", &self.with(prefix))?; ss.serialize_field("namespace_group_use_left_brace", &self.with(left_brace))?; ss.serialize_field("namespace_group_use_clauses", &self.with(clauses))?; ss.serialize_field("namespace_group_use_right_brace", &self.with(right_brace))?; ss.serialize_field("namespace_group_use_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::NamespaceUseClause (NamespaceUseClauseChildren{clause_kind,name,as_,alias} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "namespace_use_clause")?; ss.serialize_field("namespace_use_clause_kind", &self.with(clause_kind))?; ss.serialize_field("namespace_use_name", &self.with(name))?; ss.serialize_field("namespace_use_as", &self.with(as_))?; ss.serialize_field("namespace_use_alias", &self.with(alias))?; ss.end() } SyntaxVariant::FunctionDeclaration (FunctionDeclarationChildren{attribute_spec,declaration_header,body} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "function_declaration")?; ss.serialize_field("function_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("function_declaration_header", &self.with(declaration_header))?; ss.serialize_field("function_body", &self.with(body))?; ss.end() } SyntaxVariant::FunctionDeclarationHeader (FunctionDeclarationHeaderChildren{modifiers,keyword,name,type_parameter_list,left_paren,parameter_list,right_paren,contexts,colon,readonly_return,type_,where_clause} ) => { let mut ss = s.serialize_struct("", 13)?; ss.serialize_field("kind", "function_declaration_header")?; ss.serialize_field("function_modifiers", &self.with(modifiers))?; ss.serialize_field("function_keyword", &self.with(keyword))?; ss.serialize_field("function_name", &self.with(name))?; ss.serialize_field("function_type_parameter_list", &self.with(type_parameter_list))?; ss.serialize_field("function_left_paren", &self.with(left_paren))?; ss.serialize_field("function_parameter_list", &self.with(parameter_list))?; ss.serialize_field("function_right_paren", &self.with(right_paren))?; ss.serialize_field("function_contexts", &self.with(contexts))?; ss.serialize_field("function_colon", &self.with(colon))?; ss.serialize_field("function_readonly_return", &self.with(readonly_return))?; ss.serialize_field("function_type", &self.with(type_))?; ss.serialize_field("function_where_clause", &self.with(where_clause))?; ss.end() } SyntaxVariant::Contexts (ContextsChildren{left_bracket,types,right_bracket} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "contexts")?; ss.serialize_field("contexts_left_bracket", &self.with(left_bracket))?; ss.serialize_field("contexts_types", &self.with(types))?; ss.serialize_field("contexts_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::WhereClause (WhereClauseChildren{keyword,constraints} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "where_clause")?; ss.serialize_field("where_clause_keyword", &self.with(keyword))?; ss.serialize_field("where_clause_constraints", &self.with(constraints))?; ss.end() } SyntaxVariant::WhereConstraint (WhereConstraintChildren{left_type,operator,right_type} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "where_constraint")?; ss.serialize_field("where_constraint_left_type", &self.with(left_type))?; ss.serialize_field("where_constraint_operator", &self.with(operator))?; ss.serialize_field("where_constraint_right_type", &self.with(right_type))?; ss.end() } SyntaxVariant::MethodishDeclaration (MethodishDeclarationChildren{attribute,function_decl_header,function_body,semicolon} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "methodish_declaration")?; ss.serialize_field("methodish_attribute", &self.with(attribute))?; ss.serialize_field("methodish_function_decl_header", &self.with(function_decl_header))?; ss.serialize_field("methodish_function_body", &self.with(function_body))?; ss.serialize_field("methodish_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::MethodishTraitResolution (MethodishTraitResolutionChildren{attribute,function_decl_header,equal,name,semicolon} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "methodish_trait_resolution")?; ss.serialize_field("methodish_trait_attribute", &self.with(attribute))?; ss.serialize_field("methodish_trait_function_decl_header", &self.with(function_decl_header))?; ss.serialize_field("methodish_trait_equal", &self.with(equal))?; ss.serialize_field("methodish_trait_name", &self.with(name))?; ss.serialize_field("methodish_trait_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ClassishDeclaration (ClassishDeclarationChildren{attribute,modifiers,xhp,keyword,name,type_parameters,extends_keyword,extends_list,implements_keyword,implements_list,where_clause,body} ) => { let mut ss = s.serialize_struct("", 13)?; ss.serialize_field("kind", "classish_declaration")?; ss.serialize_field("classish_attribute", &self.with(attribute))?; ss.serialize_field("classish_modifiers", &self.with(modifiers))?; ss.serialize_field("classish_xhp", &self.with(xhp))?; ss.serialize_field("classish_keyword", &self.with(keyword))?; ss.serialize_field("classish_name", &self.with(name))?; ss.serialize_field("classish_type_parameters", &self.with(type_parameters))?; ss.serialize_field("classish_extends_keyword", &self.with(extends_keyword))?; ss.serialize_field("classish_extends_list", &self.with(extends_list))?; ss.serialize_field("classish_implements_keyword", &self.with(implements_keyword))?; ss.serialize_field("classish_implements_list", &self.with(implements_list))?; ss.serialize_field("classish_where_clause", &self.with(where_clause))?; ss.serialize_field("classish_body", &self.with(body))?; ss.end() } SyntaxVariant::ClassishBody (ClassishBodyChildren{left_brace,elements,right_brace} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "classish_body")?; ss.serialize_field("classish_body_left_brace", &self.with(left_brace))?; ss.serialize_field("classish_body_elements", &self.with(elements))?; ss.serialize_field("classish_body_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::TraitUsePrecedenceItem (TraitUsePrecedenceItemChildren{name,keyword,removed_names} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "trait_use_precedence_item")?; ss.serialize_field("trait_use_precedence_item_name", &self.with(name))?; ss.serialize_field("trait_use_precedence_item_keyword", &self.with(keyword))?; ss.serialize_field("trait_use_precedence_item_removed_names", &self.with(removed_names))?; ss.end() } SyntaxVariant::TraitUseAliasItem (TraitUseAliasItemChildren{aliasing_name,keyword,modifiers,aliased_name} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "trait_use_alias_item")?; ss.serialize_field("trait_use_alias_item_aliasing_name", &self.with(aliasing_name))?; ss.serialize_field("trait_use_alias_item_keyword", &self.with(keyword))?; ss.serialize_field("trait_use_alias_item_modifiers", &self.with(modifiers))?; ss.serialize_field("trait_use_alias_item_aliased_name", &self.with(aliased_name))?; ss.end() } SyntaxVariant::TraitUseConflictResolution (TraitUseConflictResolutionChildren{keyword,names,left_brace,clauses,right_brace} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "trait_use_conflict_resolution")?; ss.serialize_field("trait_use_conflict_resolution_keyword", &self.with(keyword))?; ss.serialize_field("trait_use_conflict_resolution_names", &self.with(names))?; ss.serialize_field("trait_use_conflict_resolution_left_brace", &self.with(left_brace))?; ss.serialize_field("trait_use_conflict_resolution_clauses", &self.with(clauses))?; ss.serialize_field("trait_use_conflict_resolution_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::TraitUse (TraitUseChildren{keyword,names,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "trait_use")?; ss.serialize_field("trait_use_keyword", &self.with(keyword))?; ss.serialize_field("trait_use_names", &self.with(names))?; ss.serialize_field("trait_use_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::RequireClause (RequireClauseChildren{keyword,kind,name,semicolon} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "require_clause")?; ss.serialize_field("require_keyword", &self.with(keyword))?; ss.serialize_field("require_kind", &self.with(kind))?; ss.serialize_field("require_name", &self.with(name))?; ss.serialize_field("require_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ConstDeclaration (ConstDeclarationChildren{modifiers,keyword,type_specifier,declarators,semicolon} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "const_declaration")?; ss.serialize_field("const_modifiers", &self.with(modifiers))?; ss.serialize_field("const_keyword", &self.with(keyword))?; ss.serialize_field("const_type_specifier", &self.with(type_specifier))?; ss.serialize_field("const_declarators", &self.with(declarators))?; ss.serialize_field("const_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ConstantDeclarator (ConstantDeclaratorChildren{name,initializer} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "constant_declarator")?; ss.serialize_field("constant_declarator_name", &self.with(name))?; ss.serialize_field("constant_declarator_initializer", &self.with(initializer))?; ss.end() } SyntaxVariant::TypeConstDeclaration (TypeConstDeclarationChildren{attribute_spec,modifiers,keyword,type_keyword,name,type_parameters,type_constraint,equal,type_specifier,semicolon} ) => { let mut ss = s.serialize_struct("", 11)?; ss.serialize_field("kind", "type_const_declaration")?; ss.serialize_field("type_const_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("type_const_modifiers", &self.with(modifiers))?; ss.serialize_field("type_const_keyword", &self.with(keyword))?; ss.serialize_field("type_const_type_keyword", &self.with(type_keyword))?; ss.serialize_field("type_const_name", &self.with(name))?; ss.serialize_field("type_const_type_parameters", &self.with(type_parameters))?; ss.serialize_field("type_const_type_constraint", &self.with(type_constraint))?; ss.serialize_field("type_const_equal", &self.with(equal))?; ss.serialize_field("type_const_type_specifier", &self.with(type_specifier))?; ss.serialize_field("type_const_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ContextConstDeclaration (ContextConstDeclarationChildren{modifiers,const_keyword,ctx_keyword,name,type_parameters,constraint,equal,ctx_list,semicolon} ) => { let mut ss = s.serialize_struct("", 10)?; ss.serialize_field("kind", "context_const_declaration")?; ss.serialize_field("context_const_modifiers", &self.with(modifiers))?; ss.serialize_field("context_const_const_keyword", &self.with(const_keyword))?; ss.serialize_field("context_const_ctx_keyword", &self.with(ctx_keyword))?; ss.serialize_field("context_const_name", &self.with(name))?; ss.serialize_field("context_const_type_parameters", &self.with(type_parameters))?; ss.serialize_field("context_const_constraint", &self.with(constraint))?; ss.serialize_field("context_const_equal", &self.with(equal))?; ss.serialize_field("context_const_ctx_list", &self.with(ctx_list))?; ss.serialize_field("context_const_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::DecoratedExpression (DecoratedExpressionChildren{decorator,expression} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "decorated_expression")?; ss.serialize_field("decorated_expression_decorator", &self.with(decorator))?; ss.serialize_field("decorated_expression_expression", &self.with(expression))?; ss.end() } SyntaxVariant::ParameterDeclaration (ParameterDeclarationChildren{attribute,visibility,call_convention,readonly,type_,name,default_value} ) => { let mut ss = s.serialize_struct("", 8)?; ss.serialize_field("kind", "parameter_declaration")?; ss.serialize_field("parameter_attribute", &self.with(attribute))?; ss.serialize_field("parameter_visibility", &self.with(visibility))?; ss.serialize_field("parameter_call_convention", &self.with(call_convention))?; ss.serialize_field("parameter_readonly", &self.with(readonly))?; ss.serialize_field("parameter_type", &self.with(type_))?; ss.serialize_field("parameter_name", &self.with(name))?; ss.serialize_field("parameter_default_value", &self.with(default_value))?; ss.end() } SyntaxVariant::VariadicParameter (VariadicParameterChildren{call_convention,type_,ellipsis} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "variadic_parameter")?; ss.serialize_field("variadic_parameter_call_convention", &self.with(call_convention))?; ss.serialize_field("variadic_parameter_type", &self.with(type_))?; ss.serialize_field("variadic_parameter_ellipsis", &self.with(ellipsis))?; ss.end() } SyntaxVariant::OldAttributeSpecification (OldAttributeSpecificationChildren{left_double_angle,attributes,right_double_angle} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "old_attribute_specification")?; ss.serialize_field("old_attribute_specification_left_double_angle", &self.with(left_double_angle))?; ss.serialize_field("old_attribute_specification_attributes", &self.with(attributes))?; ss.serialize_field("old_attribute_specification_right_double_angle", &self.with(right_double_angle))?; ss.end() } SyntaxVariant::AttributeSpecification (AttributeSpecificationChildren{attributes} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "attribute_specification")?; ss.serialize_field("attribute_specification_attributes", &self.with(attributes))?; ss.end() } SyntaxVariant::Attribute (AttributeChildren{at,attribute_name} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "attribute")?; ss.serialize_field("attribute_at", &self.with(at))?; ss.serialize_field("attribute_attribute_name", &self.with(attribute_name))?; ss.end() } SyntaxVariant::InclusionExpression (InclusionExpressionChildren{require,filename} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "inclusion_expression")?; ss.serialize_field("inclusion_require", &self.with(require))?; ss.serialize_field("inclusion_filename", &self.with(filename))?; ss.end() } SyntaxVariant::InclusionDirective (InclusionDirectiveChildren{expression,semicolon} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "inclusion_directive")?; ss.serialize_field("inclusion_expression", &self.with(expression))?; ss.serialize_field("inclusion_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::CompoundStatement (CompoundStatementChildren{left_brace,statements,right_brace} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "compound_statement")?; ss.serialize_field("compound_left_brace", &self.with(left_brace))?; ss.serialize_field("compound_statements", &self.with(statements))?; ss.serialize_field("compound_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::ExpressionStatement (ExpressionStatementChildren{expression,semicolon} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "expression_statement")?; ss.serialize_field("expression_statement_expression", &self.with(expression))?; ss.serialize_field("expression_statement_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::MarkupSection (MarkupSectionChildren{hashbang,suffix} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "markup_section")?; ss.serialize_field("markup_hashbang", &self.with(hashbang))?; ss.serialize_field("markup_suffix", &self.with(suffix))?; ss.end() } SyntaxVariant::MarkupSuffix (MarkupSuffixChildren{less_than_question,name} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "markup_suffix")?; ss.serialize_field("markup_suffix_less_than_question", &self.with(less_than_question))?; ss.serialize_field("markup_suffix_name", &self.with(name))?; ss.end() } SyntaxVariant::UnsetStatement (UnsetStatementChildren{keyword,left_paren,variables,right_paren,semicolon} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "unset_statement")?; ss.serialize_field("unset_keyword", &self.with(keyword))?; ss.serialize_field("unset_left_paren", &self.with(left_paren))?; ss.serialize_field("unset_variables", &self.with(variables))?; ss.serialize_field("unset_right_paren", &self.with(right_paren))?; ss.serialize_field("unset_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::UsingStatementBlockScoped (UsingStatementBlockScopedChildren{await_keyword,using_keyword,left_paren,expressions,right_paren,body} ) => { let mut ss = s.serialize_struct("", 7)?; ss.serialize_field("kind", "using_statement_block_scoped")?; ss.serialize_field("using_block_await_keyword", &self.with(await_keyword))?; ss.serialize_field("using_block_using_keyword", &self.with(using_keyword))?; ss.serialize_field("using_block_left_paren", &self.with(left_paren))?; ss.serialize_field("using_block_expressions", &self.with(expressions))?; ss.serialize_field("using_block_right_paren", &self.with(right_paren))?; ss.serialize_field("using_block_body", &self.with(body))?; ss.end() } SyntaxVariant::UsingStatementFunctionScoped (UsingStatementFunctionScopedChildren{await_keyword,using_keyword,expression,semicolon} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "using_statement_function_scoped")?; ss.serialize_field("using_function_await_keyword", &self.with(await_keyword))?; ss.serialize_field("using_function_using_keyword", &self.with(using_keyword))?; ss.serialize_field("using_function_expression", &self.with(expression))?; ss.serialize_field("using_function_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::WhileStatement (WhileStatementChildren{keyword,left_paren,condition,right_paren,body} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "while_statement")?; ss.serialize_field("while_keyword", &self.with(keyword))?; ss.serialize_field("while_left_paren", &self.with(left_paren))?; ss.serialize_field("while_condition", &self.with(condition))?; ss.serialize_field("while_right_paren", &self.with(right_paren))?; ss.serialize_field("while_body", &self.with(body))?; ss.end() } SyntaxVariant::IfStatement (IfStatementChildren{keyword,left_paren,condition,right_paren,statement,elseif_clauses,else_clause} ) => { let mut ss = s.serialize_struct("", 8)?; ss.serialize_field("kind", "if_statement")?; ss.serialize_field("if_keyword", &self.with(keyword))?; ss.serialize_field("if_left_paren", &self.with(left_paren))?; ss.serialize_field("if_condition", &self.with(condition))?; ss.serialize_field("if_right_paren", &self.with(right_paren))?; ss.serialize_field("if_statement", &self.with(statement))?; ss.serialize_field("if_elseif_clauses", &self.with(elseif_clauses))?; ss.serialize_field("if_else_clause", &self.with(else_clause))?; ss.end() } SyntaxVariant::ElseifClause (ElseifClauseChildren{keyword,left_paren,condition,right_paren,statement} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "elseif_clause")?; ss.serialize_field("elseif_keyword", &self.with(keyword))?; ss.serialize_field("elseif_left_paren", &self.with(left_paren))?; ss.serialize_field("elseif_condition", &self.with(condition))?; ss.serialize_field("elseif_right_paren", &self.with(right_paren))?; ss.serialize_field("elseif_statement", &self.with(statement))?; ss.end() } SyntaxVariant::ElseClause (ElseClauseChildren{keyword,statement} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "else_clause")?; ss.serialize_field("else_keyword", &self.with(keyword))?; ss.serialize_field("else_statement", &self.with(statement))?; ss.end() } SyntaxVariant::TryStatement (TryStatementChildren{keyword,compound_statement,catch_clauses,finally_clause} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "try_statement")?; ss.serialize_field("try_keyword", &self.with(keyword))?; ss.serialize_field("try_compound_statement", &self.with(compound_statement))?; ss.serialize_field("try_catch_clauses", &self.with(catch_clauses))?; ss.serialize_field("try_finally_clause", &self.with(finally_clause))?; ss.end() } SyntaxVariant::CatchClause (CatchClauseChildren{keyword,left_paren,type_,variable,right_paren,body} ) => { let mut ss = s.serialize_struct("", 7)?; ss.serialize_field("kind", "catch_clause")?; ss.serialize_field("catch_keyword", &self.with(keyword))?; ss.serialize_field("catch_left_paren", &self.with(left_paren))?; ss.serialize_field("catch_type", &self.with(type_))?; ss.serialize_field("catch_variable", &self.with(variable))?; ss.serialize_field("catch_right_paren", &self.with(right_paren))?; ss.serialize_field("catch_body", &self.with(body))?; ss.end() } SyntaxVariant::FinallyClause (FinallyClauseChildren{keyword,body} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "finally_clause")?; ss.serialize_field("finally_keyword", &self.with(keyword))?; ss.serialize_field("finally_body", &self.with(body))?; ss.end() } SyntaxVariant::DoStatement (DoStatementChildren{keyword,body,while_keyword,left_paren,condition,right_paren,semicolon} ) => { let mut ss = s.serialize_struct("", 8)?; ss.serialize_field("kind", "do_statement")?; ss.serialize_field("do_keyword", &self.with(keyword))?; ss.serialize_field("do_body", &self.with(body))?; ss.serialize_field("do_while_keyword", &self.with(while_keyword))?; ss.serialize_field("do_left_paren", &self.with(left_paren))?; ss.serialize_field("do_condition", &self.with(condition))?; ss.serialize_field("do_right_paren", &self.with(right_paren))?; ss.serialize_field("do_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ForStatement (ForStatementChildren{keyword,left_paren,initializer,first_semicolon,control,second_semicolon,end_of_loop,right_paren,body} ) => { let mut ss = s.serialize_struct("", 10)?; ss.serialize_field("kind", "for_statement")?; ss.serialize_field("for_keyword", &self.with(keyword))?; ss.serialize_field("for_left_paren", &self.with(left_paren))?; ss.serialize_field("for_initializer", &self.with(initializer))?; ss.serialize_field("for_first_semicolon", &self.with(first_semicolon))?; ss.serialize_field("for_control", &self.with(control))?; ss.serialize_field("for_second_semicolon", &self.with(second_semicolon))?; ss.serialize_field("for_end_of_loop", &self.with(end_of_loop))?; ss.serialize_field("for_right_paren", &self.with(right_paren))?; ss.serialize_field("for_body", &self.with(body))?; ss.end() } SyntaxVariant::ForeachStatement (ForeachStatementChildren{keyword,left_paren,collection,await_keyword,as_,key,arrow,value,right_paren,body} ) => { let mut ss = s.serialize_struct("", 11)?; ss.serialize_field("kind", "foreach_statement")?; ss.serialize_field("foreach_keyword", &self.with(keyword))?; ss.serialize_field("foreach_left_paren", &self.with(left_paren))?; ss.serialize_field("foreach_collection", &self.with(collection))?; ss.serialize_field("foreach_await_keyword", &self.with(await_keyword))?; ss.serialize_field("foreach_as", &self.with(as_))?; ss.serialize_field("foreach_key", &self.with(key))?; ss.serialize_field("foreach_arrow", &self.with(arrow))?; ss.serialize_field("foreach_value", &self.with(value))?; ss.serialize_field("foreach_right_paren", &self.with(right_paren))?; ss.serialize_field("foreach_body", &self.with(body))?; ss.end() } SyntaxVariant::SwitchStatement (SwitchStatementChildren{keyword,left_paren,expression,right_paren,left_brace,sections,right_brace} ) => { let mut ss = s.serialize_struct("", 8)?; ss.serialize_field("kind", "switch_statement")?; ss.serialize_field("switch_keyword", &self.with(keyword))?; ss.serialize_field("switch_left_paren", &self.with(left_paren))?; ss.serialize_field("switch_expression", &self.with(expression))?; ss.serialize_field("switch_right_paren", &self.with(right_paren))?; ss.serialize_field("switch_left_brace", &self.with(left_brace))?; ss.serialize_field("switch_sections", &self.with(sections))?; ss.serialize_field("switch_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::SwitchSection (SwitchSectionChildren{labels,statements,fallthrough} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "switch_section")?; ss.serialize_field("switch_section_labels", &self.with(labels))?; ss.serialize_field("switch_section_statements", &self.with(statements))?; ss.serialize_field("switch_section_fallthrough", &self.with(fallthrough))?; ss.end() } SyntaxVariant::SwitchFallthrough (SwitchFallthroughChildren{keyword,semicolon} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "switch_fallthrough")?; ss.serialize_field("fallthrough_keyword", &self.with(keyword))?; ss.serialize_field("fallthrough_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::CaseLabel (CaseLabelChildren{keyword,expression,colon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "case_label")?; ss.serialize_field("case_keyword", &self.with(keyword))?; ss.serialize_field("case_expression", &self.with(expression))?; ss.serialize_field("case_colon", &self.with(colon))?; ss.end() } SyntaxVariant::DefaultLabel (DefaultLabelChildren{keyword,colon} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "default_label")?; ss.serialize_field("default_keyword", &self.with(keyword))?; ss.serialize_field("default_colon", &self.with(colon))?; ss.end() } SyntaxVariant::ReturnStatement (ReturnStatementChildren{keyword,expression,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "return_statement")?; ss.serialize_field("return_keyword", &self.with(keyword))?; ss.serialize_field("return_expression", &self.with(expression))?; ss.serialize_field("return_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::YieldBreakStatement (YieldBreakStatementChildren{keyword,break_,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "yield_break_statement")?; ss.serialize_field("yield_break_keyword", &self.with(keyword))?; ss.serialize_field("yield_break_break", &self.with(break_))?; ss.serialize_field("yield_break_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ThrowStatement (ThrowStatementChildren{keyword,expression,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "throw_statement")?; ss.serialize_field("throw_keyword", &self.with(keyword))?; ss.serialize_field("throw_expression", &self.with(expression))?; ss.serialize_field("throw_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::BreakStatement (BreakStatementChildren{keyword,semicolon} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "break_statement")?; ss.serialize_field("break_keyword", &self.with(keyword))?; ss.serialize_field("break_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ContinueStatement (ContinueStatementChildren{keyword,semicolon} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "continue_statement")?; ss.serialize_field("continue_keyword", &self.with(keyword))?; ss.serialize_field("continue_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::EchoStatement (EchoStatementChildren{keyword,expressions,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "echo_statement")?; ss.serialize_field("echo_keyword", &self.with(keyword))?; ss.serialize_field("echo_expressions", &self.with(expressions))?; ss.serialize_field("echo_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::ConcurrentStatement (ConcurrentStatementChildren{keyword,statement} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "concurrent_statement")?; ss.serialize_field("concurrent_keyword", &self.with(keyword))?; ss.serialize_field("concurrent_statement", &self.with(statement))?; ss.end() } SyntaxVariant::SimpleInitializer (SimpleInitializerChildren{equal,value} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "simple_initializer")?; ss.serialize_field("simple_initializer_equal", &self.with(equal))?; ss.serialize_field("simple_initializer_value", &self.with(value))?; ss.end() } SyntaxVariant::AnonymousClass (AnonymousClassChildren{class_keyword,left_paren,argument_list,right_paren,extends_keyword,extends_list,implements_keyword,implements_list,body} ) => { let mut ss = s.serialize_struct("", 10)?; ss.serialize_field("kind", "anonymous_class")?; ss.serialize_field("anonymous_class_class_keyword", &self.with(class_keyword))?; ss.serialize_field("anonymous_class_left_paren", &self.with(left_paren))?; ss.serialize_field("anonymous_class_argument_list", &self.with(argument_list))?; ss.serialize_field("anonymous_class_right_paren", &self.with(right_paren))?; ss.serialize_field("anonymous_class_extends_keyword", &self.with(extends_keyword))?; ss.serialize_field("anonymous_class_extends_list", &self.with(extends_list))?; ss.serialize_field("anonymous_class_implements_keyword", &self.with(implements_keyword))?; ss.serialize_field("anonymous_class_implements_list", &self.with(implements_list))?; ss.serialize_field("anonymous_class_body", &self.with(body))?; ss.end() } SyntaxVariant::AnonymousFunction (AnonymousFunctionChildren{attribute_spec,async_keyword,function_keyword,left_paren,parameters,right_paren,ctx_list,colon,readonly_return,type_,use_,body} ) => { let mut ss = s.serialize_struct("", 13)?; ss.serialize_field("kind", "anonymous_function")?; ss.serialize_field("anonymous_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("anonymous_async_keyword", &self.with(async_keyword))?; ss.serialize_field("anonymous_function_keyword", &self.with(function_keyword))?; ss.serialize_field("anonymous_left_paren", &self.with(left_paren))?; ss.serialize_field("anonymous_parameters", &self.with(parameters))?; ss.serialize_field("anonymous_right_paren", &self.with(right_paren))?; ss.serialize_field("anonymous_ctx_list", &self.with(ctx_list))?; ss.serialize_field("anonymous_colon", &self.with(colon))?; ss.serialize_field("anonymous_readonly_return", &self.with(readonly_return))?; ss.serialize_field("anonymous_type", &self.with(type_))?; ss.serialize_field("anonymous_use", &self.with(use_))?; ss.serialize_field("anonymous_body", &self.with(body))?; ss.end() } SyntaxVariant::AnonymousFunctionUseClause (AnonymousFunctionUseClauseChildren{keyword,left_paren,variables,right_paren} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "anonymous_function_use_clause")?; ss.serialize_field("anonymous_use_keyword", &self.with(keyword))?; ss.serialize_field("anonymous_use_left_paren", &self.with(left_paren))?; ss.serialize_field("anonymous_use_variables", &self.with(variables))?; ss.serialize_field("anonymous_use_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::LambdaExpression (LambdaExpressionChildren{attribute_spec,async_,signature,arrow,body} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "lambda_expression")?; ss.serialize_field("lambda_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("lambda_async", &self.with(async_))?; ss.serialize_field("lambda_signature", &self.with(signature))?; ss.serialize_field("lambda_arrow", &self.with(arrow))?; ss.serialize_field("lambda_body", &self.with(body))?; ss.end() } SyntaxVariant::LambdaSignature (LambdaSignatureChildren{left_paren,parameters,right_paren,contexts,colon,readonly_return,type_} ) => { let mut ss = s.serialize_struct("", 8)?; ss.serialize_field("kind", "lambda_signature")?; ss.serialize_field("lambda_left_paren", &self.with(left_paren))?; ss.serialize_field("lambda_parameters", &self.with(parameters))?; ss.serialize_field("lambda_right_paren", &self.with(right_paren))?; ss.serialize_field("lambda_contexts", &self.with(contexts))?; ss.serialize_field("lambda_colon", &self.with(colon))?; ss.serialize_field("lambda_readonly_return", &self.with(readonly_return))?; ss.serialize_field("lambda_type", &self.with(type_))?; ss.end() } SyntaxVariant::CastExpression (CastExpressionChildren{left_paren,type_,right_paren,operand} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "cast_expression")?; ss.serialize_field("cast_left_paren", &self.with(left_paren))?; ss.serialize_field("cast_type", &self.with(type_))?; ss.serialize_field("cast_right_paren", &self.with(right_paren))?; ss.serialize_field("cast_operand", &self.with(operand))?; ss.end() } SyntaxVariant::ScopeResolutionExpression (ScopeResolutionExpressionChildren{qualifier,operator,name} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "scope_resolution_expression")?; ss.serialize_field("scope_resolution_qualifier", &self.with(qualifier))?; ss.serialize_field("scope_resolution_operator", &self.with(operator))?; ss.serialize_field("scope_resolution_name", &self.with(name))?; ss.end() } SyntaxVariant::MemberSelectionExpression (MemberSelectionExpressionChildren{object,operator,name} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "member_selection_expression")?; ss.serialize_field("member_object", &self.with(object))?; ss.serialize_field("member_operator", &self.with(operator))?; ss.serialize_field("member_name", &self.with(name))?; ss.end() } SyntaxVariant::SafeMemberSelectionExpression (SafeMemberSelectionExpressionChildren{object,operator,name} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "safe_member_selection_expression")?; ss.serialize_field("safe_member_object", &self.with(object))?; ss.serialize_field("safe_member_operator", &self.with(operator))?; ss.serialize_field("safe_member_name", &self.with(name))?; ss.end() } SyntaxVariant::EmbeddedMemberSelectionExpression (EmbeddedMemberSelectionExpressionChildren{object,operator,name} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "embedded_member_selection_expression")?; ss.serialize_field("embedded_member_object", &self.with(object))?; ss.serialize_field("embedded_member_operator", &self.with(operator))?; ss.serialize_field("embedded_member_name", &self.with(name))?; ss.end() } SyntaxVariant::YieldExpression (YieldExpressionChildren{keyword,operand} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "yield_expression")?; ss.serialize_field("yield_keyword", &self.with(keyword))?; ss.serialize_field("yield_operand", &self.with(operand))?; ss.end() } SyntaxVariant::PrefixUnaryExpression (PrefixUnaryExpressionChildren{operator,operand} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "prefix_unary_expression")?; ss.serialize_field("prefix_unary_operator", &self.with(operator))?; ss.serialize_field("prefix_unary_operand", &self.with(operand))?; ss.end() } SyntaxVariant::PostfixUnaryExpression (PostfixUnaryExpressionChildren{operand,operator} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "postfix_unary_expression")?; ss.serialize_field("postfix_unary_operand", &self.with(operand))?; ss.serialize_field("postfix_unary_operator", &self.with(operator))?; ss.end() } SyntaxVariant::BinaryExpression (BinaryExpressionChildren{left_operand,operator,right_operand} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "binary_expression")?; ss.serialize_field("binary_left_operand", &self.with(left_operand))?; ss.serialize_field("binary_operator", &self.with(operator))?; ss.serialize_field("binary_right_operand", &self.with(right_operand))?; ss.end() } SyntaxVariant::IsExpression (IsExpressionChildren{left_operand,operator,right_operand} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "is_expression")?; ss.serialize_field("is_left_operand", &self.with(left_operand))?; ss.serialize_field("is_operator", &self.with(operator))?; ss.serialize_field("is_right_operand", &self.with(right_operand))?; ss.end() } SyntaxVariant::AsExpression (AsExpressionChildren{left_operand,operator,right_operand} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "as_expression")?; ss.serialize_field("as_left_operand", &self.with(left_operand))?; ss.serialize_field("as_operator", &self.with(operator))?; ss.serialize_field("as_right_operand", &self.with(right_operand))?; ss.end() } SyntaxVariant::NullableAsExpression (NullableAsExpressionChildren{left_operand,operator,right_operand} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "nullable_as_expression")?; ss.serialize_field("nullable_as_left_operand", &self.with(left_operand))?; ss.serialize_field("nullable_as_operator", &self.with(operator))?; ss.serialize_field("nullable_as_right_operand", &self.with(right_operand))?; ss.end() } SyntaxVariant::ConditionalExpression (ConditionalExpressionChildren{test,question,consequence,colon,alternative} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "conditional_expression")?; ss.serialize_field("conditional_test", &self.with(test))?; ss.serialize_field("conditional_question", &self.with(question))?; ss.serialize_field("conditional_consequence", &self.with(consequence))?; ss.serialize_field("conditional_colon", &self.with(colon))?; ss.serialize_field("conditional_alternative", &self.with(alternative))?; ss.end() } SyntaxVariant::EvalExpression (EvalExpressionChildren{keyword,left_paren,argument,right_paren} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "eval_expression")?; ss.serialize_field("eval_keyword", &self.with(keyword))?; ss.serialize_field("eval_left_paren", &self.with(left_paren))?; ss.serialize_field("eval_argument", &self.with(argument))?; ss.serialize_field("eval_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::IssetExpression (IssetExpressionChildren{keyword,left_paren,argument_list,right_paren} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "isset_expression")?; ss.serialize_field("isset_keyword", &self.with(keyword))?; ss.serialize_field("isset_left_paren", &self.with(left_paren))?; ss.serialize_field("isset_argument_list", &self.with(argument_list))?; ss.serialize_field("isset_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::FunctionCallExpression (FunctionCallExpressionChildren{receiver,type_args,enum_class_label,left_paren,argument_list,right_paren} ) => { let mut ss = s.serialize_struct("", 7)?; ss.serialize_field("kind", "function_call_expression")?; ss.serialize_field("function_call_receiver", &self.with(receiver))?; ss.serialize_field("function_call_type_args", &self.with(type_args))?; ss.serialize_field("function_call_enum_class_label", &self.with(enum_class_label))?; ss.serialize_field("function_call_left_paren", &self.with(left_paren))?; ss.serialize_field("function_call_argument_list", &self.with(argument_list))?; ss.serialize_field("function_call_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::FunctionPointerExpression (FunctionPointerExpressionChildren{receiver,type_args} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "function_pointer_expression")?; ss.serialize_field("function_pointer_receiver", &self.with(receiver))?; ss.serialize_field("function_pointer_type_args", &self.with(type_args))?; ss.end() } SyntaxVariant::ParenthesizedExpression (ParenthesizedExpressionChildren{left_paren,expression,right_paren} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "parenthesized_expression")?; ss.serialize_field("parenthesized_expression_left_paren", &self.with(left_paren))?; ss.serialize_field("parenthesized_expression_expression", &self.with(expression))?; ss.serialize_field("parenthesized_expression_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::BracedExpression (BracedExpressionChildren{left_brace,expression,right_brace} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "braced_expression")?; ss.serialize_field("braced_expression_left_brace", &self.with(left_brace))?; ss.serialize_field("braced_expression_expression", &self.with(expression))?; ss.serialize_field("braced_expression_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::ETSpliceExpression (ETSpliceExpressionChildren{dollar,left_brace,expression,right_brace} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "et_splice_expression")?; ss.serialize_field("et_splice_expression_dollar", &self.with(dollar))?; ss.serialize_field("et_splice_expression_left_brace", &self.with(left_brace))?; ss.serialize_field("et_splice_expression_expression", &self.with(expression))?; ss.serialize_field("et_splice_expression_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::EmbeddedBracedExpression (EmbeddedBracedExpressionChildren{left_brace,expression,right_brace} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "embedded_braced_expression")?; ss.serialize_field("embedded_braced_expression_left_brace", &self.with(left_brace))?; ss.serialize_field("embedded_braced_expression_expression", &self.with(expression))?; ss.serialize_field("embedded_braced_expression_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::ListExpression (ListExpressionChildren{keyword,left_paren,members,right_paren} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "list_expression")?; ss.serialize_field("list_keyword", &self.with(keyword))?; ss.serialize_field("list_left_paren", &self.with(left_paren))?; ss.serialize_field("list_members", &self.with(members))?; ss.serialize_field("list_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::CollectionLiteralExpression (CollectionLiteralExpressionChildren{name,left_brace,initializers,right_brace} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "collection_literal_expression")?; ss.serialize_field("collection_literal_name", &self.with(name))?; ss.serialize_field("collection_literal_left_brace", &self.with(left_brace))?; ss.serialize_field("collection_literal_initializers", &self.with(initializers))?; ss.serialize_field("collection_literal_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::ObjectCreationExpression (ObjectCreationExpressionChildren{new_keyword,object} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "object_creation_expression")?; ss.serialize_field("object_creation_new_keyword", &self.with(new_keyword))?; ss.serialize_field("object_creation_object", &self.with(object))?; ss.end() } SyntaxVariant::ConstructorCall (ConstructorCallChildren{type_,left_paren,argument_list,right_paren} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "constructor_call")?; ss.serialize_field("constructor_call_type", &self.with(type_))?; ss.serialize_field("constructor_call_left_paren", &self.with(left_paren))?; ss.serialize_field("constructor_call_argument_list", &self.with(argument_list))?; ss.serialize_field("constructor_call_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::RecordCreationExpression (RecordCreationExpressionChildren{type_,left_bracket,members,right_bracket} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "record_creation_expression")?; ss.serialize_field("record_creation_type", &self.with(type_))?; ss.serialize_field("record_creation_left_bracket", &self.with(left_bracket))?; ss.serialize_field("record_creation_members", &self.with(members))?; ss.serialize_field("record_creation_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::DarrayIntrinsicExpression (DarrayIntrinsicExpressionChildren{keyword,explicit_type,left_bracket,members,right_bracket} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "darray_intrinsic_expression")?; ss.serialize_field("darray_intrinsic_keyword", &self.with(keyword))?; ss.serialize_field("darray_intrinsic_explicit_type", &self.with(explicit_type))?; ss.serialize_field("darray_intrinsic_left_bracket", &self.with(left_bracket))?; ss.serialize_field("darray_intrinsic_members", &self.with(members))?; ss.serialize_field("darray_intrinsic_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::DictionaryIntrinsicExpression (DictionaryIntrinsicExpressionChildren{keyword,explicit_type,left_bracket,members,right_bracket} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "dictionary_intrinsic_expression")?; ss.serialize_field("dictionary_intrinsic_keyword", &self.with(keyword))?; ss.serialize_field("dictionary_intrinsic_explicit_type", &self.with(explicit_type))?; ss.serialize_field("dictionary_intrinsic_left_bracket", &self.with(left_bracket))?; ss.serialize_field("dictionary_intrinsic_members", &self.with(members))?; ss.serialize_field("dictionary_intrinsic_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::KeysetIntrinsicExpression (KeysetIntrinsicExpressionChildren{keyword,explicit_type,left_bracket,members,right_bracket} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "keyset_intrinsic_expression")?; ss.serialize_field("keyset_intrinsic_keyword", &self.with(keyword))?; ss.serialize_field("keyset_intrinsic_explicit_type", &self.with(explicit_type))?; ss.serialize_field("keyset_intrinsic_left_bracket", &self.with(left_bracket))?; ss.serialize_field("keyset_intrinsic_members", &self.with(members))?; ss.serialize_field("keyset_intrinsic_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::VarrayIntrinsicExpression (VarrayIntrinsicExpressionChildren{keyword,explicit_type,left_bracket,members,right_bracket} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "varray_intrinsic_expression")?; ss.serialize_field("varray_intrinsic_keyword", &self.with(keyword))?; ss.serialize_field("varray_intrinsic_explicit_type", &self.with(explicit_type))?; ss.serialize_field("varray_intrinsic_left_bracket", &self.with(left_bracket))?; ss.serialize_field("varray_intrinsic_members", &self.with(members))?; ss.serialize_field("varray_intrinsic_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::VectorIntrinsicExpression (VectorIntrinsicExpressionChildren{keyword,explicit_type,left_bracket,members,right_bracket} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "vector_intrinsic_expression")?; ss.serialize_field("vector_intrinsic_keyword", &self.with(keyword))?; ss.serialize_field("vector_intrinsic_explicit_type", &self.with(explicit_type))?; ss.serialize_field("vector_intrinsic_left_bracket", &self.with(left_bracket))?; ss.serialize_field("vector_intrinsic_members", &self.with(members))?; ss.serialize_field("vector_intrinsic_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::ElementInitializer (ElementInitializerChildren{key,arrow,value} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "element_initializer")?; ss.serialize_field("element_key", &self.with(key))?; ss.serialize_field("element_arrow", &self.with(arrow))?; ss.serialize_field("element_value", &self.with(value))?; ss.end() } SyntaxVariant::SubscriptExpression (SubscriptExpressionChildren{receiver,left_bracket,index,right_bracket} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "subscript_expression")?; ss.serialize_field("subscript_receiver", &self.with(receiver))?; ss.serialize_field("subscript_left_bracket", &self.with(left_bracket))?; ss.serialize_field("subscript_index", &self.with(index))?; ss.serialize_field("subscript_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::EmbeddedSubscriptExpression (EmbeddedSubscriptExpressionChildren{receiver,left_bracket,index,right_bracket} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "embedded_subscript_expression")?; ss.serialize_field("embedded_subscript_receiver", &self.with(receiver))?; ss.serialize_field("embedded_subscript_left_bracket", &self.with(left_bracket))?; ss.serialize_field("embedded_subscript_index", &self.with(index))?; ss.serialize_field("embedded_subscript_right_bracket", &self.with(right_bracket))?; ss.end() } SyntaxVariant::AwaitableCreationExpression (AwaitableCreationExpressionChildren{attribute_spec,async_,compound_statement} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "awaitable_creation_expression")?; ss.serialize_field("awaitable_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("awaitable_async", &self.with(async_))?; ss.serialize_field("awaitable_compound_statement", &self.with(compound_statement))?; ss.end() } SyntaxVariant::XHPChildrenDeclaration (XHPChildrenDeclarationChildren{keyword,expression,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "xhp_children_declaration")?; ss.serialize_field("xhp_children_keyword", &self.with(keyword))?; ss.serialize_field("xhp_children_expression", &self.with(expression))?; ss.serialize_field("xhp_children_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::XHPChildrenParenthesizedList (XHPChildrenParenthesizedListChildren{left_paren,xhp_children,right_paren} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "xhp_children_parenthesized_list")?; ss.serialize_field("xhp_children_list_left_paren", &self.with(left_paren))?; ss.serialize_field("xhp_children_list_xhp_children", &self.with(xhp_children))?; ss.serialize_field("xhp_children_list_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::XHPCategoryDeclaration (XHPCategoryDeclarationChildren{keyword,categories,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "xhp_category_declaration")?; ss.serialize_field("xhp_category_keyword", &self.with(keyword))?; ss.serialize_field("xhp_category_categories", &self.with(categories))?; ss.serialize_field("xhp_category_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::XHPEnumType (XHPEnumTypeChildren{keyword,left_brace,values,right_brace} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "xhp_enum_type")?; ss.serialize_field("xhp_enum_keyword", &self.with(keyword))?; ss.serialize_field("xhp_enum_left_brace", &self.with(left_brace))?; ss.serialize_field("xhp_enum_values", &self.with(values))?; ss.serialize_field("xhp_enum_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::XHPLateinit (XHPLateinitChildren{at,keyword} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "xhp_lateinit")?; ss.serialize_field("xhp_lateinit_at", &self.with(at))?; ss.serialize_field("xhp_lateinit_keyword", &self.with(keyword))?; ss.end() } SyntaxVariant::XHPRequired (XHPRequiredChildren{at,keyword} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "xhp_required")?; ss.serialize_field("xhp_required_at", &self.with(at))?; ss.serialize_field("xhp_required_keyword", &self.with(keyword))?; ss.end() } SyntaxVariant::XHPClassAttributeDeclaration (XHPClassAttributeDeclarationChildren{keyword,attributes,semicolon} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "xhp_class_attribute_declaration")?; ss.serialize_field("xhp_attribute_keyword", &self.with(keyword))?; ss.serialize_field("xhp_attribute_attributes", &self.with(attributes))?; ss.serialize_field("xhp_attribute_semicolon", &self.with(semicolon))?; ss.end() } SyntaxVariant::XHPClassAttribute (XHPClassAttributeChildren{type_,name,initializer,required} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "xhp_class_attribute")?; ss.serialize_field("xhp_attribute_decl_type", &self.with(type_))?; ss.serialize_field("xhp_attribute_decl_name", &self.with(name))?; ss.serialize_field("xhp_attribute_decl_initializer", &self.with(initializer))?; ss.serialize_field("xhp_attribute_decl_required", &self.with(required))?; ss.end() } SyntaxVariant::XHPSimpleClassAttribute (XHPSimpleClassAttributeChildren{type_} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "xhp_simple_class_attribute")?; ss.serialize_field("xhp_simple_class_attribute_type", &self.with(type_))?; ss.end() } SyntaxVariant::XHPSimpleAttribute (XHPSimpleAttributeChildren{name,equal,expression} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "xhp_simple_attribute")?; ss.serialize_field("xhp_simple_attribute_name", &self.with(name))?; ss.serialize_field("xhp_simple_attribute_equal", &self.with(equal))?; ss.serialize_field("xhp_simple_attribute_expression", &self.with(expression))?; ss.end() } SyntaxVariant::XHPSpreadAttribute (XHPSpreadAttributeChildren{left_brace,spread_operator,expression,right_brace} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "xhp_spread_attribute")?; ss.serialize_field("xhp_spread_attribute_left_brace", &self.with(left_brace))?; ss.serialize_field("xhp_spread_attribute_spread_operator", &self.with(spread_operator))?; ss.serialize_field("xhp_spread_attribute_expression", &self.with(expression))?; ss.serialize_field("xhp_spread_attribute_right_brace", &self.with(right_brace))?; ss.end() } SyntaxVariant::XHPOpen (XHPOpenChildren{left_angle,name,attributes,right_angle} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "xhp_open")?; ss.serialize_field("xhp_open_left_angle", &self.with(left_angle))?; ss.serialize_field("xhp_open_name", &self.with(name))?; ss.serialize_field("xhp_open_attributes", &self.with(attributes))?; ss.serialize_field("xhp_open_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::XHPExpression (XHPExpressionChildren{open,body,close} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "xhp_expression")?; ss.serialize_field("xhp_open", &self.with(open))?; ss.serialize_field("xhp_body", &self.with(body))?; ss.serialize_field("xhp_close", &self.with(close))?; ss.end() } SyntaxVariant::XHPClose (XHPCloseChildren{left_angle,name,right_angle} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "xhp_close")?; ss.serialize_field("xhp_close_left_angle", &self.with(left_angle))?; ss.serialize_field("xhp_close_name", &self.with(name))?; ss.serialize_field("xhp_close_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::TypeConstant (TypeConstantChildren{left_type,separator,right_type} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "type_constant")?; ss.serialize_field("type_constant_left_type", &self.with(left_type))?; ss.serialize_field("type_constant_separator", &self.with(separator))?; ss.serialize_field("type_constant_right_type", &self.with(right_type))?; ss.end() } SyntaxVariant::VectorTypeSpecifier (VectorTypeSpecifierChildren{keyword,left_angle,type_,trailing_comma,right_angle} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "vector_type_specifier")?; ss.serialize_field("vector_type_keyword", &self.with(keyword))?; ss.serialize_field("vector_type_left_angle", &self.with(left_angle))?; ss.serialize_field("vector_type_type", &self.with(type_))?; ss.serialize_field("vector_type_trailing_comma", &self.with(trailing_comma))?; ss.serialize_field("vector_type_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::KeysetTypeSpecifier (KeysetTypeSpecifierChildren{keyword,left_angle,type_,trailing_comma,right_angle} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "keyset_type_specifier")?; ss.serialize_field("keyset_type_keyword", &self.with(keyword))?; ss.serialize_field("keyset_type_left_angle", &self.with(left_angle))?; ss.serialize_field("keyset_type_type", &self.with(type_))?; ss.serialize_field("keyset_type_trailing_comma", &self.with(trailing_comma))?; ss.serialize_field("keyset_type_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::TupleTypeExplicitSpecifier (TupleTypeExplicitSpecifierChildren{keyword,left_angle,types,right_angle} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "tuple_type_explicit_specifier")?; ss.serialize_field("tuple_type_keyword", &self.with(keyword))?; ss.serialize_field("tuple_type_left_angle", &self.with(left_angle))?; ss.serialize_field("tuple_type_types", &self.with(types))?; ss.serialize_field("tuple_type_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::VarrayTypeSpecifier (VarrayTypeSpecifierChildren{keyword,left_angle,type_,trailing_comma,right_angle} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "varray_type_specifier")?; ss.serialize_field("varray_keyword", &self.with(keyword))?; ss.serialize_field("varray_left_angle", &self.with(left_angle))?; ss.serialize_field("varray_type", &self.with(type_))?; ss.serialize_field("varray_trailing_comma", &self.with(trailing_comma))?; ss.serialize_field("varray_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::FunctionCtxTypeSpecifier (FunctionCtxTypeSpecifierChildren{keyword,variable} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "function_ctx_type_specifier")?; ss.serialize_field("function_ctx_type_keyword", &self.with(keyword))?; ss.serialize_field("function_ctx_type_variable", &self.with(variable))?; ss.end() } SyntaxVariant::TypeParameter (TypeParameterChildren{attribute_spec,reified,variance,name,param_params,constraints} ) => { let mut ss = s.serialize_struct("", 7)?; ss.serialize_field("kind", "type_parameter")?; ss.serialize_field("type_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("type_reified", &self.with(reified))?; ss.serialize_field("type_variance", &self.with(variance))?; ss.serialize_field("type_name", &self.with(name))?; ss.serialize_field("type_param_params", &self.with(param_params))?; ss.serialize_field("type_constraints", &self.with(constraints))?; ss.end() } SyntaxVariant::TypeConstraint (TypeConstraintChildren{keyword,type_} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "type_constraint")?; ss.serialize_field("constraint_keyword", &self.with(keyword))?; ss.serialize_field("constraint_type", &self.with(type_))?; ss.end() } SyntaxVariant::ContextConstraint (ContextConstraintChildren{keyword,ctx_list} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "context_constraint")?; ss.serialize_field("ctx_constraint_keyword", &self.with(keyword))?; ss.serialize_field("ctx_constraint_ctx_list", &self.with(ctx_list))?; ss.end() } SyntaxVariant::DarrayTypeSpecifier (DarrayTypeSpecifierChildren{keyword,left_angle,key,comma,value,trailing_comma,right_angle} ) => { let mut ss = s.serialize_struct("", 8)?; ss.serialize_field("kind", "darray_type_specifier")?; ss.serialize_field("darray_keyword", &self.with(keyword))?; ss.serialize_field("darray_left_angle", &self.with(left_angle))?; ss.serialize_field("darray_key", &self.with(key))?; ss.serialize_field("darray_comma", &self.with(comma))?; ss.serialize_field("darray_value", &self.with(value))?; ss.serialize_field("darray_trailing_comma", &self.with(trailing_comma))?; ss.serialize_field("darray_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::DictionaryTypeSpecifier (DictionaryTypeSpecifierChildren{keyword,left_angle,members,right_angle} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "dictionary_type_specifier")?; ss.serialize_field("dictionary_type_keyword", &self.with(keyword))?; ss.serialize_field("dictionary_type_left_angle", &self.with(left_angle))?; ss.serialize_field("dictionary_type_members", &self.with(members))?; ss.serialize_field("dictionary_type_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::ClosureTypeSpecifier (ClosureTypeSpecifierChildren{outer_left_paren,readonly_keyword,function_keyword,inner_left_paren,parameter_list,inner_right_paren,contexts,colon,readonly_return,return_type,outer_right_paren} ) => { let mut ss = s.serialize_struct("", 12)?; ss.serialize_field("kind", "closure_type_specifier")?; ss.serialize_field("closure_outer_left_paren", &self.with(outer_left_paren))?; ss.serialize_field("closure_readonly_keyword", &self.with(readonly_keyword))?; ss.serialize_field("closure_function_keyword", &self.with(function_keyword))?; ss.serialize_field("closure_inner_left_paren", &self.with(inner_left_paren))?; ss.serialize_field("closure_parameter_list", &self.with(parameter_list))?; ss.serialize_field("closure_inner_right_paren", &self.with(inner_right_paren))?; ss.serialize_field("closure_contexts", &self.with(contexts))?; ss.serialize_field("closure_colon", &self.with(colon))?; ss.serialize_field("closure_readonly_return", &self.with(readonly_return))?; ss.serialize_field("closure_return_type", &self.with(return_type))?; ss.serialize_field("closure_outer_right_paren", &self.with(outer_right_paren))?; ss.end() } SyntaxVariant::ClosureParameterTypeSpecifier (ClosureParameterTypeSpecifierChildren{call_convention,readonly,type_} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "closure_parameter_type_specifier")?; ss.serialize_field("closure_parameter_call_convention", &self.with(call_convention))?; ss.serialize_field("closure_parameter_readonly", &self.with(readonly))?; ss.serialize_field("closure_parameter_type", &self.with(type_))?; ss.end() } SyntaxVariant::ClassnameTypeSpecifier (ClassnameTypeSpecifierChildren{keyword,left_angle,type_,trailing_comma,right_angle} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "classname_type_specifier")?; ss.serialize_field("classname_keyword", &self.with(keyword))?; ss.serialize_field("classname_left_angle", &self.with(left_angle))?; ss.serialize_field("classname_type", &self.with(type_))?; ss.serialize_field("classname_trailing_comma", &self.with(trailing_comma))?; ss.serialize_field("classname_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::FieldSpecifier (FieldSpecifierChildren{question,name,arrow,type_} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "field_specifier")?; ss.serialize_field("field_question", &self.with(question))?; ss.serialize_field("field_name", &self.with(name))?; ss.serialize_field("field_arrow", &self.with(arrow))?; ss.serialize_field("field_type", &self.with(type_))?; ss.end() } SyntaxVariant::FieldInitializer (FieldInitializerChildren{name,arrow,value} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "field_initializer")?; ss.serialize_field("field_initializer_name", &self.with(name))?; ss.serialize_field("field_initializer_arrow", &self.with(arrow))?; ss.serialize_field("field_initializer_value", &self.with(value))?; ss.end() } SyntaxVariant::ShapeTypeSpecifier (ShapeTypeSpecifierChildren{keyword,left_paren,fields,ellipsis,right_paren} ) => { let mut ss = s.serialize_struct("", 6)?; ss.serialize_field("kind", "shape_type_specifier")?; ss.serialize_field("shape_type_keyword", &self.with(keyword))?; ss.serialize_field("shape_type_left_paren", &self.with(left_paren))?; ss.serialize_field("shape_type_fields", &self.with(fields))?; ss.serialize_field("shape_type_ellipsis", &self.with(ellipsis))?; ss.serialize_field("shape_type_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::ShapeExpression (ShapeExpressionChildren{keyword,left_paren,fields,right_paren} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "shape_expression")?; ss.serialize_field("shape_expression_keyword", &self.with(keyword))?; ss.serialize_field("shape_expression_left_paren", &self.with(left_paren))?; ss.serialize_field("shape_expression_fields", &self.with(fields))?; ss.serialize_field("shape_expression_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::TupleExpression (TupleExpressionChildren{keyword,left_paren,items,right_paren} ) => { let mut ss = s.serialize_struct("", 5)?; ss.serialize_field("kind", "tuple_expression")?; ss.serialize_field("tuple_expression_keyword", &self.with(keyword))?; ss.serialize_field("tuple_expression_left_paren", &self.with(left_paren))?; ss.serialize_field("tuple_expression_items", &self.with(items))?; ss.serialize_field("tuple_expression_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::GenericTypeSpecifier (GenericTypeSpecifierChildren{class_type,argument_list} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "generic_type_specifier")?; ss.serialize_field("generic_class_type", &self.with(class_type))?; ss.serialize_field("generic_argument_list", &self.with(argument_list))?; ss.end() } SyntaxVariant::NullableTypeSpecifier (NullableTypeSpecifierChildren{question,type_} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "nullable_type_specifier")?; ss.serialize_field("nullable_question", &self.with(question))?; ss.serialize_field("nullable_type", &self.with(type_))?; ss.end() } SyntaxVariant::LikeTypeSpecifier (LikeTypeSpecifierChildren{tilde,type_} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "like_type_specifier")?; ss.serialize_field("like_tilde", &self.with(tilde))?; ss.serialize_field("like_type", &self.with(type_))?; ss.end() } SyntaxVariant::SoftTypeSpecifier (SoftTypeSpecifierChildren{at,type_} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "soft_type_specifier")?; ss.serialize_field("soft_at", &self.with(at))?; ss.serialize_field("soft_type", &self.with(type_))?; ss.end() } SyntaxVariant::AttributizedSpecifier (AttributizedSpecifierChildren{attribute_spec,type_} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "attributized_specifier")?; ss.serialize_field("attributized_specifier_attribute_spec", &self.with(attribute_spec))?; ss.serialize_field("attributized_specifier_type", &self.with(type_))?; ss.end() } SyntaxVariant::ReifiedTypeArgument (ReifiedTypeArgumentChildren{reified,type_} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "reified_type_argument")?; ss.serialize_field("reified_type_argument_reified", &self.with(reified))?; ss.serialize_field("reified_type_argument_type", &self.with(type_))?; ss.end() } SyntaxVariant::TypeArguments (TypeArgumentsChildren{left_angle,types,right_angle} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "type_arguments")?; ss.serialize_field("type_arguments_left_angle", &self.with(left_angle))?; ss.serialize_field("type_arguments_types", &self.with(types))?; ss.serialize_field("type_arguments_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::TypeParameters (TypeParametersChildren{left_angle,parameters,right_angle} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "type_parameters")?; ss.serialize_field("type_parameters_left_angle", &self.with(left_angle))?; ss.serialize_field("type_parameters_parameters", &self.with(parameters))?; ss.serialize_field("type_parameters_right_angle", &self.with(right_angle))?; ss.end() } SyntaxVariant::TupleTypeSpecifier (TupleTypeSpecifierChildren{left_paren,types,right_paren} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "tuple_type_specifier")?; ss.serialize_field("tuple_left_paren", &self.with(left_paren))?; ss.serialize_field("tuple_types", &self.with(types))?; ss.serialize_field("tuple_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::UnionTypeSpecifier (UnionTypeSpecifierChildren{left_paren,types,right_paren} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "union_type_specifier")?; ss.serialize_field("union_left_paren", &self.with(left_paren))?; ss.serialize_field("union_types", &self.with(types))?; ss.serialize_field("union_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::IntersectionTypeSpecifier (IntersectionTypeSpecifierChildren{left_paren,types,right_paren} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "intersection_type_specifier")?; ss.serialize_field("intersection_left_paren", &self.with(left_paren))?; ss.serialize_field("intersection_types", &self.with(types))?; ss.serialize_field("intersection_right_paren", &self.with(right_paren))?; ss.end() } SyntaxVariant::ErrorSyntax (ErrorSyntaxChildren{error} ) => { let mut ss = s.serialize_struct("", 2)?; ss.serialize_field("kind", "error")?; ss.serialize_field("error_error", &self.with(error))?; ss.end() } SyntaxVariant::ListItem (ListItemChildren{item,separator} ) => { let mut ss = s.serialize_struct("", 3)?; ss.serialize_field("kind", "list_item")?; ss.serialize_field("list_item", &self.with(item))?; ss.serialize_field("list_separator", &self.with(separator))?; ss.end() } SyntaxVariant::EnumClassLabelExpression (EnumClassLabelExpressionChildren{qualifier,hash,expression} ) => { let mut ss = s.serialize_struct("", 4)?; ss.serialize_field("kind", "enum_class_label")?; ss.serialize_field("enum_class_label_qualifier", &self.with(qualifier))?; ss.serialize_field("enum_class_label_hash", &self.with(hash))?; ss.serialize_field("enum_class_label_expression", &self.with(expression))?; ss.end() } } } }
serialize
utils.py
''' Created on Nov 9, 2017 @author: khoi.ngo ''' def generate_random_string(prefix="", suffix="", size=20): """ Generate random string . :param prefix: (optional) Prefix of a string. :param suffix: (optional) Suffix of a string. :param length: (optional) Max length of a string (include prefix and suffix) :return: The random string. """ import random import string left_size = size - len(prefix) - len(suffix) random_str = "" if left_size > 0: random_str = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(left_size)) else: print("Warning: Length of prefix and suffix more than %s chars" % str(size)) result = str(prefix) + random_str + str(suffix) return result def create_step(size): from utils.step import Step lst_step = [] for i in range(0, size): step = Step(i, "") lst_step.append(step) return lst_step def handle_exception(code): if isinstance(code, IndexError or Exception): raise code else: return code async def perform(step, func, *agrs): from indy.error import IndyError from utils.report import Status result = None try: result = await func(*agrs) step.set_status(Status.PASSED) except IndyError as E: print("Indy error" + str(E)) step.set_message(str(E)) return E except Exception as Ex: print("Exception" + str(Ex)) step.set_message(str(E)) return Ex return result async def perform_with_expected_code(step, func, *agrs, expected_code=0): from indy.error import IndyError from utils.report import Status try: await func(*agrs) except IndyError as E: if E == expected_code:
else: print("Indy error" + str(E)) step.set_message(str(E)) return E except Exception as Ex: print("Exception" + str(Ex)) return Ex
step.set_status(Status.PASSED)
store.js
import Vue from 'vue' import Vuex from 'vuex' import router from './router' import axios from 'axios' import {isNull} from "bootstrap-vue/esm/utils/inspect"; import {from} from "bootstrap-vue/esm/utils/array"; // test it. Vue.use(Vuex) export default new Vuex.Store({ state:{ userInfo: null, isLogin: false, isLoginError: true }, mutations: {
state.isLoginError = false }, //login fail loginError(state){ state.isLogin = false, state.isLoginError = true }, logout(state) { state.isLogin = false, state.isLoginError = false, sessionStorage.removeItem("access_token"); } }, actions:{ getToken() { const token = sessionStorage.getItem("access_token") console.log(token) return token }, //try login login({ commit}, loginObj) { // Login => token return axios .post("/login", loginObj) .then(res => { let response = res.data console.log(response) if(response['code'] == '200') { sessionStorage.setItem("access_token", response['access_token']) let token = sessionStorage.getItem("access_token") let config = { headers: { "Authorization": token } } commit('loginSuccess') router.push("/Books") } else { alert(' Check your Id&PW 1') } }) .catch(() => { alert(' Check your Id&PW 2') }) }, register({ commit }, registerObj) { if (registerObj['password'] == registerObj['passwordConfirm']) { axios .post("/api/register", registerObj) .then(res => { let response = res.data { console.log(response) if (response['code'] == '404') { alert(' Already exist ID') } else { alert(' Register Success') router.go(-1) } } }) } else { alert('password is not same') } }, loginRefresh( {commit} ) { let token = sessionStorage.getItem("access_token"); if (token != null) { commit("loginSuccess") router.push("/dashboard") } else commit('loginError') }, logout({commit}) { commit("logout") router.push("/login") }, } })
//login success loginSuccess(state){ state.isLogin = true,
protocol.rs
use std::time::{SystemTime, UNIX_EPOCH}; use aes::cipher::{AsyncStreamCipher, KeyIvInit}; use anyhow::{anyhow, Result}; use byteorder::{BigEndian, ByteOrder}; use bytes::{BufMut, BytesMut}; use hmac::{Hmac, Mac}; use lz_fnv::{Fnv1a, FnvHasher}; use md5::{Digest, Md5}; use rand::{rngs::StdRng, Rng, SeedableRng}; use uuid::Uuid; use crate::session::{SocksAddr, SocksAddrWireType}; type RequestCommand = u8; pub const REQUEST_COMMAND_TCP: RequestCommand = 0x01; pub const REQUEST_COMMAND_UDP: RequestCommand = 0x02; type Security = u8; pub const SECURITY_TYPE_AES128_GCM: Security = 0x03; pub const SECURITY_TYPE_CHACHA20_POLY1305: Security = 0x04; type RequestOption = u8; pub const REQUEST_OPTION_CHUNK_STREAM: RequestOption = 0x01; pub const REQUEST_OPTION_CHUNK_MASKING: RequestOption = 0x04; pub const REQUEST_OPTION_GLOBAL_PADDING: RequestOption = 0x08; pub struct RequestHeader { pub version: u8, pub command: RequestCommand, pub option: u8, pub security: Security, pub address: SocksAddr, pub uuid: Uuid, } impl RequestHeader { pub fn set_option(&mut self, opt: RequestOption) { self.option |= opt; } pub fn encode(&self, buf: &mut BytesMut, sess: &ClientSession) -> Result<()> { // generate auth info let mut timestamp = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(n) => n.as_secs(), Err(_) => return Err(anyhow!("invalid system time")), }; let mut rng = StdRng::from_entropy(); let delta: i32 = rng.gen_range(0..30 * 2) - 30; timestamp = timestamp.wrapping_add(delta as u64); let mut mac = Hmac::<Md5>::new_from_slice(self.uuid.as_bytes()).map_err(|_| anyhow!("md5 failed"))?; let mut tmp = [0u8; 8]; BigEndian::write_u64(&mut tmp, timestamp as u64); mac.update(&tmp); let auth_info = mac.finalize().into_bytes(); buf.put_slice(&auth_info[..]); buf.put_u8(self.version); buf.put_slice(&sess.request_body_iv); buf.put_slice(&sess.request_body_key); buf.put_u8(sess.response_header); buf.put_u8(self.option); let padding_len = StdRng::from_entropy().gen_range(0..16) as u8; let security = (padding_len << 4) | self.security as u8; buf.put_u8(security); buf.put_u8(0); buf.put_u8(self.command); self.address.write_buf(buf, SocksAddrWireType::PortFirst); // add random bytes if padding_len > 0 { let mut padding_bytes = BytesMut::with_capacity(padding_len as usize); unsafe { padding_bytes.set_len(padding_len as usize) }; let mut rng = StdRng::from_entropy(); for i in 0..padding_bytes.len() { padding_bytes[i] = rng.gen(); } buf.put_slice(&padding_bytes); } // checksum let mut hasher = Fnv1a::<u32>::default(); hasher.write(&buf[auth_info.len()..]); let h = hasher.finish(); let buf_size = buf.len(); buf.resize(buf_size + 4, 0); BigEndian::write_u32(&mut buf[buf_size..], h); // iv for header encryption let mut tmp = [0u8; 8]; BigEndian::write_u64(&mut tmp, timestamp as u64); let mut hasher = Md5::new(); hasher.update(&tmp); hasher.update(&tmp); hasher.update(&tmp); hasher.update(&tmp); let iv = hasher.finalize(); // key for header ecnryption let mut hasher = Md5::new(); hasher.update(self.uuid.as_bytes()); hasher.update( "c48619fe-8f02-49e0-b9e9-edf763e17e21" .to_string() .as_bytes(), ); let key = hasher.finalize(); // encrypt cmd part cfb_mode::Encryptor::<aes::Aes128>::new(&key, &iv).encrypt(&mut buf[auth_info.len()..]); Ok(()) } } pub struct ClientSession { pub request_body_key: Vec<u8>, pub request_body_iv: Vec<u8>, pub response_body_key: Vec<u8>, pub response_body_iv: Vec<u8>, pub response_header: u8, } impl ClientSession { pub fn new() -> Self { let mut request_body_key = vec![0u8; 16]; let mut request_body_iv = vec![0u8; 16]; let response_header: u8; // fill random bytes let mut rand_bytes = BytesMut::with_capacity(16 + 16 + 1); unsafe { rand_bytes.set_len(16 + 16 + 1) }; let mut rng = StdRng::from_entropy(); for i in 0..rand_bytes.len() { rand_bytes[i] = rng.gen(); } (&mut request_body_key[..]).copy_from_slice(&rand_bytes[..16]); (&mut request_body_iv[..]).copy_from_slice(&rand_bytes[16..32]); response_header = rand_bytes[32]; let response_body_key = Md5::digest(&request_body_key).to_vec(); let response_body_iv = Md5::digest(&request_body_iv).to_vec();
ClientSession { request_body_key, request_body_iv, response_body_key, response_body_iv, response_header, } } }
index.ts
import elementResizeDetectorMaker from "element-resize-detector"; let erd = elementResizeDetectorMaker({ strategy: "scroll" }); function
(element: HTMLElement, handler: (element: HTMLElement) => void) { erd.listenTo(element, handler); let currentHandler = handler; return { update(newHandler: (element: HTMLElement) => void) { erd.removeListener(element, currentHandler); erd.listenTo(element, newHandler); currentHandler = newHandler; }, destroy() { erd.removeListener(element, currentHandler); }, }; } export { watchResize };
watchResize
block_device.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BlockDeviceError { /// Hardware didn't behave as expected, unrecoverable HardwareError, /// Error during writing; most likely value read back after write was wrong WriteError, /// Error during erase; most likely value read back after erase was wrong /// /// STM32 flash programming app note implies this is possible but doesn't say under what /// circumstances. Is the flash knackered if this happens? EraseError, /// Address is invalid or out of range InvalidAddress, /// Media not ready NotReady, } pub trait BlockDevice { /// The number of bytes per block. This determines the size of the buffer passed /// to read/write functions const BLOCK_BYTES: usize; /// Read the block indicated by `lba` into the provided buffer fn read_block(&mut self, lba: u32, block: &mut [u8]) -> Result<(), BlockDeviceError>; /// Write the `block` buffer to the block indicated by `lba` fn write_block(&mut self, lba: u32, block: &[u8]) -> Result<(), BlockDeviceError>; /// Get the maxium valid lba (logical block address) fn max_lba(&self) -> u32; /// Get Write-protect status fn is_write_protected(&self) -> bool
/// Get Device ready status fn is_ready(&self) -> bool { true } }
{ false }
signature_sets.rs
//! A `SignatureSet` is an abstraction over the components of a signature. A `SignatureSet` may be //! validated individually, or alongside in others in a potentially cheaper bulk operation. //! //! This module exposes one function to extract each type of `SignatureSet` from a `BeaconBlock`. use bls::{G1Point, G1Ref, SignatureSet, SignedMessage}; use std::borrow::Cow; use std::convert::TryInto; use tree_hash::{SignedRoot, TreeHash}; use types::{ AggregateSignature, AttesterSlashing, BeaconBlock, BeaconBlockHeader, BeaconState, BeaconStateError, ChainSpec, DepositData, Domain, EthSpec, Hash256, IndexedAttestation, ProposerSlashing, PublicKey, Signature, VoluntaryExit, }; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug, PartialEq)] pub enum Error { /// Signature verification failed. The block is invalid. SignatureInvalid, /// There was an error attempting to read from a `BeaconState`. Block /// validity was not determined. BeaconStateError(BeaconStateError), /// Attempted to find the public key of a validator that does not exist. You cannot distinguish /// between an error and an invalid block in this case. ValidatorUnknown(u64), /// The public keys supplied do not match the number of objects requiring keys. Block validity /// was not determined. MismatchedPublicKeyLen { pubkey_len: usize, other_len: usize }, /// The public key bytes stored in the `BeaconState` were not valid. This is a serious internal /// error. BadBlsBytes { validator_index: u64 }, } impl From<BeaconStateError> for Error { fn from(e: BeaconStateError) -> Error { Error::BeaconStateError(e) } } /// A signature set that is valid if a block was signed by the expected block producer. pub fn block_proposal_signature_set<'a, T: EthSpec>( state: &'a BeaconState<T>, block: &'a BeaconBlock<T>, block_signed_root: Option<Hash256>, spec: &'a ChainSpec, ) -> Result<SignatureSet<'a>> { let proposer_index = state.get_beacon_proposer_index(block.slot, spec)?; let domain = spec.get_domain( block.slot.epoch(T::slots_per_epoch()), Domain::BeaconProposer, &state.fork, ); let message = if let Some(root) = block_signed_root { root.as_bytes().to_vec() } else { block.signed_root() }; Ok(SignatureSet::single( &block.signature, validator_pubkey(state, proposer_index)?, message, domain, )) } /// A signature set that is valid if the block proposers randao reveal signature is correct. pub fn randao_signature_set<'a, T: EthSpec>( state: &'a BeaconState<T>, block: &'a BeaconBlock<T>, spec: &'a ChainSpec, ) -> Result<SignatureSet<'a>> { let proposer_index = state.get_beacon_proposer_index(block.slot, spec)?; let domain = spec.get_domain( block.slot.epoch(T::slots_per_epoch()), Domain::Randao, &state.fork, ); let message = state.current_epoch().tree_hash_root(); Ok(SignatureSet::single( &block.body.randao_reveal, validator_pubkey(state, proposer_index)?, message, domain, )) } /// Returns two signature sets, one for each `BlockHeader` included in the `ProposerSlashing`. pub fn proposer_slashing_signature_set<'a, T: EthSpec>( state: &'a BeaconState<T>, proposer_slashing: &'a ProposerSlashing, spec: &'a ChainSpec, ) -> Result<(SignatureSet<'a>, SignatureSet<'a>)>
/// Returns a signature set that is valid if the given `pubkey` signed the `header`. fn block_header_signature_set<'a, T: EthSpec>( state: &'a BeaconState<T>, header: &'a BeaconBlockHeader, pubkey: Cow<'a, G1Point>, spec: &'a ChainSpec, ) -> Result<SignatureSet<'a>> { let domain = spec.get_domain( header.slot.epoch(T::slots_per_epoch()), Domain::BeaconProposer, &state.fork, ); let message = header.signed_root(); Ok(SignatureSet::single( &header.signature, pubkey, message, domain, )) } /// Returns the signature set for the given `indexed_attestation`. pub fn indexed_attestation_signature_set<'a, 'b, T: EthSpec>( state: &'a BeaconState<T>, signature: &'a AggregateSignature, indexed_attestation: &'b IndexedAttestation<T>, spec: &'a ChainSpec, ) -> Result<SignatureSet<'a>> { let message = indexed_attestation.data.tree_hash_root(); let pubkeys = indexed_attestation .attesting_indices .into_iter() .map(|&validator_idx| Ok(validator_pubkey(state, validator_idx as usize)?)) .collect::<Result<_>>()?; let signed_message = SignedMessage::new(pubkeys, message); let domain = spec.get_domain( indexed_attestation.data.target.epoch, Domain::BeaconAttester, &state.fork, ); Ok(SignatureSet::new(signature, vec![signed_message], domain)) } /// Returns the signature set for the given `attester_slashing` and corresponding `pubkeys`. pub fn attester_slashing_signature_sets<'a, T: EthSpec>( state: &'a BeaconState<T>, attester_slashing: &'a AttesterSlashing<T>, spec: &'a ChainSpec, ) -> Result<(SignatureSet<'a>, SignatureSet<'a>)> { Ok(( indexed_attestation_signature_set( state, &attester_slashing.attestation_1.signature, &attester_slashing.attestation_1, spec, )?, indexed_attestation_signature_set( state, &attester_slashing.attestation_2.signature, &attester_slashing.attestation_2, spec, )?, )) } /// Returns the BLS values in a `Deposit`, if they're all valid. Otherwise, returns `None`. /// /// This method is separate to `deposit_signature_set` to satisfy lifetime requirements. pub fn deposit_pubkey_signature_message( deposit_data: &DepositData, ) -> Option<(PublicKey, Signature, Vec<u8>)> { let pubkey = (&deposit_data.pubkey).try_into().ok()?; let signature = (&deposit_data.signature).try_into().ok()?; let message = deposit_data.signed_root(); Some((pubkey, signature, message)) } /// Returns the signature set for some set of deposit signatures, made with /// `deposit_pubkey_signature_message`. pub fn deposit_signature_set<'a>( pubkey_signature_message: &'a (PublicKey, Signature, Vec<u8>), spec: &'a ChainSpec, ) -> SignatureSet<'a> { let (pubkey, signature, message) = pubkey_signature_message; // Note: Deposits are valid across forks, thus the deposit domain is computed // with the fork zeroed. SignatureSet::single( signature, pubkey.g1_ref(), message.clone(), spec.get_deposit_domain(), ) } /// Returns a signature set that is valid if the `VoluntaryExit` was signed by the indicated /// validator. pub fn exit_signature_set<'a, T: EthSpec>( state: &'a BeaconState<T>, exit: &'a VoluntaryExit, spec: &'a ChainSpec, ) -> Result<SignatureSet<'a>> { let proposer_index = exit.validator_index as usize; let domain = spec.get_domain(exit.epoch, Domain::VoluntaryExit, &state.fork); let message = exit.signed_root(); Ok(SignatureSet::single( &exit.signature, validator_pubkey(state, proposer_index)?, message, domain, )) } /// Maps a validator index to a `PublicKey`. fn validator_pubkey<'a, T: EthSpec>( state: &'a BeaconState<T>, validator_index: usize, ) -> Result<Cow<'a, G1Point>> { let pubkey_bytes = &state .validators .get(validator_index) .ok_or_else(|| Error::ValidatorUnknown(validator_index as u64))? .pubkey; pubkey_bytes .try_into() .map(|pubkey: PublicKey| Cow::Owned(pubkey.as_raw().point.clone())) .map_err(|_| Error::BadBlsBytes { validator_index: validator_index as u64, }) }
{ let proposer_index = proposer_slashing.proposer_index as usize; Ok(( block_header_signature_set( state, &proposer_slashing.header_1, validator_pubkey(state, proposer_index)?, spec, )?, block_header_signature_set( state, &proposer_slashing.header_2, validator_pubkey(state, proposer_index)?, spec, )?, )) }
__init__.py
from abc import ABC, abstractmethod from app.shared.operation import Operation class APIModelBase(ABC): def __init__(self):
@abstractmethod def exec(self) -> None: pass @abstractmethod def to_response(self) -> tuple: pass def load(self, operation: Operation): self.detail = operation.detail self.status_code = operation.status_code self.was_successful = operation.was_successful
self.detail: str = "" self.status_code: int | None = None self.was_successful: bool = False
index.tsx
import React, { FunctionComponent } from 'react' import { Joystick } from 'react-joystick-component' import { GamepadAxis, GamepadButtons } from '@xrengine/engine/src/input/enums/InputEnums' import TouchAppIcon from '@mui/icons-material/TouchApp' import styles from './index.module.scss' import { TouchGamepadProps } from './TouchGamepadProps' export const TouchGamepad: FunctionComponent<TouchGamepadProps> = () => { const triggerButton = (button: GamepadButtons, pressed: boolean): void => { const eventType = pressed ? 'touchgamepadbuttondown' : 'touchgamepadbuttonup' const event = new CustomEvent(eventType, { detail: { button } }) document.dispatchEvent(event) } const buttonsConfig: Array<{ button: GamepadButtons; label: string }> = [ { button: GamepadButtons.A, label: 'A' } ] const buttons = buttonsConfig.map((value, index) => { return ( <div
} onPointerDown={(): void => triggerButton(value.button, true)} onPointerUp={(): void => triggerButton(value.button, false)} > <TouchAppIcon /> </div> ) }) const normalizeValues = (val) => { const a = 1 const b = -1 const maxVal = 50 const minVal = -50 const newValue = (b - a) * ((val - minVal) / (maxVal - minVal)) + a return newValue } const handleMove = (e) => { const event = new CustomEvent('touchstickmove', { detail: { stick: GamepadAxis.Left, value: { x: normalizeValues(-e.y), y: normalizeValues(e.x), angleRad: 0 } } }) document.dispatchEvent(event) } const handleStop = () => { const event = new CustomEvent('touchstickmove', { detail: { stick: GamepadAxis.Left, value: { x: 0, y: 0, angleRad: 0 } } }) document.dispatchEvent(event) } return ( <> <div className={styles.stickLeft}> <Joystick size={100} throttle={100} minDistance={40} move={handleMove} stop={handleStop} baseColor="rgba(255, 255, 255, 0.5)" stickColor="rgba(255, 255, 255, 0.8)" /> </div> <div className={styles.controlButtonContainer}>{buttons}</div> </> ) } export default TouchGamepad
key={index} className={ styles.controllButton + ' ' + styles[`gamepadButton_${value.label}`] + ' ' + styles.availableButton // (hovered ? styles.availableButton : styles.notAvailableButton)
views.py
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Chris Caron <[email protected]> # All rights reserved. # # This code is licensed under the MIT License. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files(the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and / or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions : # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views import View from django.conf import settings from django.utils.html import escape from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.decorators.gzip import gzip_page from django.utils.translation import gettext_lazy as _ from django.core.serializers.json import DjangoJSONEncoder from .utils import ConfigCache from .forms import AddByUrlForm from .forms import AddByConfigForm from .forms import NotifyForm from .forms import NotifyByUrlForm from .forms import CONFIG_FORMATS from .forms import AUTO_DETECT_CONFIG_KEYWORD import apprise import json import re # import the logging library import logging # Get an instance of a logger logger = logging.getLogger('django') # Content-Type Parsing # application/x-www-form-urlencoded # application/x-www-form-urlencoded # multipart/form-data MIME_IS_FORM = re.compile( r'(multipart|application)/(x-www-)?form-(data|urlencoded)', re.I) # Support JSON formats # text/json # text/x-json # application/json # application/x-json MIME_IS_JSON = re.compile( r'(text|application)/(x-)?json', re.I) class JSONEncoder(DjangoJSONEncoder): """ A wrapper to the DjangoJSONEncoder to support sets() (converting them to lists). """ def default(self, obj): if isinstance(obj, set): return list(obj) return super().default(obj) class ResponseCode(object):
class WelcomeView(View): """ A simple welcome/index page """ template_name = 'welcome.html' def get(self, request): return render(request, self.template_name, {}) @method_decorator(never_cache, name='dispatch') class ConfigView(View): """ A Django view used to manage configuration """ template_name = 'config.html' def get(self, request, key): """ Handle a GET request """ return render(request, self.template_name, { 'key': key, 'form_url': AddByUrlForm(), 'form_cfg': AddByConfigForm(), 'form_notify': NotifyForm(), }) @method_decorator(never_cache, name='dispatch') class AddView(View): """ A Django view used to store Apprise configuration """ def post(self, request, key): """ Handle a POST request """ # Detect the format our response should be in json_response = MIME_IS_JSON.match(request.content_type) is not None if settings.APPRISE_CONFIG_LOCK: # General Access Control msg = _('The site has been configured to deny this request.') status = ResponseCode.no_access return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # our content content = {} if MIME_IS_FORM.match(request.content_type): content = {} form = AddByConfigForm(request.POST) if form.is_valid(): content.update(form.cleaned_data) form = AddByUrlForm(request.POST) if form.is_valid(): content.update(form.cleaned_data) elif json_response: # Prepare our default response try: # load our JSON content content = json.loads(request.body.decode('utf-8')) except (AttributeError, ValueError): # could not parse JSON response... return JsonResponse({ 'error': _('Invalid JSON specified.'), }, encoder=JSONEncoder, safe=False, status=ResponseCode.bad_request, ) if not content: # No information was posted msg = _('The message format is not supported.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Create ourselves an apprise object to work with a_obj = apprise.Apprise() if 'urls' in content: # Load our content a_obj.add(content['urls']) if not len(a_obj): # No URLs were loaded msg = _('No valid URLs were found.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) if not ConfigCache.put( key, '\r\n'.join([s.url() for s in a_obj]), apprise.ConfigFormat.TEXT): msg = _('The configuration could not be saved.') status = ResponseCode.internal_server_error return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) elif 'config' in content: fmt = content.get('format', '').lower() if fmt not in [i[0] for i in CONFIG_FORMATS]: # Format must be one supported by apprise msg = _('The format specified is invalid.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # prepare our apprise config object ac_obj = apprise.AppriseConfig() if fmt == AUTO_DETECT_CONFIG_KEYWORD: # By setting format to None, it is automatically detected from # within the add_config() call fmt = None # Load our configuration if not ac_obj.add_config(content['config'], format=fmt): # The format could not be detected msg = _('The configuration format could not be detected.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Add our configuration a_obj.add(ac_obj) if not len(a_obj): # No specified URL(s) were loaded due to # mis-configuration on the caller's part msg = _('No valid URL(s) were specified.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) if not ConfigCache.put( key, content['config'], fmt=ac_obj[0].config_format): # Something went very wrong; return 500 msg = _('An error occured saving configuration.') status = ResponseCode.internal_server_error return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) else: # No configuration specified; we're done msg = _('No configuration specified.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # If we reach here; we successfully loaded the configuration so we can # go ahead and write it to disk and alert our caller of the success. return HttpResponse( _('Successfully saved configuration.'), status=ResponseCode.okay, ) @method_decorator(never_cache, name='dispatch') class DelView(View): """ A Django view for removing content associated with a key """ def post(self, request, key): """ Handle a POST request """ # Detect the format our response should be in json_response = MIME_IS_JSON.match(request.content_type) is not None if settings.APPRISE_CONFIG_LOCK: # General Access Control msg = _('The site has been configured to deny this request.') status = ResponseCode.no_access return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Clear the key result = ConfigCache.clear(key) if result is None: msg = _('There was no configuration to remove.') status = ResponseCode.no_content return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) elif result is False: # There was a failure at the os level msg = _('The configuration could not be removed.') status = ResponseCode.internal_server_error return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Removed content return HttpResponse( _('Successfully removed configuration.'), status=ResponseCode.okay, ) @method_decorator((gzip_page, never_cache), name='dispatch') class GetView(View): """ A Django view used to retrieve previously stored Apprise configuration """ def post(self, request, key): """ Handle a POST request """ # Detect the format our response should be in json_response = MIME_IS_JSON.match(request.content_type) is not None if settings.APPRISE_CONFIG_LOCK: # General Access Control return HttpResponse( _('The site has been configured to deny this request.'), status=ResponseCode.no_access, ) if not json_response else JsonResponse({ 'error': _('The site has been configured to deny this request.') }, encoder=JSONEncoder, safe=False, status=ResponseCode.no_access, ) config, format = ConfigCache.get(key) if config is None: # The returned value of config and format tell a rather cryptic # story; this portion could probably be updated in the future. # but for now it reads like this: # config == None and format == None: We had an internal error # config == None and format != None: we simply have no data # config != None: we simply have no data if format is not None: # no content to return return HttpResponse( _('There was no configuration found.'), status=ResponseCode.no_content, ) if not json_response else JsonResponse({ 'error': _('There was no configuration found.') }, encoder=JSONEncoder, safe=False, status=ResponseCode.no_content, ) # Something went very wrong; return 500 msg = _('An error occured accessing configuration.') status = ResponseCode.internal_server_error return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Our configuration was retrieved; now our response varies on whether # we are a YAML configuration or a TEXT based one. This allows us to # be compatible with those using the AppriseConfig() library or the # reference to it through the --config (-c) option in the CLI. content_type = 'text/yaml; charset=utf-8' \ if format == apprise.ConfigFormat.YAML \ else 'text/html; charset=utf-8' # Return our retrieved content return HttpResponse( config, content_type=content_type, status=ResponseCode.okay, ) if not json_response else JsonResponse({ 'format': format, 'config': config, }, encoder=JSONEncoder, safe=False, status=ResponseCode.okay, ) @method_decorator((gzip_page, never_cache), name='dispatch') class NotifyView(View): """ A Django view for sending a notification """ def post(self, request, key): """ Handle a POST request """ # Detect the format our response should be in json_response = MIME_IS_JSON.match(request.content_type) is not None # our content content = {} if MIME_IS_FORM.match(request.content_type): content = {} form = NotifyForm(request.POST) if form.is_valid(): content.update(form.cleaned_data) elif json_response: # Prepare our default response try: # load our JSON content content = json.loads(request.body.decode('utf-8')) except (AttributeError, ValueError): # could not parse JSON response... return JsonResponse( _('Invalid JSON specified.'), encoder=JSONEncoder, safe=False, status=ResponseCode.bad_request) if not content: # We could not handle the Content-Type msg = _('The message format is not supported.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Some basic error checking if not content.get('body') or \ content.get('type', apprise.NotifyType.INFO) \ not in apprise.NOTIFY_TYPES: msg = _('An invalid payload was specified.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Acquire our body format (if identified) body_format = content.get('format', apprise.NotifyFormat.TEXT) if body_format and body_format not in apprise.NOTIFY_FORMATS: msg = _('An invalid body input format was specified.') status = ResponseCode.bad_request return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # If we get here, we have enough information to generate a notification # with. config, format = ConfigCache.get(key) if config is None: # The returned value of config and format tell a rather cryptic # story; this portion could probably be updated in the future. # but for now it reads like this: # config == None and format == None: We had an internal error # config == None and format != None: we simply have no data # config != None: we simply have no data if format is not None: # no content to return msg = _('There was no configuration found.') status = ResponseCode.no_content return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Something went very wrong; return 500 msg = _('An error occured accessing configuration.') status = ResponseCode.internal_server_error return HttpResponse(msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # # Apply Any Global Filters (if identified) # if settings.APPRISE_ALLOW_SERVICES: alphanum_re = re.compile( r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE) entries = \ [alphanum_re.match(x).group('name').lower() for x in re.split(r'[ ,]+', settings.APPRISE_ALLOW_SERVICES) if alphanum_re.match(x)] for plugin in set(apprise.plugins.SCHEMA_MAP.values()): if entries: # Get a list of the current schema's associated with # a given plugin schemas = set(apprise.plugins.details(plugin) ['tokens']['schema']['values']) # Check what was defined and see if there is a hit for entry in entries: if entry in schemas: # We had a hit; we're done break if entry in schemas: entries.remove(entry) # We can keep this plugin enabled and move along to the # next one... continue # if we reach here, we have to block our plugin plugin.enabled = False for entry in entries: # Generate some noise for those who have bad configurations logger.warning( 'APPRISE_ALLOW_SERVICES plugin %s:// was not found - ' 'ignoring.', entry) elif settings.APPRISE_DENY_SERVICES: alphanum_re = re.compile( r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE) entries = \ [alphanum_re.match(x).group('name').lower() for x in re.split(r'[ ,]+', settings.APPRISE_DENY_SERVICES) if alphanum_re.match(x)] for name in entries: try: # Force plugin to be disabled apprise.plugins.SCHEMA_MAP[name].enabled = False except KeyError: logger.warning( 'APPRISE_DENY_SERVICES plugin %s:// was not found -' ' ignoring.', name) # Prepare our keyword arguments (to be passed into an AppriseAsset # object) kwargs = {} if body_format: # Store our defined body format kwargs['body_format'] = body_format # Acquire our recursion count (if defined) try: recursion = \ int(request.headers.get('X-Apprise-Recursion-Count', 0)) if recursion < 0: # We do not accept negative numbers raise TypeError("Invalid Recursion Value") if recursion > settings.APPRISE_RECURSION_MAX: return HttpResponse( _('The recursion limit has been reached.'), status=ResponseCode.method_not_accepted) # Store our recursion value for our AppriseAsset() initialization kwargs['_recursion'] = recursion except (TypeError, ValueError): return HttpResponse( _('An invalid recursion value was specified.'), status=ResponseCode.bad_request) # Acquire our unique identifier (if defined) uid = request.headers.get('X-Apprise-ID', '').strip() if uid: kwargs['_uid'] = uid # Prepare ourselves a default Asset asset = None if not body_format else \ apprise.AppriseAsset(body_format=body_format) # Prepare our apprise object a_obj = apprise.Apprise(asset=asset) # Create an apprise config object ac_obj = apprise.AppriseConfig() # Load our configuration ac_obj.add_config(config, format=format) # Add our configuration a_obj.add(ac_obj) # Our return content type can be controlled by the Accept keyword # If it includes /* or /html somewhere then we return html, otherwise # we return the logs as they're processed in their text format. # The HTML response type has a bit of overhead where as it's not # the case with text/plain content_type = \ 'text/html' if re.search(r'text\/(\*|html)', request.headers.get('Accept', ''), re.IGNORECASE) \ else 'text/plain' # Acquire our log level from headers if defined, otherwise use # the global one set in the settings level = request.headers.get( 'X-Apprise-Log-Level', settings.LOGGING['loggers']['apprise']['level']).upper() # Initialize our response object response = None if level in ('CRITICAL', 'ERROR' 'WARNING', 'INFO', 'DEBUG'): level = getattr(apprise.logging, level) esc = '<!!-!ESC!-!!>' fmt = '<li class="log_%(levelname)s">' \ '<div class="log_time">%(asctime)s</div>' \ '<div class="log_level">%(levelname)s</div>' \ f'<div class="log_msg">{esc}%(message)s{esc}</div></li>' \ if content_type == 'text/html' else \ settings.LOGGING['formatters']['standard']['format'] # Now specify our format (and over-ride the default): with apprise.LogCapture(level=level, fmt=fmt) as logs: # Perform our notification at this point result = a_obj.notify( content.get('body'), title=content.get('title', ''), notify_type=content.get('type', apprise.NotifyType.INFO), tag=content.get('tag'), ) if content_type == 'text/html': # Iterate over our entries so that we can prepare to escape # things to be presented as HTML esc = re.escape(esc) entries = re.findall( r'(?P<head><li .+?){}(?P<to_escape>.*?)' r'{}(?P<tail>.+li>$)(?=$|<li .+{})'.format( esc, esc, esc), logs.getvalue(), re.DOTALL) # Wrap logs in `<ul>` tag and escape our message body: response = '<ul class="logs">{}</ul>'.format( ''.join([e[0] + escape(e[1]) + e[2] for e in entries])) else: # content_type == 'text/plain' response = logs.getvalue() else: # Perform our notification at this point without logging result = a_obj.notify( content.get('body'), title=content.get('title', ''), notify_type=content.get('type', apprise.NotifyType.INFO), tag=content.get('tag'), ) if not result: # If at least one notification couldn't be sent; change up # the response to a 424 error code msg = _('One or more notification could not be sent.') status = ResponseCode.failed_dependency return HttpResponse(response if response else msg, status=status) \ if not json_response else JsonResponse({ 'error': msg, }, encoder=JSONEncoder, safe=False, status=status, ) # Return our retrieved content return HttpResponse( response if response is not None else _('Notification(s) sent.'), content_type=content_type, status=ResponseCode.okay, ) @method_decorator((gzip_page, never_cache), name='dispatch') class StatelessNotifyView(View): """ A Django view for sending a stateless notification """ def post(self, request): """ Handle a POST request """ # our content content = {} if MIME_IS_FORM.match(request.content_type): content = {} form = NotifyByUrlForm(request.POST) if form.is_valid(): content.update(form.cleaned_data) elif MIME_IS_JSON.match(request.content_type): # Prepare our default response try: # load our JSON content content = json.loads(request.body.decode('utf-8')) except (AttributeError, ValueError): # could not parse JSON response... return HttpResponse( _('Invalid JSON specified.'), status=ResponseCode.bad_request) if not content: # We could not handle the Content-Type return HttpResponse( _('The message format is not supported.'), status=ResponseCode.bad_request) if not content.get('urls') and settings.APPRISE_STATELESS_URLS: # fallback to settings.APPRISE_STATELESS_URLS if no urls were # defined content['urls'] = settings.APPRISE_STATELESS_URLS # Some basic error checking if not content.get('body') or \ content.get('type', apprise.NotifyType.INFO) \ not in apprise.NOTIFY_TYPES: return HttpResponse( _('An invalid payload was specified.'), status=ResponseCode.bad_request) # Acquire our body format (if identified) body_format = content.get('format', apprise.NotifyFormat.TEXT) if body_format and body_format not in apprise.NOTIFY_FORMATS: return HttpResponse( _('An invalid (body) format was specified.'), status=ResponseCode.bad_request) # Prepare our keyword arguments (to be passed into an AppriseAsset # object) kwargs = {} if body_format: # Store our defined body format kwargs['body_format'] = body_format # Acquire our recursion count (if defined) try: recursion = \ int(request.headers.get('X-Apprise-Recursion-Count', 0)) if recursion < 0: # We do not accept negative numbers raise TypeError("Invalid Recursion Value") if recursion > settings.APPRISE_RECURSION_MAX: return HttpResponse( _('The recursion limit has been reached.'), status=ResponseCode.method_not_accepted) # Store our recursion value for our AppriseAsset() initialization kwargs['_recursion'] = recursion except (TypeError, ValueError): return HttpResponse( _('An invalid recursion value was specified.'), status=ResponseCode.bad_request) # Acquire our unique identifier (if defined) uid = request.headers.get('X-Apprise-ID', '').strip() if uid: kwargs['_uid'] = uid # Prepare ourselves a default Asset asset = None if not body_format else \ apprise.AppriseAsset(body_format=body_format) # # Apply Any Global Filters (if identified) # if settings.APPRISE_ALLOW_SERVICES: alphanum_re = re.compile( r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE) entries = \ [alphanum_re.match(x).group('name').lower() for x in re.split(r'[ ,]+', settings.APPRISE_ALLOW_SERVICES) if alphanum_re.match(x)] for plugin in set(apprise.plugins.SCHEMA_MAP.values()): if entries: # Get a list of the current schema's associated with # a given plugin schemas = set(apprise.plugins.details(plugin) ['tokens']['schema']['values']) # Check what was defined and see if there is a hit for entry in entries: if entry in schemas: # We had a hit; we're done break if entry in schemas: entries.remove(entry) # We can keep this plugin enabled and move along to the # next one... continue # if we reach here, we have to block our plugin plugin.enabled = False for entry in entries: # Generate some noise for those who have bad configurations logger.warning( 'APPRISE_ALLOW_SERVICES plugin %s:// was not found - ' 'ignoring.', entry) elif settings.APPRISE_DENY_SERVICES: alphanum_re = re.compile( r'^(?P<name>[a-z][a-z0-9]+)', re.IGNORECASE) entries = \ [alphanum_re.match(x).group('name').lower() for x in re.split(r'[ ,]+', settings.APPRISE_DENY_SERVICES) if alphanum_re.match(x)] for name in entries: try: # Force plugin to be disabled apprise.plugins.SCHEMA_MAP[name].enabled = False except KeyError: logger.warning( 'APPRISE_DENY_SERVICES plugin %s:// was not found -' ' ignoring.', name) # Prepare our apprise object a_obj = apprise.Apprise(asset=asset) # Add URLs a_obj.add(content.get('urls')) if not len(a_obj): return HttpResponse( _('There was no services to notify.'), status=ResponseCode.no_content, ) # Perform our notification at this point result = a_obj.notify( content.get('body'), title=content.get('title', ''), notify_type=content.get('type', apprise.NotifyType.INFO), tag='all', ) if not result: # If at least one notification couldn't be sent; change up the # response to a 424 error code return HttpResponse( _('One or more notification could not be sent.'), status=ResponseCode.failed_dependency) # Return our retrieved content return HttpResponse( _('Notification(s) sent.'), status=ResponseCode.okay, ) @method_decorator((gzip_page, never_cache), name='dispatch') class JsonUrlView(View): """ A Django view that lists all loaded tags and URLs for a given key """ def get(self, request, key): """ Handle a POST request """ # Now build our tag response that identifies all of the tags # and the URL's they're associated with # { # "tags": ["tag1', "tag2", "tag3"], # "urls": [ # { # "url": "windows://", # "tags": [], # }, # { # "url": "mailto://user:[email protected]" # "tags": ["tag1", "tag2", "tag3"] # } # ] # } response = { 'tags': set(), 'urls': [], } # Privacy flag # Support 'yes', '1', 'true', 'enable', 'active', and + privacy = settings.APPRISE_CONFIG_LOCK or \ request.GET.get('privacy', 'no')[0] in ( 'a', 'y', '1', 't', 'e', '+') # Optionally filter on tags. Use comma to identify more then one tag = request.GET.get('tag', 'all') config, format = ConfigCache.get(key) if config is None: # The returned value of config and format tell a rather cryptic # story; this portion could probably be updated in the future. # but for now it reads like this: # config == None and format == None: We had an internal error # config == None and format != None: we simply have no data # config != None: we simply have no data if format is not None: # no content to return return JsonResponse( response, encoder=JSONEncoder, safe=False, status=ResponseCode.no_content, ) # Something went very wrong; return 500 response['error'] = _('There was no configuration found.') return JsonResponse( response, encoder=JSONEncoder, safe=False, status=ResponseCode.internal_server_error, ) # Prepare our apprise object a_obj = apprise.Apprise() # Create an apprise config object ac_obj = apprise.AppriseConfig() # Load our configuration ac_obj.add_config(config, format=format) # Add our configuration a_obj.add(ac_obj) for notification in a_obj.find(tag): # Set Notification response['urls'].append({ 'url': notification.url(privacy=privacy), 'tags': notification.tags, }) # Store Tags response['tags'] |= notification.tags # Return our retrieved content return JsonResponse( response, encoder=JSONEncoder, safe=False, status=ResponseCode.okay )
""" These codes are based on those provided by the requests object """ okay = 200 no_content = 204 bad_request = 400 no_access = 403 not_found = 404 method_not_allowed = 405 method_not_accepted = 406 failed_dependency = 424 internal_server_error = 500
pipe_mic.py
# -*- coding: utf-8 -*- # a może teraz? """ A drop-in replacement for the Mic class that gets input from named pipe. It can be anny source, by here the goal is to communicate with www flask server, where voice recognition is done through chrome browser. We get plain text with no need for stt engine (chrome browser uses google engine). """ import re import alteration import os import io import str_formater PIPE_NAME = '/home/osmc/flask/jasper_pipe_mic' class Mic: p
rev = None def __init__(self, speaker, passive_stt_engine, active_stt_engine, logger): self.speaker = speaker self.first_run = True #self.passive_stt_engine = passive_stt_engine #self.active_stt_engine = active_stt_engine self.logger = logger try: if not os.path.exists(PIPE_NAME): os.mkfifo(PIPE_NAME) self.pipein = io.open(PIPE_NAME, 'r') #, "utf-8" except: self.logger.error("error preparing named pipe", exc_info=True) exit(1) return def passiveListen(self, PERSONA): return True, "JASPER" def activeListen(self, THRESHOLD=None, LISTEN=True, MUSIC=False): if self.first_run: self.first_run = False return "" if not LISTEN: return self.prev stop = False while not stop: input = self.pipein.readline()[:-1] if input: stop = True input = str_formater.unicodeToUTF8(input, self.logger) self.prev = input return input def say(self, phrase, OPTIONS=None): #phrase = phrase.decode('utf8') #print "JAN: " + phrase self.logger.info(">>>>>>>>>>>>>>>>>>>") self.logger.info("JAN: " + phrase ) self.logger.info(">>>>>>>>>>>>>>>>>>>") phrase = alteration.clean(phrase) self.speaker.say(phrase)
hermes-tokens.js
/** * @fileoverview added by tsickle * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/ /** @type {?} */ export var COMMAND_LOGGER_ENABLED = 'GUI - COMMAND_LOGGER_ENABLED'; /** @type {?} */ export var EVENT_LOGGER_ENABLED = 'GUI - EVENT_LOGGER_ENABLED'; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGVybWVzLXRva2Vucy5qcyIsInNvdXJjZVJvb3QiOiJuZzovL0BnZW5lcmljLXVpL2hlcm1lcy8iLCJzb3VyY2VzIjpbImRvbWFpbi9oZXJtZXMtdG9rZW5zLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsTUFBTSxLQUFPLHNCQUFzQixHQUFHLDhCQUE4Qjs7QUFDcEUsTUFBTSxLQUFPLG9CQUFvQixHQUFHLDRCQUE0QiIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBjb25zdCBDT01NQU5EX0xPR0dFUl9FTkFCTEVEID0gJ0dVSSAtIENPTU1BTkRfTE9HR0VSX0VOQUJMRUQnO1xuZXhwb3J0IGNvbnN0IEVWRU5UX0xPR0dFUl9FTkFCTEVEID0gJ0dVSSAtIEVWRU5UX0xPR0dFUl9FTkFCTEVEJztcbiJdfQ==
LivechatEditView.tsx
import React, { useEffect, useState } from 'react'; import { StackNavigationProp } from '@react-navigation/stack'; import { RouteProp } from '@react-navigation/native'; import { ScrollView, StyleSheet, Text } from 'react-native'; import { connect } from 'react-redux'; import { BLOCK_CONTEXT } from '@rocket.chat/ui-kit'; import { withTheme } from '../theme'; import { themes } from '../constants/colors'; import TextInput from '../containers/TextInput'; import KeyboardView from '../presentation/KeyboardView'; import RocketChat from '../lib/rocketchat'; import I18n from '../i18n'; import { LISTENER } from '../containers/Toast'; import EventEmitter from '../utils/events'; import scrollPersistTaps from '../utils/scrollPersistTaps'; import { getUserSelector } from '../selectors/login'; import Button from '../containers/Button'; import SafeAreaView from '../containers/SafeAreaView'; import { MultiSelect } from '../containers/UIKit/MultiSelect'; import { ICustomFields, IInputsRefs, TParams, ITitle, ILivechat } from '../definitions/ILivechatEditView'; import { IApplicationState } from '../definitions'; import { ChatsStackParamList } from '../stacks/types'; import sharedStyles from './Styles'; const styles = StyleSheet.create({ container: { padding: 16 }, title: { fontSize: 20, paddingVertical: 10, ...sharedStyles.textMedium }, label: { marginBottom: 10, fontSize: 14, ...sharedStyles.textSemibold }, multiSelect: { marginBottom: 10 } }); interface ILivechatEditViewProps { // TODO: Refactor when migrate models user: any; navigation: StackNavigationProp<ChatsStackParamList, 'LivechatEditView'>; route: RouteProp<ChatsStackParamList, 'LivechatEditView'>; theme: string; editOmnichannelContact: string[] | undefined; editLivechatRoomCustomfields: string[] | undefined; } const Title = ({ title, theme }: ITitle) => title ? <Text style={[styles.title, { color: themes[theme].titleText }]}>{title}</Text> : null; const LivechatEditView = ({ user, navigation, route, theme, editOmnichannelContact, editLivechatRoomCustomfields }: ILivechatEditViewProps) => { const [customFields, setCustomFields] = useState<ICustomFields>({}); const [availableUserTags, setAvailableUserTags] = useState<string[]>([]); const [permissions, setPermissions] = useState([]); const params = {} as TParams; const inputs = {} as IInputsRefs; const livechat = (route.params?.room ?? {}) as ILivechat; const visitor = route.params?.roomUser ?? {}; const getCustomFields = async () => { const result = await RocketChat.getCustomFields(); if (result.success && result.customFields?.length) { const visitorCustomFields = result.customFields .filter(field => field.visibility !== 'hidden' && field.scope === 'visitor') .map(field => ({ [field._id]: (visitor.livechatData && visitor.livechatData[field._id]) || '' })) .reduce((ret, field) => ({ ...field, ...ret }), {}); const livechatCustomFields = result.customFields .filter(field => field.visibility !== 'hidden' && field.scope === 'room') .map(field => ({ [field._id]: (livechat.livechatData && livechat.livechatData[field._id]) || '' })) .reduce((ret, field) => ({ ...field, ...ret }), {}); return setCustomFields({ visitor: visitorCustomFields, livechat: livechatCustomFields }); } }; const [tagParam, setTags] = useState(livechat?.tags || []); const [tagParamSelected, setTagParamSelected] = useState(livechat?.tags || []); useEffect(() => { const arr = [...tagParam, ...availableUserTags]; const uniqueArray = arr.filter((val, i) => arr.indexOf(val) === i); setTags(uniqueArray); }, [availableUserTags]);
const isAdmin = ['admin', 'livechat-manager'].find(role => user.roles.includes(role)); const availableTags = tags .filter(({ departments }) => isAdmin || departments.length === 0 || departments.some(i => agentDepartments.indexOf(i) > -1)) .map(({ name }) => name); setAvailableUserTags(availableTags); }; const getAgentDepartments = async () => { const result = await RocketChat.getAgentDepartments(visitor?._id); if (result.success) { const agentDepartments = result.departments.map(dept => dept.departmentId); getTagsList(agentDepartments); } }; const submit = async () => { const userData = { _id: visitor?._id } as TParams; const { rid } = livechat; const sms = livechat?.sms; const roomData = { _id: rid } as TParams; if (params.name) { userData.name = params.name; } if (params.email) { userData.email = params.email; } if (params.phone) { userData.phone = params.phone; } userData.livechatData = {}; Object.entries(customFields?.visitor || {}).forEach(([key]) => { if (params[key] || params[key] === '') { userData.livechatData[key] = params[key]; } }); if (params.topic) { roomData.topic = params.topic; } roomData.tags = tagParamSelected; roomData.livechatData = {}; Object.entries(customFields?.livechat || {}).forEach(([key]) => { if (params[key] || params[key] === '') { roomData.livechatData[key] = params[key]; } }); if (sms) { delete userData.phone; } const { error } = await RocketChat.editLivechat(userData, roomData); if (error) { EventEmitter.emit(LISTENER, { message: error }); } else { EventEmitter.emit(LISTENER, { message: I18n.t('Saved') }); navigation.goBack(); } }; const onChangeText = (key: string, text: string) => { params[key] = text; }; const getPermissions = async () => { const permissionsArray = await RocketChat.hasPermission([editOmnichannelContact, editLivechatRoomCustomfields], livechat.rid); setPermissions(permissionsArray); }; useEffect(() => { navigation.setOptions({ title: I18n.t('Edit') }); getAgentDepartments(); getCustomFields(); getPermissions(); }, []); return ( <KeyboardView style={{ backgroundColor: themes[theme].auxiliaryBackground }} contentContainerStyle={sharedStyles.container} keyboardVerticalOffset={128}> <ScrollView {...scrollPersistTaps} style={styles.container}> <SafeAreaView> <Title title={visitor?.username} theme={theme} /> <TextInput label={I18n.t('Name')} defaultValue={visitor?.name} onChangeText={text => onChangeText('name', text)} onSubmitEditing={() => { inputs.name?.focus(); }} theme={theme} editable={!!permissions[0]} /> <TextInput label={I18n.t('Email')} inputRef={e => { inputs.name = e; }} defaultValue={visitor?.visitorEmails && visitor?.visitorEmails[0]?.address} onChangeText={text => onChangeText('email', text)} onSubmitEditing={() => { inputs.phone?.focus(); }} theme={theme} editable={!!permissions[0]} /> <TextInput label={I18n.t('Phone')} inputRef={e => { inputs.phone = e; }} defaultValue={visitor?.phone && visitor?.phone[0]?.phoneNumber} onChangeText={text => onChangeText('phone', text)} onSubmitEditing={() => { const keys = Object.keys(customFields?.visitor || {}); if (keys.length > 0) { const key = keys[0]; inputs[key]?.focus(); } else { inputs.topic?.focus(); } }} theme={theme} editable={!!permissions[0]} /> {Object.entries(customFields?.visitor || {}).map(([key, value], index, array) => ( <TextInput label={key} defaultValue={value} inputRef={e => { inputs[key] = e; }} onChangeText={text => onChangeText(key, text)} onSubmitEditing={() => { if (array.length - 1 > index) { return inputs[array[index + 1][0]]?.focus(); } inputs.topic?.focus(); }} theme={theme} editable={!!permissions[0]} /> ))} <Title title={I18n.t('Conversation')} theme={theme} /> <TextInput label={I18n.t('Topic')} inputRef={e => { inputs.topic = e; }} defaultValue={livechat?.topic} onChangeText={text => onChangeText('topic', text)} theme={theme} editable={!!permissions[1]} /> <Text style={[styles.label, { color: themes[theme].titleText }]}>{I18n.t('Tags')}</Text> <MultiSelect options={tagParam.map((tag: string) => ({ text: { text: tag }, value: tag }))} onChange={({ value }: { value: string[] }) => { setTagParamSelected([...value]); }} placeholder={{ text: I18n.t('Tags') }} value={tagParamSelected} context={BLOCK_CONTEXT.FORM} multiselect theme={theme} disabled={!permissions[1]} inputStyle={styles.multiSelect} /> {Object.entries(customFields?.livechat || {}).map(([key, value], index, array: any) => ( <TextInput label={key} defaultValue={value} inputRef={e => { inputs[key] = e; }} onChangeText={text => onChangeText(key, text)} onSubmitEditing={() => { if (array.length - 1 > index) { return inputs[array[index + 1]]?.focus(); } submit(); }} theme={theme} editable={!!permissions[1]} /> ))} <Button title={I18n.t('Save')} onPress={submit} theme={theme} /> </SafeAreaView> </ScrollView> </KeyboardView> ); }; const mapStateToProps = (state: IApplicationState) => ({ server: state.server.server, user: getUserSelector(state), editOmnichannelContact: state.permissions['edit-omnichannel-contact'], editLivechatRoomCustomfields: state.permissions['edit-livechat-room-customfields'] }); export default connect(mapStateToProps)(withTheme(LivechatEditView));
const getTagsList = async (agentDepartments: string[]) => { const tags = await RocketChat.getTagsList();
cache.rs
#[macro_use] mod utils; inject_indy_dependencies!(); extern crate indyrs as indy; extern crate indyrs as api; use utils::cache::*; use utils::Setup; use utils::domain::crypto::did::DidValue; use self::indy::ErrorCode; pub const FORBIDDEN_TYPE: &'static str = "Indy::Test"; mod high_cases { use super::*; mod schema_cache { use super::*; use utils::domain::anoncreds::schema::{SchemaV1, SchemaId}; use utils::constants::*; use std::thread::sleep; #[test] fn indy_get_schema_empty_options() { let setup = Setup::wallet_and_pool(); let (schema_id, _, _) = utils::ledger::post_entities(); let options_json = json!({}).to_string(); let schema_json = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json).unwrap(); let _schema: SchemaV1 = serde_json::from_str(&schema_json).unwrap(); } #[test] fn indy_get_schema_empty_options_for_unknown_id() { let setup = Setup::wallet_and_pool(); let options_json = json!({}).to_string(); let res = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, &SchemaId::new(&DidValue(DID.to_string()), "other_schema", "1.0").0, &options_json); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn indy_get_schema_only_cache_no_cached_data() { let setup = Setup::wallet_and_pool(); let (schema_id, _, _) = utils::ledger::post_entities(); let options_json = json!({"noUpdate": true}).to_string(); let res = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn indy_get_schema_cache_works() { let setup = Setup::wallet_and_pool(); let (schema_id, _, _) = utils::ledger::post_entities(); let options_json = json!({}).to_string(); let schema_json1 = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json ).unwrap(); let _schema: SchemaV1 = serde_json::from_str(&schema_json1).unwrap(); // now retrieve it from cache let options_json = json!({"noUpdate": true}).to_string(); let schema_json2 = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json ).unwrap(); let _schema: SchemaV1 = serde_json::from_str(&schema_json2).unwrap(); assert_eq!(schema_json1, schema_json2); } #[test] fn indy_get_schema_no_store_works() { let setup = Setup::wallet_and_pool(); let (schema_id, _, _) = utils::ledger::post_entities(); let options_json = json!({"noStore": true}).to_string(); let schema_json1 = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json ).unwrap(); let _schema: SchemaV1 = serde_json::from_str(&schema_json1).unwrap(); // it should not be present inside of cache, because of noStore option in previous request. let options_json = json!({"noUpdate": true}).to_string(); let res = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json ); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn indy_get_schema_no_cache_works() { let setup = Setup::wallet_and_pool(); let (schema_id, _, _) = utils::ledger::post_entities(); let options_json = json!({}).to_string(); let schema_json1 = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json ).unwrap(); let _schema: SchemaV1 = serde_json::from_str(&schema_json1).unwrap(); // it should not be present inside of cache, because of noStore option in previous request. let options_json = json!({"noUpdate": true, "noCache": true}).to_string(); let res = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json ); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn indy_get_schema_fully_qualified_ids() { let setup = Setup::wallet_and_pool(); let (schema_id, _) = utils::ledger::post_qualified_entities(); let options_json = json!({}).to_string(); let schema_json = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1_V1, &schema_id, &options_json).unwrap(); let schema: SchemaV1 = serde_json::from_str(&schema_json).unwrap(); assert_eq!(schema_id, schema.id.0); } #[test] fn indy_get_schema_min_fresh_works() { let setup = Setup::wallet_and_pool(); let (schema_id, _, _) = utils::ledger::post_entities(); let options_json = json!({}).to_string(); let schema_json1 = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json ).unwrap(); let _schema: SchemaV1 = serde_json::from_str(&schema_json1).unwrap(); sleep(std::time::Duration::from_secs(2)); // it should not be present inside of cache, because of noStore option in previous request. let options_json = json!({"noUpdate": true, "minFresh": 1}).to_string(); let res = get_schema_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, schema_id, &options_json ); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn indy_purge_schema_cache_no_options() { let setup = Setup::wallet(); purge_schema_cache(setup.wallet_handle, "{}").unwrap(); } #[test] fn indy_purge_schema_cache_all_data() { let setup = Setup::wallet(); purge_schema_cache(setup.wallet_handle, &json!({"minFresh": -1}).to_string()).unwrap(); } #[test] fn indy_purge_schema_cache_older_than_1000_seconds() { let setup = Setup::wallet(); purge_schema_cache(setup.wallet_handle, &json!({"minFresh": 1000}).to_string()).unwrap(); } } mod cred_def_cache { use super::*; use utils::domain::anoncreds::credential_definition::{CredentialDefinition, CredentialDefinitionV1}; use utils::constants::*; use std::thread::sleep; #[test] fn indy_get_cred_def_empty_options() { let setup = Setup::wallet_and_pool(); let (_, cred_def_id, _) = utils::ledger::post_entities(); let options_json = json!({}).to_string(); let cred_def_json = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json).unwrap(); let _cred_def: CredentialDefinition = serde_json::from_str(&cred_def_json).unwrap(); } #[test] fn indy_get_cred_def_only_cache_no_cached_data() { let setup = Setup::wallet_and_pool(); let (_, cred_def_id, _) = utils::ledger::post_entities(); let options_json = json!({"noUpdate": true}).to_string(); let res = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn
() { let setup = Setup::wallet_and_pool(); let (_, cred_def_id, _) = utils::ledger::post_entities(); let options_json = json!({}).to_string(); let cred_def_json1 = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json ).unwrap(); let _cred_def: CredentialDefinition = serde_json::from_str(&cred_def_json1).unwrap(); // now retrieve it from cache let options_json = json!({"noUpdate": true}).to_string(); let cred_def_json2 = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json ).unwrap(); let _cred_def: CredentialDefinition = serde_json::from_str(&cred_def_json2).unwrap(); assert_eq!(cred_def_json1, cred_def_json2); } #[test] fn indy_get_cred_def_no_store_works() { let setup = Setup::wallet_and_pool(); let (_, cred_def_id, _) = utils::ledger::post_entities(); let options_json = json!({"noStore": true}).to_string(); let cred_def_json1 = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json ).unwrap(); let _cred_def: CredentialDefinition = serde_json::from_str(&cred_def_json1).unwrap(); // it should not be present inside of cache, because of noStore option in previous request. let options_json = json!({"noUpdate": true}).to_string(); let res = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json ); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn indy_get_cred_def_no_cache_works() { let setup = Setup::wallet_and_pool(); let (_, cred_def_id, _) = utils::ledger::post_entities(); let options_json = json!({}).to_string(); let cred_def_json1 = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json ).unwrap(); let _cred_def: CredentialDefinition = serde_json::from_str(&cred_def_json1).unwrap(); // it should not be present inside of cache, because of noStore option in previous request. let options_json = json!({"noUpdate": true, "noCache": true}).to_string(); let res = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json ); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn indy_get_cred_def_min_fresh_works() { let setup = Setup::wallet_and_pool(); let (_, cred_def_id, _) = utils::ledger::post_entities(); let options_json = json!({}).to_string(); let cred_def_json1 = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json ).unwrap(); let _cred_def: CredentialDefinition = serde_json::from_str(&cred_def_json1).unwrap(); sleep(std::time::Duration::from_secs(2)); // it should not be present inside of cache, because of noStore option in previous request. let options_json = json!({"noUpdate": true, "minFresh": 1}).to_string(); let res = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1, cred_def_id, &options_json ); assert_code!(ErrorCode::LedgerNotFound, res); } #[test] fn indy_get_cred_def_fully_qualified_ids() { let setup = Setup::wallet_and_pool(); let (_, cred_def_id) = utils::ledger::post_qualified_entities(); let options_json = json!({}).to_string(); let cred_def_json = get_cred_def_cache( setup.pool_handle, setup.wallet_handle, DID_MY1_V1, &cred_def_id, &options_json).unwrap(); let cred_def: CredentialDefinitionV1 = serde_json::from_str(&cred_def_json).unwrap(); assert_eq!(cred_def_id, cred_def.id.0); } #[test] fn indy_purge_cred_def_cache_no_options() { let setup = Setup::wallet(); purge_cred_def_cache(setup.wallet_handle, "{}").unwrap(); } #[test] fn indy_purge_cred_def_cache_all_data() { let setup = Setup::wallet(); purge_cred_def_cache(setup.wallet_handle, &json!({"minFresh": -1}).to_string()).unwrap(); } #[test] fn indy_purge_cred_def_cache_older_than_1000_seconds() { let setup = Setup::wallet(); purge_cred_def_cache(setup.wallet_handle, &json!({"minFresh": 1000}).to_string()).unwrap(); } } }
indy_get_cred_def_cache_works
issue_submission_data.py
advanced_settings_data = """ ### *Advanced Settings >This will be empty or non-existent if the user did not change any advanced settings from their default. Any settings changed from default will show up here | Parameter | Value | |:-----------------------:|:---------------------------:| | Common Pool Amount | {commons_pool_amount} wxDAI | | HNY Liquidity | {hny_liquidity} wxDAI | | Garden Liquidity | {garden_liquidity} TEC | | Virtual Supply | {virtual_supply} TEC | | Virtual Balance | {virtual_balance} wxDAI | | Transferable | {transferability} | | Token Name | {token_name} | | Token Symbol | {token_symbol} | | Proposal Deposit | {proposal_deposit} wxDAI | | Challenge Deposit | {challenge_deposit} wxDAI | | Settlement Period | {settlement_period} days | | Minimum Effective Supply | {minimum_effective_supply}% | | Hatchers Rage Quit | {hatchers_rage_quit} wxDAI | | Initial Buy | {initial_buy} wxDAI | [*Learn more about Advanced Settings on the TEC forum](https://forum.tecommons.org/c/defi-legos-and-how-they-work-together/adv-ccd-params/27) ### [FORK THIS PROPOSAL](http://config.tecommons.org/config/import/{issue_number}) (link) """ issue_data = """ ![image](https://i.imgflip.com/5rop7m.jpg) ## What is the overall Commons Configuration strategy? {overall_strategy} #### Advanced Settings Modified? {has_advanced_settings} ### [FORK THIS PROPOSAL](http://config.tecommons.org/config/import/{issue_number}) (link) # Summary ### Module 1: Token Freeze & Token Thaw | Parameter | Value | | ------------- | --------------------------- | | Token Freeze | {token_freeze_period} Weeks | | Token Thaw | {token_thaw_period} Weeks | | Opening Price | {opening_price} wxDAI | ### Module 2: Augmented Bonding Curve | Parameter | Value | | ---------------- | ------------------ | | Commons Tribute | {commons_tribute}% | | Entry Tribute | {entry_tribute}% | | Exit Tribute | {exit_tribute}% | | *_Reserve Ratio_ | {reserve_ratio}% | *This is an output. [Learn more about the Reserve Ratio here](https://forum.tecommons.org/t/augmented-bonding-curve-opening-price-reserve-ratio/516). ### Module 3: Tao Voting | Parameters | Value | | ----------------------- | ------------------------------------ | | Support Required | {support_required}% | | Minimum Quorum | {minimum_quorum}% | | Vote Duration | {vote_duration_days} days(s) | | Delegated Voting Period | {delegated_voting_days} day(s) | | Quiet Ending Period | {quiet_ending_days} day(s) | | Quiet Ending Extension | {quiet_ending_extension_days} day(s) | | Execution Delay | {execution_delay_days} day(s) | ### Module 4: Conviction Voting | Parameter | Value | | ------------------ | ------------------------------- | | Conviction Growth | {conviction_growth_days} day(s) | | Minimum Conviction | {minimum_conviction}% | | Spending Limit | {relative_spending_limit}% | # Module 1: Token Freeze and Token Thaw ### Data: ![]({token_lockup_image}) | Duration | % of Tokens Released | Price Floor of Token | | ------------------------- | --------------------- | ---------------------- | | 3 months | {tokens_released[0]}% | {price_floor[0]} wxDAI | | 6 months | {tokens_released[1]}% | {price_floor[1]} wxDAI | | 9 months | {tokens_released[2]}% | {price_floor[2]} wxDAI | | 1 year | {tokens_released[3]}% | {price_floor[3]} wxDAI | | 1.5 years | {tokens_released[4]}% | {price_floor[4]} wxDAI | | 2 years | {tokens_released[5]}% | {price_floor[5]} wxDAI | | 3 years | {tokens_released[6]}% | {price_floor[6]} wxDAI | | 4 years | {tokens_released[7]}% | {price_floor[7]} wxDAI | | 5 years | {tokens_released[8]}% | {price_floor[8]} wxDAI | - **Token Freeze**: **{token_freeze_period} weeks**, meaning that 100% of TEC tokens minted for Hatchers will remain locked from being sold or transferred for {token_freeze_period} weeks. They can still be used to vote while frozen. - **Token Thaw**: **{token_thaw_period} weeks**, meaning the Hatchers frozen tokens will start to become transferable at a steady rate starting at the end of Token Freeze and ending {token_thaw_period} weeks later. - **Opening Price**: **{opening_price} wxDAI**, meaning for the initial buy, the first TEC minted by the Augmented Bonding Curve will be priced at {opening_price} wxDAI making it the price floor during the Token Freeze. ### Strategy: {token_lockup_strategy} # Module 2: Augmented Bonding Curve (ABC) ### Data: ![]({abc_image}) | Step # | Current Price | Amount In | Tribute Collected | Amount Out | New Price | Price Slippage | | ------------------ | ------------------ | -------------- | ---------------------- | --------------- | -------------- | ------------------- | {abc_steps} #### NOTE: We're very bullish on TEC so we provide the BUY scenario at launch to compare proposals... to explore this proposal's ABC further Click the link below to see their parameters in your dashboard, be warned this will clear any data you have in your dashboard: ### [FORK THIS PROPOSAL](http://config.tecommons.org/config/import/{issue_number}) (link) | Allocation of Funds | wxDAI | |----------------------------------|--------------------------| | Common Pool (Before Initial Buy) | {common_pool_before} | | Reserve (Before Initial Buy) | {reserve_balance_before} | | Common Pool (After Initial Buy) | {common_pool_after} | | Reserve (After Initial Buy) | {reserve_balance_after} | ## ABC Configuration Table | Reserve (wxDai) | Supply (TEC) | Price (wxDai/TEC) | |:-------------------:|:------------------:|:-----------------:| | {abc_reserve[0]:,} | {abc_supply[0]:,.0f} | {abc_price[0]:,.2f} | | {abc_reserve[1]:,} | {abc_supply[1]:,.0f} | {abc_price[1]:,.2f} | | {abc_reserve[2]:,} | {abc_supply[2]:,.0f} | {abc_price[2]:,.2f} | | {abc_reserve[3]:,} | {abc_supply[3]:,.0f} | {abc_price[3]:,.2f} | | {abc_reserve[4]:,} | {abc_supply[4]:,.0f} | {abc_price[4]:,.2f} | | {abc_reserve[5]:,} | {abc_supply[5]:,.0f} | {abc_price[5]:,.2f} | | {abc_reserve[6]:,} | {abc_supply[6]:,.0f} | {abc_price[6]:,.2f} | | {abc_reserve[7]:,} | {abc_supply[7]:,.0f} | {abc_price[7]:,.2f} | | {abc_reserve[8]:,} | {abc_supply[8]:,.0f} | {abc_price[8]:,.2f} | | {abc_reserve[9]:,} | {abc_supply[9]:,.0f} | {abc_price[9]:,.2f} | | {abc_reserve[10]:,} | {abc_supply[10]:,.0f} | {abc_price[10]:,.2f} | | {abc_reserve[11]:,} | {abc_supply[11]:,.0f} | {abc_price[11]:,.2f} | | {abc_reserve[12]:,} | {abc_supply[12]:,.0f} | {abc_price[12]:,.2f} | | {abc_reserve[13]:,} | {abc_supply[13]:,.0f} | {abc_price[13]:,.2f} | | {abc_reserve[14]:,} | {abc_supply[14]:,.0f} | {abc_price[14]:,.2f} | | {abc_reserve[15]:,} | {abc_supply[15]:,.0f} | {abc_price[15]:,.2f} | | {abc_reserve[16]:,} | {abc_supply[16]:,.0f} | {abc_price[16]:,.2f} | | {abc_reserve[17]:,} | {abc_supply[17]:,.0f} | {abc_price[17]:,.2f} | | {abc_reserve[18]:,} | {abc_supply[18]:,.0f} | {abc_price[18]:,.2f} | | {abc_reserve[19]:,} | {abc_supply[19]:,.0f} | {abc_price[19]:,.2f} | | {abc_reserve[20]:,} | {abc_supply[20]:,.0f} | {abc_price[20]:,.2f} | | {abc_reserve[21]:,} | {abc_supply[21]:,.0f} | {abc_price[21]:,.2f} | | {abc_reserve[22]:,} | {abc_supply[22]:,.0f} | {abc_price[22]:,.2f} | | {abc_reserve[23]:,} | {abc_supply[23]:,.0f} | {abc_price[23]:,.2f} | | {abc_reserve[24]:,} | {abc_supply[24]:,.0f} | {abc_price[24]:,.2f} | | {abc_reserve[25]:,} | {abc_supply[25]:,.0f} | {abc_price[25]:,.2f} | | {abc_reserve[26]:,} | {abc_supply[26]:,.0f} | {abc_price[26]:,.2f} | - **Commons Tribute**: **{commons_tribute}%**, which means that {commons_tribute}% of the Hatch funds ({common_pool_before} wxDAI) will go to the Common Pool and {commons_tribute_remainder}% ({reserve_balance_before} wxDAI) will go to the ABC's Reserve. - **Entry Tribute**: **{entry_tribute}%** meaning that from every **BUY** order on the ABC, {entry_tribute}% of the order value in wxDAI is subtracted and sent to the Common Pool. - **Exit Tribute**: **{exit_tribute}%** meaning that from every **SELL** order on the ABC, {exit_tribute}% of the order value in wxDAI is subtracted and sent to the Common Pool. ### Strategy: {abc_strategy} # Module 3: Tao Voting ### Data: ![]({tao_voting_image}) |# of Quiet Ending Extensions | No Extensions | With 1 Extension | With 2 Extensions | | ------------------------------------------- | ------------------------------------- | ------------------------------------------------- | -------------------------------------------------- | | **Time to Vote on Proposals** | {vote_duration_days} days | {vote_duration_days_1_extension} days | {vote_duration_days_2_extensions} days | | **Time to Review a Delegates Vote** | {review_duration_days} days | {review_duration_days_1_extension} days | {review_duration_days_2_extensions} days | | **Time to Execute a Passing Proposal** | {execute_proposal_duration_days} days | {execute_proposal_duration_days_1_extension} days | {execute_proposal_duration_days_2_extensions} days | - **Support Required**: **{support_required}%**, which means {support_required}% of all votes must be in favor of a proposal for it to pass. - **Minimum Quorum**: **{minimum_quorum}%**, meaning that {minimum_quorum}% of all tokens need to have voted on a proposal in order for it to become valid. - **Vote Duration**: **{vote_duration_days} day(s)**, meaning that eligible voters will have {vote_duration_days} day(s) to vote on a proposal. - **Delegated Voting Period** is set for **{delegated_voting_days} day(s)**, meaning that Delegates will have {delegated_voting_days} day(s) to use their delegated voting power to vote on a proposal. - **Quiet Ending Period**: **{quiet_ending_days} day(s)**, this means that {quiet_ending_days} day(s) before the end of the Vote Duration, if the vote outcome changes, the Quiet Ending Extension will be triggered. - **Quiet Ending Extension**: **{quiet_ending_extension_days} day(s)**, meaning that if the vote outcome changes during the Quiet Ending Period, an additional {quiet_ending_extension_days} day(s) will be added for voting. - **Execution Delay**: **{execution_delay_days} days(s)**, meaning that there is an {execution_delay_days} day delay after the vote is passed before the proposed action is executed. ### Strategy: {tao_voting_strategy} # Module 4: Conviction Voting ### Data:
![]({conviction_voting_image}) | Proposal | Requested Amount (wxDAI) | Common Pool (wxDAI) | Effective supply (TEC) | Tokens Needed To Pass (TEC) | |:---------:|:------------------------:|:-------------------------:|:-----------------------:|:---------------------------:| | 1 | {requested_amount[0]:,} | {amount_common_pool[0]:,} | {effective_supply[0]:,} | {min_tokens_pass[0]} | | 2 | {requested_amount[1]:,} | {amount_common_pool[1]:,} | {effective_supply[1]:,} | {min_tokens_pass[1]} | | 3 | {requested_amount[2]:,} | {amount_common_pool[2]:,} | {effective_supply[2]:,} | {min_tokens_pass[2]} | | 4 | {requested_amount[3]:,} | {amount_common_pool[3]:,} | {effective_supply[3]:,} | {min_tokens_pass[3]} | | 5 | {requested_amount[4]:,} | {amount_common_pool[4]:,} | {effective_supply[4]:,} | {min_tokens_pass[4]} | | 6 | {requested_amount[5]:,} | {amount_common_pool[5]:,} | {effective_supply[5]:,} | {min_tokens_pass[5]} | - **Conviction Growth**: **{conviction_growth_days} day(s)**, meaning that voting power will increase by 50% every {conviction_growth_days} days that they are staked behind a proposal, so after {double_conviction_growth_days} days, a voters voting power will have reached 75% of it's maximum capacity. - **Minimum Conviction**: **{minimum_conviction}%**, this means that to pass any funding request it will take at least {minimum_conviction}% of the actively voting TEC tokens. - The **Spending Limit**: **{relative_spending_limit}%**, which means that no more than {relative_spending_limit}% of the total funds in the Common Pool can be funded by a single proposal. ### Strategy: {conviction_voting_strategy} ### [FORK THIS PROPOSAL](http://config.tecommons.org/config/import/{issue_number}) (link) {advanced_settings_section} """
clean.rs
//! Tests for the `cargo clean` command. use cargo_test_support::paths::CargoPathExt; use cargo_test_support::registry::Package; use cargo_test_support::{basic_bin_manifest, basic_manifest, git, main_file, project, rustc_host}; use std::env; use std::path::Path; #[cargo_test] fn cargo_clean_simple() { let p = project() .file("Cargo.toml", &basic_bin_manifest("foo")) .file("src/foo.rs", &main_file(r#""i am foo""#, &[])) .build(); p.cargo("build").run(); assert!(p.build_dir().is_dir()); p.cargo("clean").run(); assert!(!p.build_dir().is_dir()); } #[cargo_test] fn
() { let p = project() .file("Cargo.toml", &basic_bin_manifest("foo")) .file("src/foo.rs", &main_file(r#""i am foo""#, &[])) .file("src/bar/a.rs", "") .build(); p.cargo("build").run(); assert!(p.build_dir().is_dir()); p.cargo("clean").cwd("src").with_stdout("").run(); assert!(!p.build_dir().is_dir()); } #[cargo_test] fn clean_multiple_packages() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.d1] path = "d1" [dependencies.d2] path = "d2" [[bin]] name = "foo" "#, ) .file("src/foo.rs", &main_file(r#""i am foo""#, &[])) .file("d1/Cargo.toml", &basic_bin_manifest("d1")) .file("d1/src/main.rs", "fn main() { println!(\"d1\"); }") .file("d2/Cargo.toml", &basic_bin_manifest("d2")) .file("d2/src/main.rs", "fn main() { println!(\"d2\"); }") .build(); p.cargo("build -p d1 -p d2 -p foo").run(); let d1_path = &p .build_dir() .join("debug") .join(format!("d1{}", env::consts::EXE_SUFFIX)); let d2_path = &p .build_dir() .join("debug") .join(format!("d2{}", env::consts::EXE_SUFFIX)); assert!(p.bin("foo").is_file()); assert!(d1_path.is_file()); assert!(d2_path.is_file()); p.cargo("clean -p d1 -p d2") .cwd("src") .with_stdout("") .run(); assert!(p.bin("foo").is_file()); assert!(!d1_path.is_file()); assert!(!d2_path.is_file()); } #[cargo_test] fn clean_release() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies] a = { path = "a" } "#, ) .file("src/main.rs", "fn main() {}") .file("a/Cargo.toml", &basic_manifest("a", "0.0.1")) .file("a/src/lib.rs", "") .build(); p.cargo("build --release").run(); p.cargo("clean -p foo").run(); p.cargo("build --release").with_stdout("").run(); p.cargo("clean -p foo --release").run(); p.cargo("build --release") .with_stderr( "\ [COMPILING] foo v0.0.1 ([..]) [FINISHED] release [optimized] target(s) in [..] ", ) .run(); p.cargo("build").run(); p.cargo("clean").arg("--release").run(); assert!(p.build_dir().is_dir()); assert!(p.build_dir().join("debug").is_dir()); assert!(!p.build_dir().join("release").is_dir()); } #[cargo_test] fn clean_doc() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies] a = { path = "a" } "#, ) .file("src/main.rs", "fn main() {}") .file("a/Cargo.toml", &basic_manifest("a", "0.0.1")) .file("a/src/lib.rs", "") .build(); p.cargo("doc").run(); let doc_path = &p.build_dir().join("doc"); assert!(doc_path.is_dir()); p.cargo("clean --doc").run(); assert!(!doc_path.is_dir()); assert!(p.build_dir().is_dir()); } #[cargo_test] fn build_script() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] build = "build.rs" "#, ) .file("src/main.rs", "fn main() {}") .file( "build.rs", r#" use std::path::PathBuf; use std::env; fn main() { let out = PathBuf::from(env::var_os("OUT_DIR").unwrap()); if env::var("FIRST").is_ok() { std::fs::File::create(out.join("out")).unwrap(); } else { assert!(!out.join("out").exists()); } } "#, ) .file("a/src/lib.rs", "") .build(); p.cargo("build").env("FIRST", "1").run(); p.cargo("clean -p foo").run(); p.cargo("build -v") .with_stderr( "\ [COMPILING] foo v0.0.1 ([..]) [RUNNING] `rustc [..] build.rs [..]` [RUNNING] `[..]build-script-build` [RUNNING] `rustc [..] src/main.rs [..]` [FINISHED] dev [unoptimized + debuginfo] target(s) in [..] ", ) .run(); } #[cargo_test] fn clean_git() { let git = git::new("dep", |project| { project .file("Cargo.toml", &basic_manifest("dep", "0.5.0")) .file("src/lib.rs", "") }); let p = project() .file( "Cargo.toml", &format!( r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies] dep = {{ git = '{}' }} "#, git.url() ), ) .file("src/main.rs", "fn main() {}") .build(); p.cargo("build").run(); p.cargo("clean -p dep").with_stdout("").run(); p.cargo("build").run(); } #[cargo_test] fn registry() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies] bar = "0.1" "#, ) .file("src/main.rs", "fn main() {}") .build(); Package::new("bar", "0.1.0").publish(); p.cargo("build").run(); p.cargo("clean -p bar").with_stdout("").run(); p.cargo("build").run(); } #[cargo_test] fn clean_verbose() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" [dependencies] bar = "0.1" "#, ) .file("src/main.rs", "fn main() {}") .build(); Package::new("bar", "0.1.0").publish(); p.cargo("build").run(); p.cargo("clean -p bar --verbose") .with_stderr( "\ [REMOVING] [..] [REMOVING] [..] [REMOVING] [..] [REMOVING] [..] ", ) .run(); p.cargo("build").run(); } #[cargo_test] fn clean_remove_rlib_rmeta() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" "#, ) .file("src/lib.rs", "") .build(); p.cargo("build").run(); assert!(p.target_debug_dir().join("libfoo.rlib").exists()); let rmeta = p.glob("target/debug/deps/*.rmeta").next().unwrap().unwrap(); assert!(rmeta.exists()); p.cargo("clean -p foo").run(); assert!(!p.target_debug_dir().join("libfoo.rlib").exists()); assert!(!rmeta.exists()); } #[cargo_test] fn package_cleans_all_the_things() { // -p cleans everything // Use dashes everywhere to make sure dash/underscore stuff is handled. for crate_type in &["rlib", "dylib", "cdylib", "staticlib", "proc-macro"] { // Try each crate type individually since the behavior changes when // they are combined. let p = project() .file( "Cargo.toml", &format!( r#" [package] name = "foo-bar" version = "0.1.0" [lib] crate-type = ["{}"] "#, crate_type ), ) .file("src/lib.rs", "") .build(); p.cargo("build").run(); p.cargo("clean -p foo-bar").run(); assert_all_clean(&p.build_dir()); } let p = project() .file( "Cargo.toml", r#" [package] name = "foo-bar" version = "0.1.0" edition = "2018" [lib] crate-type = ["rlib", "dylib", "staticlib"] [[example]] name = "foo-ex-rlib" crate-type = ["rlib"] test = true [[example]] name = "foo-ex-cdylib" crate-type = ["cdylib"] test = true [[example]] name = "foo-ex-bin" test = true "#, ) .file("src/lib.rs", "") .file("src/main.rs", "fn main() {}") .file("src/bin/other-main.rs", "fn main() {}") .file("examples/foo-ex-rlib.rs", "") .file("examples/foo-ex-cdylib.rs", "") .file("examples/foo-ex-bin.rs", "fn main() {}") .file("tests/foo-test.rs", "") .file("benches/foo-bench.rs", "") .file("build.rs", "fn main() {}") .build(); p.cargo("build --all-targets") .env("CARGO_INCREMENTAL", "1") .run(); p.cargo("test --all-targets") .env("CARGO_INCREMENTAL", "1") .run(); p.cargo("check --all-targets") .env("CARGO_INCREMENTAL", "1") .run(); p.cargo("clean -p foo-bar").run(); assert_all_clean(&p.build_dir()); // Try some targets. p.cargo("build --all-targets --target") .arg(rustc_host()) .run(); p.cargo("clean -p foo-bar --target").arg(rustc_host()).run(); assert_all_clean(&p.build_dir()); } // Ensures that all files for the package have been deleted. fn assert_all_clean(build_dir: &Path) { let walker = walkdir::WalkDir::new(build_dir).into_iter(); for entry in walker.filter_entry(|e| { let path = e.path(); // This is a known limitation, clean can't differentiate between // the different build scripts from different packages. !(path .file_name() .unwrap() .to_str() .unwrap() .starts_with("build_script_build") && path .parent() .unwrap() .file_name() .unwrap() .to_str() .unwrap() == "incremental") }) { let entry = entry.unwrap(); let path = entry.path(); if let ".rustc_info.json" | ".cargo-lock" | "CACHEDIR.TAG" = path.file_name().unwrap().to_str().unwrap() { continue; } if path.is_symlink() || path.is_file() { panic!("{:?} was not cleaned", path); } } } #[cargo_test] fn clean_spec_multiple() { // clean -p foo where foo matches multiple versions Package::new("bar", "1.0.0").publish(); Package::new("bar", "2.0.0").publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] bar1 = {version="1.0", package="bar"} bar2 = {version="2.0", package="bar"} "#, ) .file("src/lib.rs", "") .build(); p.cargo("build").run(); // Check suggestion for bad pkgid. p.cargo("clean -p baz") .with_status(101) .with_stderr( "\ error: package ID specification `baz` did not match any packages <tab>Did you mean `bar`? ", ) .run(); p.cargo("clean -p bar:1.0.0") .with_stderr( "warning: version qualifier in `-p bar:1.0.0` is ignored, \ cleaning all versions of `bar` found", ) .run(); let mut walker = walkdir::WalkDir::new(p.build_dir()) .into_iter() .filter_map(|e| e.ok()) .filter(|e| { let n = e.file_name().to_str().unwrap(); n.starts_with("bar") || n.starts_with("libbar") }); if let Some(e) = walker.next() { panic!("{:?} was not cleaned", e.path()); } } #[cargo_test] fn clean_spec_reserved() { // Clean when a target (like a test) has a reserved name. In this case, // make sure `clean -p` doesn't delete the reserved directory `build` when // there is a test named `build`. Package::new("bar", "1.0.0") .file("src/lib.rs", "") .file("build.rs", "fn main() {}") .publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] bar = "1.0" "#, ) .file("src/lib.rs", "") .file("tests/build.rs", "") .build(); p.cargo("build --all-targets").run(); assert!(p.target_debug_dir().join("build").is_dir()); let build_test = p.glob("target/debug/deps/build-*").next().unwrap().unwrap(); assert!(build_test.exists()); // Tests are never "uplifted". assert!(p.glob("target/debug/build-*").next().is_none()); p.cargo("clean -p foo").run(); // Should not delete this. assert!(p.target_debug_dir().join("build").is_dir()); // This should not rebuild bar. p.cargo("build -v --all-targets") .with_stderr( "\ [FRESH] bar v1.0.0 [COMPILING] foo v0.1.0 [..] [RUNNING] `rustc [..] [RUNNING] `rustc [..] [RUNNING] `rustc [..] [FINISHED] [..] ", ) .run(); }
different_dir
f06_reader.py
from __future__ import print_function, absolute_import from six import iteritems, iterkeys, itervalues from six.moves import range from _file_reader import FileReader from f06_table import F06Table class _DummyTable(object): def __init__(self): self.header = [] self.data = [] self.line_number = -1 self.table_format = None class TableFormat(object): def __init__(self):
class F06Reader(object): def __init__(self, filename): self.file = FileReader(filename) self._done_reading = False self._table_formats = [TableFormat()] self._current_table = None self._callback = None def register_callback(self, callback): assert callable(callback) self._callback = callback def read(self): while not self._done_reading: table_lines, line_number = self._read_table() if self._done_reading: break table_format = F06Table.find_table(table_lines) if table_format is None: self._process_table(self._current_table) self._current_table = None continue table = table_format() table.set_data(table_lines) table.line_number = line_number for i in range(len(table.header)): table.header[i] = table.header[i].strip() if self._current_table is None: self._current_table = table else: if self._current_table.header == table.header: self._current_table.data.extend(table.data) else: self._process_table(self._current_table) self._current_table = table if self._current_table is not None: self._process_table(self._current_table) self._current_table = None def _process_table(self, table): if table is None: return pch_table = table.to_punch() if isinstance(pch_table, (list, tuple)): for table in pch_table: self._callback(table) else: self._callback(pch_table) def _read_table(self): table_lines = [] first_line = self._find_next_table() if self._done_reading: return None, None line_number = self.file.line_number() while True: if first_line is not None: line = first_line first_line = None else: line = self.file.next_line() self._check_done_reading(line) if self._done_reading: break # print(line) if line.startswith(b'1'): break table_lines.append(line) return table_lines, line_number def _find_next_table(self): while True: line = self.file.next_line() self._check_done_reading(line) if self._done_reading: break if line.startswith(b'0') and b'SUBCASE' in line: return line return None def _check_done_reading(self, line): if line is None or b'END OF JOB' in line: self._done_reading = True
self.header_check = b'D I S P L A C E M E N T V E C T O R' self.header_check_line = 2 self.header_lines = 5
jdr.rs
#[doc = "Register `JDR%s` reader"] pub struct R(crate::R<JDR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<JDR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<JDR_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<JDR_SPEC>) -> Self { R(reader) } } #[doc = "Field `JDATA` reader - Injected data"] pub struct JDATA_R(crate::FieldReader<u16, u16>); impl JDATA_R { #[inline(always)] pub(crate) fn new(bits: u16) -> Self { JDATA_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for JDATA_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:15 - Injected data"] #[inline(always)] pub fn
(&self) -> JDATA_R { JDATA_R::new((self.bits & 0xffff) as u16) } } #[doc = "injected data register x\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [jdr](index.html) module"] pub struct JDR_SPEC; impl crate::RegisterSpec for JDR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [jdr::R](R) reader structure"] impl crate::Readable for JDR_SPEC { type Reader = R; } #[doc = "`reset()` method sets JDR%s to value 0"] impl crate::Resettable for JDR_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
jdata
currentRefinedValues.js
/* eslint-disable import/default */ import instantsearch from '../../../../index.js'; const renderFn = ( { clearAllClick, clearAllURL, createURL, refine, refinements, widgetParams: { containerNode }, }, isFirstRendering ) => { // append initial markup on first rendering // ---------------------------------------- if (isFirstRendering) { const markup = window.$(` <div class="facet-title">Custom current refinements</div> <div id="custom-crv-clear-all-container"></div> <ul style="list-style-type: none; margin: 0; padding: 0;"></ul> `); containerNode.append(markup); } if (refinements && refinements.length > 0) { // append clear all link // --------------------- containerNode.find('#custom-crv-clear-all-container').html(` <a href="${clearAllURL}" class="ais-current-refined-values--clear-all" > Clear all </a> `);
.find('#custom-crv-clear-all-container > a') .off('click') .on('click', e => { e.preventDefault(); clearAllClick(); }); // show current refined values // --------------------------- const list = refinements .map(value => { const { computedLabel, count } = value; const afterCount = count ? `<span class="pull-right facet-count">${count}</span>` : ''; switch (true) { case value.attributeName === 'price_range': return `Price range: ${computedLabel.replace( /(\d+)/g, '$$$1' )} ${afterCount}`; case value.attributeName === 'price': return `Price: ${computedLabel.replace(/(\d+)/g, '$$$1')}`; case value.attributeName === 'free_shipping': return computedLabel === 'true' ? `Free shipping ${afterCount}` : ''; default: return `${computedLabel} ${afterCount}`; } }) .map( (content, index) => ` <li> <a href="${createURL(refinements[index])}" class="facet-value facet-value-removable clearfix" > ${content} </a> </li> ` ); containerNode.find('ul').html(list.join('')); // bind click events on links // -------------------------- containerNode.find('li > a').each(function(index) { window.$(this).off('click').on('click', e => { e.preventDefault(); refine(refinements[index]); }); }); // show container // -------------- containerNode.find('#custom-current-refined-values').show(); } else { // remove refinements list and clear all button, hide the container // ---------------------------------------------------------------- containerNode.find('ul').html(''); containerNode.find('#custom-crv-clear-all-container').html(''); containerNode.find('#custom-current-refined-values').hide(); } }; export default instantsearch.connectors.connectCurrentRefinedValues(renderFn);
containerNode
gis-viewer_20171229103419.tsx
import { Component, Prop, Method, Event, EventEmitter, State} from '@stencil/core'; import { GisViewerProps, Coordinate, WktShape } from '../../models/apiModels'; import { MAX_NORTH_EAST, MAX_SOUTH_WEST } from './classes/statics'; import { MapContainer } from './classes/MapContainer/MapContainer'; import _ from 'lodash'; import L from 'leaflet'; @Component({ tag: 'gis-viewer', styleUrls: [ 'gis-viewer.scss', '../../../node_modules/leaflet/dist/leaflet.css', /* MapContainer */ 'classes/MapContainer/MapContainer.css', /* ToolbarComp */ 'classes/features/ToolbarComp/ToolbarComp.css', /* LayersControllerComp */ '../../../node_modules/material-design-lite/material.min.css', // Need to import this from styledLayerControl.css '../../../node_modules/leaflet.styledlayercontrol/css/MaterialIcons.css', // Need to import this from styledLayerControl.css '../../../node_modules/leaflet.styledlayercontrol/css/styledLayerControl.css', 'classes/features/LayersControllerComp/LayersControllerComp.css', /* LayersCreatorComp */ '../../../node_modules/leaflet.markercluster/dist/MarkerCluster.css', '../../../node_modules/leaflet.markercluster/dist/MarkerCluster.Default.css', /* DrawBarComp */ // '../../../node_modules/leaflet-draw/dist/images/marker-icon.png', '../../../node_modules/leaflet-draw/dist/leaflet.draw.css', 'classes/features/DrawBarComp/DrawBarComp.css', /* PolylineMeasureComp */ '../../../node_modules/leaflet.polylinemeasure/Leaflet.PolylineMeasure.css', 'classes/features/PolylineMeasureComp/PolylineMeasureComp.css', /* SearchBoxComp */ 'classes/features/SearchBoxComp/SearchBoxComp.css', '../../../node_modules/leaflet-search/dist/leaflet-search.min.css', /* ZoomToExtendComp */ 'classes/features/ZoomToExtendComp/ZoomToExtend.css', /* MouseCoordintatePlugin */ '../../../node_modules/leaflet.mousecoordinate/dist/leaflet.mousecoordinate.css', /* ScaleControlComp */ 'classes/features/ScaleControlComp/ScaleControlComp.css', /* MiniMapComp */ '../../../node_modules/leaflet-minimap/dist/Control.MiniMap.min.css', /* CustomControlComp */ // classes/features/CustomControlComp/CustomControlComp.css ], }) export class
{ // private map: L.Map; @State() mapContainer: MapContainer; // @Element() el: HTMLElement; @Prop() gisViewerProps: GisViewerProps; @Event() mapReady: EventEmitter; @Event() moveEnd: EventEmitter; @Event() drawCreated: EventEmitter; @Event() drawEdited: EventEmitter; @Event() drawDeleted: EventEmitter; @Event() endImportDraw: EventEmitter; render() { return ( <div id='map' /> ) } componentDidLoad() { this.mapContainer = new MapContainer(this.gisViewerProps); } @Method() emitDrawCreated(wktShape: WktShape) { this.drawCreated.emit(wktShape); } @Method() emitDrawEdited(wktList: WktShape[]) { this.drawEdited.emit(wktList); } @Method() emitDrawDeleted(wktList: WktShape[]) { this.drawDeleted.emit(wktList); } @Method() emitEndImportDraw(importedLayers: WktShape[]) { this.endImportDraw.emit(importedLayers); } }
GisViewer
pipeline.ts
import { Construct, Stack, StackProps, SecretValue } from "@aws-cdk/core"; import { Artifact } from "@aws-cdk/aws-codepipeline"; import { PolicyStatement } from "@aws-cdk/aws-iam"; import { CdkPipeline, SimpleSynthAction, ShellScriptAction } from "@aws-cdk/pipelines"; import { GitHubSourceAction, ManualApprovalAction } from "@aws-cdk/aws-codepipeline-actions"; import DevelopmentStage from "../stages/development"; import ProductionStage from "../stages/production"; export interface PipelineStackProps extends StackProps { developmentStageAccountId: string; developmentStageRegion: string; productionStageAccountId: string; productionStageRegion: string; gitHubBranch: string; gitHubOwner: string; gitHubRepository: string; gitHubTokenSecretId: string; } export default class
extends Stack { constructor(scope: Construct, id: string, props: PipelineStackProps) { super(scope, id, props); const sourceArtifact = new Artifact(); const buildArtifact = new Artifact(); const cdkPipeline = new CdkPipeline(this, "Pipeline", { cloudAssemblyArtifact: buildArtifact, crossAccountKeys: true, pipelineName: "StartupSnack-CICD-Pipeline", selfMutating: true, sourceAction: new GitHubSourceAction({ actionName: "GitHub", output: sourceArtifact, owner: props.gitHubOwner, repo: props.gitHubRepository, branch: props.gitHubBranch, oauthToken: SecretValue.secretsManager(props.gitHubTokenSecretId) }), synthAction: SimpleSynthAction.standardNpmSynth({ sourceArtifact, cloudAssemblyArtifact: buildArtifact, actionName: "Build", installCommand: "npm install", buildCommand: "npm run build" }) }); //// Development Stage const development = new DevelopmentStage(this, "Development", { managementAccount: Stack.of(this).account, env: { account: props.developmentStageAccountId, region: props.developmentStageRegion } }); cdkPipeline.addApplicationStage(development); const { roleArn: readerRoleArn } = development.crossAccountReaderStack .crossAccountRole; const testDevelopmentStage = cdkPipeline .addStage(`Test-${development.stageName}`); testDevelopmentStage.addActions( new ShellScriptAction({ actionName: "RunTests", runOrder: testDevelopmentStage.nextSequentialRunOrder(), additionalArtifacts: [sourceArtifact], rolePolicyStatements: [ new PolicyStatement({ actions: ["sts:AssumeRole"], resources: [readerRoleArn] }) ], environmentVariables: { STACK_OUTPUT_KEY: { value: development.apiStack.apiOutputKey }, STACK_NAME: { value: development.apiStack.stackName }, CROSS_ACCOUNT_READER_ROLE_ARN: { value: readerRoleArn } }, commands: [ "npm install", "npm run test" ] }), new ManualApprovalAction({ actionName: "ApproveDevelopment", runOrder: testDevelopmentStage.nextSequentialRunOrder() }) ); //// Production Stage cdkPipeline.addApplicationStage(new ProductionStage(this, "Production", { env: { account: props.productionStageAccountId, region: props.productionStageRegion } })); } }
PipelineStack
__init__.py
"""REST API implementation.""" import json import logging import os import pathlib from datetime import datetime from aiohttp import web from core.addons.api.dto.details import Details from core.addons.api.dto.location import Location from core.addons.api.dto.photo import PhotoDetailsResponse, PhotoEncoder, PhotoResponse from core.addons.api.dto.photo_response import PhotosResponse from core.base import Session from core.core import ApplicationCore from core.persistency.dto.photo import Photo from core.webserver.request import KEY_USER_ID, RequestView from core.webserver.status import HTTP_CREATED, HTTP_OK _LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) async def async_setup(core: ApplicationCore, config: dict) -> bool: """Set up addon to core application.""" if config is not None and "cors" in config: is_cors_enabled = config["cors"] else: is_cors_enabled = False _LOGGER.debug(f"enable cors: {is_cors_enabled}") core.http.register_request(APIStatusView()) core.http.register_request(PhotosView()) core.http.register_request(PhotoDetailsView()) core.http.register_request(PhotoView()) core.http.register_request(AlbumView()) return True class APIStatusView(RequestView): """View to handle Status requests.""" requires_auth = False url = "/api" name = "api:status" async def get(self, core: ApplicationCore, request: web.Request): """Retrieve if API is running.""" return self.json_message("API running.") async def head(self, core: ApplicationCore, request: web.Request): """Retrieve if API is running.""" return self.json_message("API running.") class PhotosView(RequestView): """View to handle photos requests.""" url = "/api/photos" name = "api:photo" async def get(self, core: ApplicationCore, request: web.Request) -> web.Response: """Get a list of all photo resources.""" _LOGGER.debug("GET /api/photos") await core.authentication.check_permission(request, "library:read") user_id = await core.http.get_user_id(request) if user_id is None: raise web.HTTPForbidden() limit = 50 if "limit" in request.query: limit = int(request.query["limit"]) offset = 0 if "offset" in request.query: offset = int(request.query["offset"]) _LOGGER.debug( f"read {limit} photos for user_id {user_id} beginning with {offset}" ) user_photos = await core.storage.read_photos(user_id, offset, limit) results = [] _LOGGER.debug(f"found {len(user_photos)} photos") for photo in user_photos: results.append( PhotoResponse( id=photo.uuid, name=photo.filename, image_url=f"{core.config.external_url}:{core.config.port}/api/file/{photo.uuid}", date_added=photo.date_added, date_taken=photo.date_taken, ) ) response = PhotosResponse( offset=offset, limit=limit, size=len(results), results=results ) return web.Response( text=json.dumps(response, cls=PhotoEncoder), content_type="application/json" ) class PhotoDetailsView(RequestView): """View to handle single photo requests.""" url = "/api/photo/{entity_id}" name = "api:photo" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: """Return an entity.""" _LOGGER.debug(f"GET /api/photo/{entity_id}") # TODO: add user_id to check if user has access to image photo = await core.storage.read_photo(entity_id) if photo is None: raise web.HTTPNotFound # photo owner # TODO: get first-/lastname of owner # owner = await core.authentication _LOGGER.debug(f"photo {photo.uuid}") file = os.path.join(photo.directory, photo.filename) _LOGGER.debug(f"get additional data for {file} / {os.path.exists(file)}") # photo creation time fname = pathlib.Path(file) mtime = datetime.fromtimestamp(fname.stat().st_mtime) ctime = datetime.fromtimestamp(fname.stat().st_ctime) # photo location location = None latitude = await core.storage.read("latitude") longitude = await core.storage.read("longitude") if latitude is not None and longitude is not None: altitude = await core.storage.read("altitude") if altitude is not None: location = Location( latitude=latitude, longitude=longitude, altitude=altitude ) else: location = Location( latitude=latitude, longitude=longitude, altitude="0.0" ) # photo tags tags = await core.storage.read("tags") result = PhotoDetailsResponse( id=photo.uuid, name=photo.filename, owner=photo.owner, created_at=ctime.isoformat(), modified_at=mtime.isoformat(), details=Details( camera="Nikon Z7", lens="Nikkor 200mm F1.8", focal_length="200", iso="400", shutter_speed="1/2000", aperture="4.0", ), tags=tags, location=location, image_url=f"{core.config.external_url}/api/file/{entity_id}", ) return web.Response( text=json.dumps(result, cls=PhotoEncoder), content_type="application/json" ) class PhotoView(RequestView): """View to handle photo file requests.""" requires_auth = True url = "/api/file/{entity_id}" name = "api:file" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: """Return an entity.""" _LOGGER.debug(f"GET /api/file/{entity_id}") # TODO: parse params max-with / max-height =wmax-width-hmax-height (=w2048-h1024) # -wmax-width (preserving the aspect ratio) # -hmax-height (preserving the aspect ratio) # -c crop images to max-width / max-height # -d remove exif data result = Session.query(Photo).filter(Photo.uuid == entity_id).first() if result: file = os.path.join(result.directory, result.filename) if os.path.exists(os.path.join(file)): return web.FileResponse(path=file, status=200) else: raise web.HTTPNotFound() else: raise web.HTTPNotFound() async def post(self, core: ApplicationCore, request: web.Request) -> web.Response: """Upload new photo resource.""" user = request[KEY_USER_ID] reader = await request.multipart() field = await reader.next() assert field.name == "data" original_filename = field.filename _LOGGER.warning(f"request: {original_filename}") # TODO: get storage directory for user path = os.path.join(f"./data/users/{user}/", original_filename) if os.path.exists(path): # TODO: handle filename already exists _LOGGER.warning(f"file already exists! {path}") filename = original_filename size = 0 with open(os.path.join(f"./data/users/{user}/", filename), "wb") as f: while True: chunk = await field.read_chunk() # 8192 bytes by default. if not chunk: break size += len(chunk) f.write(chunk) _LOGGER.error(f"added {filename} to data directory of {user}.") # TODO: add new filepath to database # TODO: return unique_id from database new_entity_id = 123456 new_entity_created = True status_code = HTTP_CREATED if new_entity_created else HTTP_OK resp = self.json_message( f"File successfully added with ID: {new_entity_id}", status_code ) resp.headers.add("Location", f"/api/photo/{new_entity_id}") return resp async def delete(self, core: ApplicationCore, request: web.Request, entity_id: str): """Delete an entity.""" _LOGGER.debug(f"DELETE /api/file/{entity_id}") # TODO: delete entity return self.json_message(f"return DELETE {entity_id}") class AlbumsView(RequestView): """View to handle albums requests.""" requires_auth = False url = "/api/album/" name = "api:albums" async def get(self, request: web.Request) -> web.Response: """Retrieve if API is running.""" return self.json_message("return Albums") class AlbumView(RequestView):
"""View to handle single album requests.""" requires_auth = False url = "/api/album/{entity_id}" name = "api:album" async def get(self, request: web.Request, entity_id) -> web.Response: """Retrieve if API is running.""" return self.json_message(f"return Album {entity_id}") async def post(self, request: web.Request) -> web.Response: """Create a new album.""" return self.json_message("create a new Album")
Label.js
import React, { Component } from 'react' import { StyleSheet, View } from 'react-native' import * as theme from '../constants/theme'; export default class Label extends Component { render() { const { blue, green, red, yellow, teal, purple, black, white, gray, color, style, children, ...props } = this.props; const labelStyles = [ styles.label, color && { backgroundColor: color }, blue && { backgroundColor: theme.colors.blue }, green && { backgroundColor: theme.colors.green }, red && { backgroundColor: theme.colors.red }, yellow && { backgroundColor: theme.colors.yellow },
teal && { backgroundColor: theme.colors.teal }, purple && { backgroundColor: theme.colors.purple }, black && { backgroundColor: theme.colors.black }, white && { backgroundColor: theme.colors.white }, gray && { backgroundColor: theme.colors.gray }, style, ]; return ( <View style={labelStyles} {...props}> {children} </View> ) } } const styles = StyleSheet.create({ label: { margin: 4, width: 12, height: 12, borderRadius: 12, }, });
tilemap.py
""" Functions and classes for managing a map saved in the .tmx format. Typically these .tmx maps are created using the `Tiled Map Editor`_. For more information, see the `Platformer Tutorial`_. .. _Tiled Map Editor: https://www.mapeditor.org/ .. _Platformer Tutorial: http://arcade.academy/examples/platform_tutorial/index.html """ from typing import Optional, List, cast, Union import math import copy import pytiled_parser import os from pathlib import Path from arcade import Sprite from arcade import AnimatedTimeBasedSprite from arcade import AnimationKeyframe from arcade import SpriteList from arcade import load_texture from arcade.arcade_types import Point from arcade.resources import resolve_resource_path _FLIPPED_HORIZONTALLY_FLAG = 0x80000000 _FLIPPED_VERTICALLY_FLAG = 0x40000000 _FLIPPED_DIAGONALLY_FLAG = 0x20000000 def read_tmx(tmx_file: Union[str, Path]) -> pytiled_parser.objects.TileMap: """ Given a .tmx, this will read in a tiled map, and return a TiledMap object. Given a tsx_file, the map will use it as the tileset. If tsx_file is not specified, it will use the tileset specified within the tmx_file. Important: Tiles must be a "collection" of images. Hitboxes can be drawn around tiles in the tileset editor, but only polygons are supported. (This is a great area for PR's to improve things.) :param str tmx_file: String with name of our TMX file :returns: Map :rtype: TiledMap """ # If we should pull from local resources, replace with proper path tmx_file = resolve_resource_path(tmx_file) tile_map = pytiled_parser.parse_tile_map(tmx_file) return tile_map def get_tilemap_layer(map_object: pytiled_parser.objects.TileMap, layer_path: str) -> Optional[pytiled_parser.objects.Layer]: """ Given a TileMap and a layer path, this returns the TileLayer. :param pytiled_parser.objects.TileMap map_object: The map read in by the read_tmx function. :param str layer_path: A string to match the layer name. Case sensitive. :returns: A TileLayer, or None if no layer was found. """ assert isinstance(map_object, pytiled_parser.objects.TileMap) assert isinstance(layer_path, str) def _get_tilemap_layer(path, layers):
path = layer_path.strip('/').split('/') layer = _get_tilemap_layer(path, map_object.layers) return layer def _get_tile_by_gid(map_object: pytiled_parser.objects.TileMap, tile_gid: int) -> Optional[pytiled_parser.objects.Tile]: flipped_diagonally = False flipped_horizontally = False flipped_vertically = False if tile_gid & _FLIPPED_HORIZONTALLY_FLAG: flipped_horizontally = True tile_gid -= _FLIPPED_HORIZONTALLY_FLAG if tile_gid & _FLIPPED_DIAGONALLY_FLAG: flipped_diagonally = True tile_gid -= _FLIPPED_DIAGONALLY_FLAG if tile_gid & _FLIPPED_VERTICALLY_FLAG: flipped_vertically = True tile_gid -= _FLIPPED_VERTICALLY_FLAG for tileset_key, tileset in map_object.tile_sets.items(): if tile_gid < tileset_key: continue tile_ref = tileset.tiles.get(tile_gid - tileset_key) # No specific tile info, but there is a tile sheet if tile_ref is None \ and tileset.image is not None \ and tileset_key <= tile_gid < tileset_key + tileset.tile_count: image = pytiled_parser.objects.Image(source=tileset.image.source) tile_ref = pytiled_parser.objects.Tile(id_=(tile_gid - tileset_key), image=image) if tile_ref is None: continue my_tile = copy.copy(tile_ref) my_tile.tileset = tileset my_tile.flipped_vertically = flipped_vertically my_tile.flipped_diagonally = flipped_diagonally my_tile.flipped_horizontally = flipped_horizontally return my_tile return None def _get_tile_by_id(map_object: pytiled_parser.objects.TileMap, tileset: pytiled_parser.objects.TileSet, tile_id: int) -> Optional[pytiled_parser.objects.Tile]: for tileset_key, cur_tileset in map_object.tile_sets.items(): if cur_tileset is tileset: for tile_key, tile in cur_tileset.tiles.items(): if tile_id == tile.id_: return tile return None def _get_image_info_from_tileset(tile): image_x = 0 image_y = 0 if tile.tileset.image is not None: row = tile.id_ // tile.tileset.columns image_y = row * tile.tileset.max_tile_size.height col = tile.id_ % tile.tileset.columns image_x = col * tile.tileset.max_tile_size.width if tile.image and tile.image.size: # Individual image, use image width and height width = tile.image.size.width height = tile.image.size.height else: # Sprite sheet, use max width/height from sheet width = tile.tileset.max_tile_size.width height = tile.tileset.max_tile_size.height return image_x, image_y, width, height def _get_image_source(tile: pytiled_parser.objects.Tile, base_directory: Optional[str], map_directory: Optional[str]): image_file = None if tile.image: image_file = tile.image.source elif tile.tileset.image: image_file = tile.tileset.image.source if not image_file: print(f"Warning for tile {tile.id_}, no image source listed either for individual tile, or as a tileset.") return None if os.path.exists(image_file): return image_file if base_directory: try2 = Path(base_directory, image_file) if os.path.exists(try2): return try2 if map_directory: try3 = Path(map_directory, image_file) if os.path.exists(try3): return try3 if tile.tileset and tile.tileset.parent_dir: try4 = Path(tile.tileset.parent_dir, image_file) if os.path.exists(try4): return try4 print(f"Warning, can't file image {image_file} for tile {tile.id_} - {base_directory}") return None def _create_sprite_from_tile(map_object: pytiled_parser.objects.TileMap, tile: pytiled_parser.objects.Tile, scaling: float = 1.0, base_directory: str = None, hit_box_algorithm="Simple", hit_box_detail: float = 4.5 ): """ Given a tile from the parser, see if we can create a sprite from it """ # --- Step 1, find a reference to an image this is going to be based off of map_source = map_object.tmx_file map_directory = os.path.dirname(map_source) image_file = _get_image_source(tile, base_directory, map_directory) # print(f"Creating tile: {tmx_file}") if tile.animation: # my_sprite = AnimatedTimeSprite(tmx_file, scaling) my_sprite: Sprite = AnimatedTimeBasedSprite(image_file, scaling) else: image_x, image_y, width, height = _get_image_info_from_tileset(tile) my_sprite = Sprite(image_file, scaling, image_x, image_y, width, height, flipped_horizontally=tile.flipped_horizontally, flipped_vertically=tile.flipped_vertically, flipped_diagonally=tile.flipped_diagonally, hit_box_algorithm=hit_box_algorithm, hit_box_detail=hit_box_detail ) if tile.properties is not None and len(tile.properties) > 0: for my_property in tile.properties: my_sprite.properties[my_property.name] = my_property.value if tile.type_: my_sprite.properties['type'] = tile.type_ # print(tile.image.source, my_sprite.center_x, my_sprite.center_y) if tile.objectgroup is not None: if len(tile.objectgroup) > 1: print(f"Warning, only one hit box supported for tile with image {tile.image.source}.") for hitbox in tile.objectgroup: points: List[Point] = [] if isinstance(hitbox, pytiled_parser.objects.RectangleObject): if hitbox.size is None: print(f"Warning: Rectangle hitbox created for without a " f"height or width for {tile.image.source}. Ignoring.") continue # print(my_sprite.width, my_sprite.height) sx = hitbox.location[0] - (my_sprite.width / (scaling * 2)) sy = -(hitbox.location[1] - (my_sprite.height / (scaling * 2))) ex = (hitbox.location[0] + hitbox.size[0]) - (my_sprite.width / (scaling * 2)) ey = -((hitbox.location[1] + hitbox.size[1]) - (my_sprite.height / (scaling * 2))) # print(f"Size: {hitbox.size} Location: {hitbox.location}") p1 = [sx, sy] p2 = [ex, sy] p3 = [ex, ey] p4 = [sx, ey] # print(f"w:{my_sprite.width:.1f}, h:{my_sprite.height:.1f}", end=", ") points = [p1, p2, p3, p4] # for point in points: # print(f"({point[0]:.1f}, {point[1]:.1f}) ") # print() elif isinstance(hitbox, pytiled_parser.objects.PolygonObject) \ or isinstance(hitbox, pytiled_parser.objects.PolylineObject): for point in hitbox.points: adj_x = point[0] + hitbox.location[0] - my_sprite.width / (scaling * 2) adj_y = -(point[1] + hitbox.location[1] - my_sprite.height / (scaling * 2)) adj_point = [adj_x, adj_y] points.append(adj_point) # If we have a polyline, and it is closed, we need to # remove the duplicate end-point if points[0][0] == points[-1][0] and points[0][1] == points[-1][1]: points.pop() elif isinstance(hitbox, pytiled_parser.objects.ElipseObject): if hitbox.size is None: print(f"Warning: Ellipse hitbox created for without a height " f"or width for {tile.image.source}. Ignoring.") continue # print(f"Size: {hitbox.size} Location: {hitbox.location}") hw = hitbox.size[0] / 2 hh = hitbox.size[1] / 2 cx = hitbox.location[0] + hw cy = hitbox.location[1] + hh acx = cx - (my_sprite.width / (scaling * 2)) acy = cy - (my_sprite.height / (scaling * 2)) # print(f"acx: {acx} acy: {acy} cx: {cx} cy: {cy} hh: {hh} hw: {hw}") total_steps = 8 angles = [step / total_steps * 2 * math.pi for step in range(total_steps)] for angle in angles: x = (hw * math.cos(angle) + acx) y = (-(hh * math.sin(angle) + acy)) point = [x, y] points.append(point) # for point in points: # print(f"({point[0]:.1f}, {point[1]:.1f}) ") # print() else: print(f"Warning: Hitbox type {type(hitbox)} not supported.") my_sprite.set_hit_box(points) if tile.animation is not None: # Animated image key_frame_list = [] # Loop through each frame for frame in tile.animation: # Get the tile for the frame frame_tile = _get_tile_by_id(map_object, tile.tileset, frame.tile_id) if frame_tile: image_file = _get_image_source(frame_tile, base_directory, map_directory) # Does the tile have an image? if frame_tile.image: # Yes, use it texture = load_texture(image_file) else: # No image for tile? Pull from tilesheet image_x, image_y, width, height = _get_image_info_from_tileset(frame_tile) texture = load_texture(image_file, image_x, image_y, width, height) key_frame = AnimationKeyframe(frame.tile_id, frame.duration, texture) key_frame_list.append(key_frame) # If this is the first texture in the animation, go ahead and # set it as the current texture. if len(key_frame_list) == 1: my_sprite.texture = key_frame.texture # print(f"Add tile {frame.tile_id} for keyframe. Source: {frame_tile.image.source}") cast(AnimatedTimeBasedSprite, my_sprite).frames = key_frame_list return my_sprite def _process_object_layer(map_object: pytiled_parser.objects.TileMap, layer: pytiled_parser.objects.ObjectLayer, scaling: float = 1, base_directory: str = "", use_spatial_hash: Optional[bool] = None, hit_box_algorithm = "Simple", hit_box_detail = 4.5) -> SpriteList: sprite_list: SpriteList = SpriteList(use_spatial_hash=use_spatial_hash) for cur_object in layer.tiled_objects: if cur_object.gid is None: print("Warning: Currently only tiles (not objects) are supported in object layers.") continue tile = _get_tile_by_gid(map_object, cur_object.gid) my_sprite = _create_sprite_from_tile(map_object, tile, scaling=scaling, base_directory=base_directory, hit_box_algorithm=hit_box_algorithm, hit_box_detail=hit_box_detail) x = cur_object.location.x * scaling y = (map_object.map_size.height * map_object.tile_size[1] - cur_object.location.y) * scaling my_sprite.width = width = cur_object.size[0] * scaling my_sprite.height = height = cur_object.size[1] * scaling center_x = width / 2 center_y = height / 2 if cur_object.rotation is not None: rotation = -math.radians(cur_object.rotation) else: rotation = 0 cos_rotation = math.cos(rotation) sin_rotation = math.sin(rotation) rotated_center_x = center_x * cos_rotation - center_y * sin_rotation rotated_center_y = center_x * sin_rotation + center_y * cos_rotation my_sprite.position = (x + rotated_center_x, y + rotated_center_y) my_sprite.angle = math.degrees(rotation) # Opacity opacity = layer.opacity if opacity: my_sprite.alpha = int(opacity * 255) # Properties if cur_object.properties is not None and 'change_x' in cur_object.properties: my_sprite.change_x = float(cur_object.properties['change_x']) if cur_object.properties is not None and 'change_y' in cur_object.properties: my_sprite.change_y = float(cur_object.properties['change_y']) if cur_object.properties is not None and 'boundary_bottom' in cur_object.properties: my_sprite.boundary_bottom = float(cur_object.properties['boundary_bottom']) if cur_object.properties is not None and 'boundary_top' in cur_object.properties: my_sprite.boundary_top = float(cur_object.properties['boundary_top']) if cur_object.properties is not None and 'boundary_left' in cur_object.properties: my_sprite.boundary_left = float(cur_object.properties['boundary_left']) if cur_object.properties is not None and 'boundary_right' in cur_object.properties: my_sprite.boundary_right = float(cur_object.properties['boundary_right']) if cur_object.properties is not None: my_sprite.properties.update(cur_object.properties) if cur_object.type: my_sprite.properties['type'] = cur_object.type if cur_object.name: my_sprite.properties['name'] = cur_object.name sprite_list.append(my_sprite) return sprite_list def _process_tile_layer(map_object: pytiled_parser.objects.TileMap, layer: pytiled_parser.objects.TileLayer, scaling: float = 1, base_directory: str = "", use_spatial_hash: Optional[bool] = None, hit_box_algorithm="Simple", hit_box_detail: float = 4.5 ) -> SpriteList: sprite_list: SpriteList = SpriteList(use_spatial_hash=use_spatial_hash) map_array = layer.layer_data # Loop through the layer and add in the wall list for row_index, row in enumerate(map_array): for column_index, item in enumerate(row): # Check for empty square if item == 0: continue tile = _get_tile_by_gid(map_object, item) if tile is None: print(f"Warning, couldn't find tile for item {item} in layer " f"'{layer.name}' in file '{map_object.tmx_file}'.") continue my_sprite = _create_sprite_from_tile(map_object, tile, scaling=scaling, base_directory=base_directory, hit_box_algorithm=hit_box_algorithm, hit_box_detail=hit_box_detail) if my_sprite is None: print(f"Warning: Could not create sprite number {item} in layer '{layer.name}' {tile.image.source}") else: my_sprite.center_x = column_index * (map_object.tile_size[0] * scaling) + my_sprite.width / 2 my_sprite.center_y = (map_object.map_size.height - row_index - 1) \ * (map_object.tile_size[1] * scaling) + my_sprite.height / 2 # Opacity opacity = layer.opacity if opacity: my_sprite.alpha = int(opacity * 255) sprite_list.append(my_sprite) return sprite_list def process_layer(map_object: pytiled_parser.objects.TileMap, layer_name: str, scaling: float = 1, base_directory: str = "", use_spatial_hash: Optional[bool] = None, hit_box_algorithm="Simple", hit_box_detail: float = 4.5 ) -> SpriteList: """ This takes a map layer returned by the read_tmx function, and creates Sprites for it. :param map_object: The TileMap read in by read_tmx. :param layer_name: The name of the layer that we are creating sprites for. :param scaling: Scaling the layer up or down. (Note, any number besides 1 can create a tearing effect, if numbers don't evenly divide.) :param base_directory: Base directory of the file, that we start from to load images. :param use_spatial_hash: If all, or at least 75%, of the loaded tiles will not move between frames and you are using either the simple physics engine or platformer physics engine, set this to True to speed collision calculation. Leave False if using PyMunk, if all sprites are moving, or if no collision will be checked. :param str hit_box_algorithm: One of 'None', 'Simple' or 'Detailed'. \ Defaults to 'Simple'. Use 'Simple' for the :data:`PhysicsEngineSimple`, \ :data:`PhysicsEnginePlatformer` \ and 'Detailed' for the :data:`PymunkPhysicsEngine`. .. figure:: images/hit_box_algorithm_none.png :width: 40% hit_box_algorithm = "None" .. figure:: images/hit_box_algorithm_simple.png :width: 55% hit_box_algorithm = "Simple" .. figure:: images/hit_box_algorithm_detailed.png :width: 75% hit_box_algorithm = "Detailed" :param float hit_box_detail: Float, defaults to 4.5. Used with 'Detailed' to hit box :returns: A SpriteList. """ if len(base_directory) > 0 and not base_directory.endswith("/"): base_directory += "/" layer = get_tilemap_layer(map_object, layer_name) if layer is None: print(f"Warning, no layer named '{layer_name}'.") return SpriteList() if isinstance(layer, pytiled_parser.objects.TileLayer): return _process_tile_layer(map_object, layer, scaling, base_directory, use_spatial_hash, hit_box_algorithm, hit_box_detail) elif isinstance(layer, pytiled_parser.objects.ObjectLayer): return _process_object_layer(map_object, layer, scaling, base_directory, use_spatial_hash, hit_box_algorithm, hit_box_detail ) print(f"Warning, layer '{layer_name}' has unexpected type. '{type(layer)}'") return SpriteList()
layer_name = path.pop(0) for layer in layers: if layer.name == layer_name: if isinstance(layer, pytiled_parser.objects.LayerGroup): if len(path) != 0: return _get_tilemap_layer(path, layer.layers) else: return layer return None
nmea_topic_driver.py
# Software License Agreement (BSD License) # # Copyright (c) 2013, Eric Perko # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the names of the authors nor the names of their # affiliated organizations may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Defines the main method for the nmea_topic_driver executable.""" from nmea_msgs.msg import Sentence import rospy from libnmea_navsat_driver.driver import RosNMEADriver def nmea_sentence_callback(nmea_sentence, driver): """Process a NMEA sentence message with a RosNMEADriver. Args: nmea_sentence (nmea_msgs.msg.Sentence): NMEA sentence message to feed to the driver. driver (RosNMEADriver): Driver to feed the sentence. """ try: driver.add_sentence( nmea_sentence.sentence, frame_id=nmea_sentence.header.frame_id, timestamp=nmea_sentence.header.stamp) except ValueError as e: rospy.logwarn( "Value error, likely due to missing fields in the NMEA message. " "Error was: %s. Please report this issue at github.com/ros-drivers/nmea_navsat_driver, " "including a bag file with the NMEA sentences that caused it." % e) def
(): """Create and run the nmea_topic_driver ROS node. Creates a NMEA Driver and feeds it NMEA sentence strings from a ROS subscriber. ROS subscribers: mea_sentence (nmea_msgs.msg.Sentence): NMEA sentence messages to feed to the driver. """ rospy.init_node('nmea_topic_driver') driver = RosNMEADriver() rospy.Subscriber("nmea_sentence", Sentence, nmea_sentence_callback, driver) rospy.spin()
main
stopWords.py
from flask import Flask, render_template, request import json import requests app = Flask(__name__) @app.route('/') def stop_words():
if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port) #app.run()
URL_prefix = 'https://api.github.com/search/code?q=' URL_suffix = '+repo:spotify/mkdocs-monorepo-plugin/docs' reportfile = open('./templates/stopWordsSearch.html', 'w') reportfile.write('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">') reportfile.write('<link rel="stylesheet" type="text/css" href="../static/bootstrap.min.css">') reportfile.write('<link rel="stylesheet" type="text/css" href="../static/common.css">') reportfile.write('<script src="../static/jquery.min.js"></script>') reportfile.write('<script src="../static/popper.min.js"></script>') reportfile.write('<script src="../static/bootstrap.min.js"></script>') reportfile.write('<title>Stop-words Search</title></head>') reportfile.write('<body><div class="container"><h1>Stop-words Search</h1>') fname = './static/wordList.txt' wordlist = [] explainlist = [] print("\n") print('Reading the word list ...\n') fwordlist = open(fname, 'r') for line in fwordlist: colon = line.find(':') word = line[0:(colon)] explain = line[(colon + 1):] explain = explain.rstrip() print(word) print(explain) wordlist.append(word) explainlist.append(explain) fwordlist.close() print(wordlist) print(explainlist) x = len(wordlist) print('\nNo. of words and phrases to search for: ', x) try: reportfile.write('<p class="lead">Consider reviewing the occurrences of the following words in the documentation.</p><hr/>') wordpos = 0 for word in wordlist: url_string = URL_prefix + word + URL_suffix r = requests.get(url_string) json_data = json.loads(json.dumps(r.json())) print(json_data) if len(json_data['items']) != 0: print(word) reportfile.write('<div class="container">') reportfile.write('<h2>' + word + '</h2>') print(explainlist[wordpos]) reportfile.write('<p>' + explainlist[wordpos] + '</p>') print(json_data['total_count'], 'instances of', word) reportfile.write('<p>' + str(json_data['total_count']) + ' instances of <mark>' + word + '</mark> found in the following files:</p>') reportfile.write('<ul>') for line in json_data['items']: for k, v in line.items(): if k == 'path': print(v) reportfile.write('<li>' + v + '</li>') print('--------\n') reportfile.write('</ul>') reportfile.write('</div>') reportfile.write('<hr/>') wordpos = wordpos + 1 except: reportfile.write("<p class='text-danger'>&gt;&gt;&gt;&gt;&gt; If you're seeing these lines, it means you've hit the API rate limits for GitHub search and the Stopwords search was abandoned.</p>") #reportfile.write("<p class='text-danger'>Had the search been completed, you would've got an output shown in the following image.</p>") #reportfile.write('<img src="../static/stopWords.png"/>') reportfile.write("<p class='text-danger'>Maybe choose a smaller documentation repository for your search?</p>") reportfile.write("<p class='text-danger'>But then, this is just a demo and you get the general idea, I hope? &lt;&lt;&lt;&lt;&lt;") reportfile.write("</div></body>") reportfile.write("</html>") reportfile.close() return render_template('stopWordsSearch.html')
actions.js
import { CHANGE_THEME, CHANGE_TAB, CREATE_MESSAGE, MAKE_DAMAGE } from './types' export function changeTheme(newTheme) { return { type: CHANGE_THEME, payload: newTheme, } } export function changeTab(newTab) { return { type: CHANGE_TAB, payload: newTab, } }
payload: [newMessage, newUser, newUserColor, newHealth], } } export function makeDamage(damage) { return { type: MAKE_DAMAGE, payload: damage, } }
export function createMessage(newMessage, newUser, newUserColor, newHealth) { return { type: CREATE_MESSAGE,
printf.go
package fmt import ( "io" "strings" ) func findVerb(f string) (int, string, byte) { start := strings.IndexByte(f, '%') if start == -1 { return len(f), "", 0 } f = f[start+1:] for k := 0; k < len(f); k++ { c := f[k] if c >= '0' && c <= '9' { continue } switch c { case '+', '-', ' ', '*', '#', '.': continue } return start, f[:k], c } return start, "", 0 } func Fprintf(w io.Writer, f string, a ...interface{}) (int, error) { neww := writer{w: w} p, ok := w.(printer) if !ok { p.writer = &neww } var m int for { start, flags, verb := findVerb(f) p.WriteString(f[:start]) if p.err != nil { return p.n, p.err } if start == len(f) { break } switch verb { case '%': p.WriteByte('%') case 0: // Unfinished format. p.fmtErr(0, "UNFINISHED", nil) default: if m < len(a)
m++ } if p.err != nil { return p.n, p.err } if m > len(a) { p.fmtErr(verb, "MISSING", nil) if p.err != nil { return p.n, p.err } } f = f[start+2+len(flags):] } for ; m < len(a); m++ { p.fmtErr(0, "EXTRA ", a[m]) if p.err != nil { break } } return p.n, p.err }
{ p.parse(flags) p.format(verb, a[m]) }
collections.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CollectionsRoutingModule } from './collections-routing.module'; import { CollectionsHomeComponent } from './collections-home/collections-home.component'; import { TableComponent } from './table/table.component'; import { SharedModule } from '../shared/shared.module'; import { BiographyComponent } from './biography/biography.component'; import { CompaniesComponent } from './companies/companies.component'; import { PartnersComponent } from './partners/partners.component'; import { TabsComponent } from './tabs/tabs.component'; @NgModule({ declarations: [CollectionsHomeComponent, TableComponent, BiographyComponent, CompaniesComponent, PartnersComponent, TabsComponent], imports: [ CommonModule, CollectionsRoutingModule, SharedModule ] }) export class
{ }
CollectionsModule
test_noop_task.py
# Copyright 2014 - Mirantis, 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. from oslo_config import cfg from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') WF = """ --- version: '2.0' wf: type: direct input: - num1 - num2 output: result: <% $.result %> tasks: task1: action: std.echo output=<% $.num1 %> publish: result1: <% task(task1).result %> on-complete: - task3 task2: action: std.echo output=<% $.num2 %> publish: result2: <% task(task2).result %> on-complete: - task3 task3: description: | This task doesn't "action" or "workflow" property. It works as "no-op" task and serves just a decision point in the workflow. join: all on-complete: - task4: <% $.num1 + $.num2 = 2 %> - task5: <% $.num1 + $.num2 = 3 %> task4: action: std.echo output=4 publish: result: <% task(task4).result %> task5: action: std.echo output=5 publish: result: <% task(task5).result %> """ class NoopTaskEngineTest(base.EngineTestCase): def test_noop_task1(self): wf_service.create_workflows(WF) # Start workflow. wf_ex = self.engine.start_workflow('wf', {'num1': 1, 'num2': 1}) self.await_execution_success(wf_ex.id) # Note: We need to reread execution to access related tasks. wf_ex = db_api.get_workflow_execution(wf_ex.id) tasks = wf_ex.task_executions self.assertEqual(4, len(tasks)) task1 = self._assert_single_item(tasks, name='task1') task2 = self._assert_single_item(tasks, name='task2') task3 = self._assert_single_item(tasks, name='task3') task4 = self._assert_single_item(tasks, name='task4') self.assertEqual(states.SUCCESS, task1.state) self.assertEqual(states.SUCCESS, task2.state) self.assertEqual(states.SUCCESS, task3.state) self.assertEqual(states.SUCCESS, task4.state) self.assertDictEqual({'result': 4}, wf_ex.output) def test_noop_task2(self):
wf_service.create_workflows(WF) # Start workflow. wf_ex = self.engine.start_workflow('wf', {'num1': 1, 'num2': 2}) self.await_execution_success(wf_ex.id) # Note: We need to reread execution to access related tasks. wf_ex = db_api.get_workflow_execution(wf_ex.id) tasks = wf_ex.task_executions self.assertEqual(4, len(tasks)) task1 = self._assert_single_item(tasks, name='task1') task2 = self._assert_single_item(tasks, name='task2') task3 = self._assert_single_item(tasks, name='task3') task5 = self._assert_single_item(tasks, name='task5') self.assertEqual(states.SUCCESS, task1.state) self.assertEqual(states.SUCCESS, task2.state) self.assertEqual(states.SUCCESS, task3.state) self.assertEqual(states.SUCCESS, task5.state) self.assertDictEqual({'result': 5}, wf_ex.output)
device_code_responses.rs
use oauth2::AccessToken; use serde::Deserialize; use thiserror::Error; use std::convert::TryInto; use std::fmt; #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct DeviceCodeErrorResponse { pub error: String, pub error_description: String, pub error_uri: String, } impl fmt::Display for DeviceCodeErrorResponse { // This trait requires `fmt` with this exact signature. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}. {}", self.error, self.error_description) } } #[derive(Debug, Clone, Deserialize)] pub struct DeviceCodeAuthorization { pub token_type: String, pub scope: String, pub expires_in: u64, access_token: AccessToken, refresh_token: Option<AccessToken>, id_token: Option<AccessToken>, } impl DeviceCodeAuthorization { pub fn access_token(&self) -> &AccessToken { &self.access_token } pub fn refresh_token(&self) -> Option<&AccessToken> { self.refresh_token.as_ref() } pub fn id_token(&self) -> Option<&AccessToken> { self.id_token.as_ref() } } #[derive(Error, Debug)] pub enum DeviceCodeError { #[error("Authorization declined")] AuthorizationDeclined(DeviceCodeErrorResponse), #[error("Bad verification code")] BadVerificationCode(DeviceCodeErrorResponse), #[error("Expired token")] ExpiredToken(DeviceCodeErrorResponse), #[error("Unrecognized error: {0}")] UnrecognizedError(DeviceCodeErrorResponse), #[error("Unhandled error: {0}. {1}")] UnhandledError(String, String), #[error("Reqwest error: {0}")] ReqwestError(reqwest::Error), } #[derive(Debug, Clone)] pub enum DeviceCodeResponse { AuthorizationSucceded(DeviceCodeAuthorization), AuthorizationPending(DeviceCodeErrorResponse), } impl TryInto<DeviceCodeResponse> for String { type Error = DeviceCodeError; fn
(self) -> Result<DeviceCodeResponse, Self::Error> { // first we try to deserialize as DeviceCodeAuthorization (success) match serde_json::from_str::<DeviceCodeAuthorization>(&self) { Ok(device_code_authorization) => Ok(DeviceCodeResponse::AuthorizationSucceded( device_code_authorization, )), Err(_) => { // now we try to map it to a DeviceCodeErrorResponse match serde_json::from_str::<DeviceCodeErrorResponse>(&self) { Ok(device_code_error_response) => { match &device_code_error_response.error as &str { "authorization_pending" => { Ok(DeviceCodeResponse::AuthorizationPending( device_code_error_response, )) } "authorization_declined" => Err( DeviceCodeError::AuthorizationDeclined(device_code_error_response), ), "bad_verification_code" => Err(DeviceCodeError::BadVerificationCode( device_code_error_response, )), "expired_token" => { Err(DeviceCodeError::ExpiredToken(device_code_error_response)) } _ => Err(DeviceCodeError::UnrecognizedError( device_code_error_response, )), } } // If we cannot, we bail out giving the full error as string Err(error) => Err(DeviceCodeError::UnhandledError(error.to_string(), self)), } } } } }
try_into
tunerTrialKerasTunerTrialScore.ts
/** * Edge Impulse API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ export class TunerTrialKerasTunerTrialScore { 'value'?: number; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "value", "baseName": "value", "type": "number" } ]; static getAttributeTypeMap() { return TunerTrialKerasTunerTrialScore.attributeTypeMap; }
}
reflected.py
from torch.distributions import constraints from torch.distributions.transforms import AbsTransform from pyro.distributions.torch import TransformedDistribution class ReflectedDistribution(TransformedDistribution): """ Equivalent to ``TransformedDistribution(base_dist, AbsTransform())``, but additionally supports :meth:`log_prob` . :param ~torch.distributions.Distribution base_dist: The distribution to reflect. """ support = constraints.positive def __init__(self, base_dist, validate_args=None): if base_dist.event_shape:
super().__init__(base_dist, AbsTransform(), validate_args) def expand(self, batch_shape, _instance=None): new = self._get_checked_instance(type(self), _instance) return super().expand(batch_shape, _instance=new) def log_prob(self, value): if self._validate_args: self._validate_sample(value) dim = max(len(self.batch_shape), value.dim()) plus_minus = value.new_tensor([1., -1.]).reshape((2,) + (1,) * dim) return self.base_dist.log_prob(plus_minus * value).logsumexp(0)
raise ValueError("Only univariate distributions can be reflected.")
outputs.py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs from ._enums import * __all__ = [ 'AddressSpaceResponse', 'ApplicationGatewayAuthenticationCertificateResponse', 'ApplicationGatewayBackendAddressPoolResponse', 'ApplicationGatewayBackendAddressResponse', 'ApplicationGatewayBackendHttpSettingsResponse', 'ApplicationGatewayFrontendIPConfigurationResponse', 'ApplicationGatewayFrontendPortResponse', 'ApplicationGatewayHttpListenerResponse', 'ApplicationGatewayIPConfigurationResponse', 'ApplicationGatewayPathRuleResponse', 'ApplicationGatewayProbeResponse', 'ApplicationGatewayRequestRoutingRuleResponse', 'ApplicationGatewaySkuResponse', 'ApplicationGatewaySslCertificateResponse', 'ApplicationGatewaySslPolicyResponse', 'ApplicationGatewayUrlPathMapResponse', 'ApplicationGatewayWebApplicationFirewallConfigurationResponse', 'BackendAddressPoolResponse', 'BgpPeerStatusResponseResult', 'BgpSettingsResponse', 'DhcpOptionsResponse', 'ExpressRouteCircuitAuthorizationResponse', 'ExpressRouteCircuitPeeringConfigResponse', 'ExpressRouteCircuitPeeringResponse', 'ExpressRouteCircuitServiceProviderPropertiesResponse', 'ExpressRouteCircuitSkuResponse', 'ExpressRouteCircuitStatsResponse', 'FrontendIPConfigurationResponse', 'GatewayRouteResponseResult', 'IPConfigurationResponse', 'InboundNatPoolResponse', 'InboundNatRuleResponse', 'LoadBalancingRuleResponse', 'LocalNetworkGatewayResponse', 'NetworkInterfaceDnsSettingsResponse', 'NetworkInterfaceIPConfigurationResponse', 'NetworkInterfaceResponse', 'NetworkSecurityGroupResponse', 'OutboundNatRuleResponse', 'PacketCaptureFilterResponse', 'PacketCaptureStorageLocationResponse', 'ProbeResponse', 'PublicIPAddressDnsSettingsResponse', 'PublicIPAddressResponse', 'ResourceNavigationLinkResponse', 'RouteResponse', 'RouteTableResponse', 'SecurityRuleResponse', 'SubResourceResponse', 'SubnetResponse', 'TunnelConnectionHealthResponse', 'VirtualNetworkGatewayIPConfigurationResponse', 'VirtualNetworkGatewayResponse', 'VirtualNetworkGatewaySkuResponse', 'VirtualNetworkPeeringResponse', 'VpnClientConfigurationResponse', 'VpnClientRevokedCertificateResponse', 'VpnClientRootCertificateResponse', ] @pulumi.output_type class AddressSpaceResponse(dict): """ AddressSpace contains an array of IP address ranges that can be used by subnets of the virtual network. """ def __init__(__self__, *, address_prefixes: Optional[Sequence[str]] = None): """ AddressSpace contains an array of IP address ranges that can be used by subnets of the virtual network. :param Sequence[str] address_prefixes: A list of address blocks reserved for this virtual network in CIDR notation. """ if address_prefixes is not None: pulumi.set(__self__, "address_prefixes", address_prefixes) @property @pulumi.getter(name="addressPrefixes") def address_prefixes(self) -> Optional[Sequence[str]]: """ A list of address blocks reserved for this virtual network in CIDR notation. """ return pulumi.get(self, "address_prefixes") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayAuthenticationCertificateResponse(dict): """ Authentication certificates of an application gateway. """ def __init__(__self__, *, data: Optional[str] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, provisioning_state: Optional[str] = None): """ Authentication certificates of an application gateway. :param str data: Certificate public data. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param str provisioning_state: Provisioning state of the authentication certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ if data is not None: pulumi.set(__self__, "data", data) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter def data(self) -> Optional[str]: """ Certificate public data. """ return pulumi.get(self, "data") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the authentication certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayBackendAddressPoolResponse(dict): """ Backend Address Pool of an application gateway. """ def __init__(__self__, *, backend_addresses: Optional[Sequence['outputs.ApplicationGatewayBackendAddressResponse']] = None, backend_ip_configurations: Optional[Sequence['outputs.NetworkInterfaceIPConfigurationResponse']] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, provisioning_state: Optional[str] = None): """ Backend Address Pool of an application gateway. :param Sequence['ApplicationGatewayBackendAddressResponseArgs'] backend_addresses: Backend addresses :param Sequence['NetworkInterfaceIPConfigurationResponseArgs'] backend_ip_configurations: Collection of references to IPs defined in network interfaces. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Resource that is unique within a resource group. This name can be used to access the resource. :param str provisioning_state: Provisioning state of the backend address pool resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ if backend_addresses is not None: pulumi.set(__self__, "backend_addresses", backend_addresses) if backend_ip_configurations is not None: pulumi.set(__self__, "backend_ip_configurations", backend_ip_configurations) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="backendAddresses") def backend_addresses(self) -> Optional[Sequence['outputs.ApplicationGatewayBackendAddressResponse']]: """ Backend addresses """ return pulumi.get(self, "backend_addresses") @property @pulumi.getter(name="backendIPConfigurations") def backend_ip_configurations(self) -> Optional[Sequence['outputs.NetworkInterfaceIPConfigurationResponse']]: """ Collection of references to IPs defined in network interfaces. """ return pulumi.get(self, "backend_ip_configurations") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """
Resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the backend address pool resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayBackendAddressResponse(dict): """ Backend address of an application gateway. """ def __init__(__self__, *, fqdn: Optional[str] = None, ip_address: Optional[str] = None): """ Backend address of an application gateway. :param str fqdn: Fully qualified domain name (FQDN). :param str ip_address: IP address """ if fqdn is not None: pulumi.set(__self__, "fqdn", fqdn) if ip_address is not None: pulumi.set(__self__, "ip_address", ip_address) @property @pulumi.getter def fqdn(self) -> Optional[str]: """ Fully qualified domain name (FQDN). """ return pulumi.get(self, "fqdn") @property @pulumi.getter(name="ipAddress") def ip_address(self) -> Optional[str]: """ IP address """ return pulumi.get(self, "ip_address") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayBackendHttpSettingsResponse(dict): """ Backend address pool settings of an application gateway. """ def __init__(__self__, *, authentication_certificates: Optional[Sequence['outputs.SubResourceResponse']] = None, cookie_based_affinity: Optional[str] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, port: Optional[int] = None, probe: Optional['outputs.SubResourceResponse'] = None, protocol: Optional[str] = None, provisioning_state: Optional[str] = None, request_timeout: Optional[int] = None): """ Backend address pool settings of an application gateway. :param Sequence['SubResourceResponseArgs'] authentication_certificates: Array of references to application gateway authentication certificates. :param str cookie_based_affinity: Cookie based affinity. Possible values are: 'Enabled' and 'Disabled'. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param int port: Port :param 'SubResourceResponseArgs' probe: Probe resource of an application gateway. :param str protocol: Protocol. Possible values are: 'Http' and 'Https'. :param str provisioning_state: Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param int request_timeout: Request timeout in seconds. Application Gateway will fail the request if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400 seconds. """ if authentication_certificates is not None: pulumi.set(__self__, "authentication_certificates", authentication_certificates) if cookie_based_affinity is not None: pulumi.set(__self__, "cookie_based_affinity", cookie_based_affinity) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if port is not None: pulumi.set(__self__, "port", port) if probe is not None: pulumi.set(__self__, "probe", probe) if protocol is not None: pulumi.set(__self__, "protocol", protocol) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if request_timeout is not None: pulumi.set(__self__, "request_timeout", request_timeout) @property @pulumi.getter(name="authenticationCertificates") def authentication_certificates(self) -> Optional[Sequence['outputs.SubResourceResponse']]: """ Array of references to application gateway authentication certificates. """ return pulumi.get(self, "authentication_certificates") @property @pulumi.getter(name="cookieBasedAffinity") def cookie_based_affinity(self) -> Optional[str]: """ Cookie based affinity. Possible values are: 'Enabled' and 'Disabled'. """ return pulumi.get(self, "cookie_based_affinity") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def port(self) -> Optional[int]: """ Port """ return pulumi.get(self, "port") @property @pulumi.getter def probe(self) -> Optional['outputs.SubResourceResponse']: """ Probe resource of an application gateway. """ return pulumi.get(self, "probe") @property @pulumi.getter def protocol(self) -> Optional[str]: """ Protocol. Possible values are: 'Http' and 'Https'. """ return pulumi.get(self, "protocol") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="requestTimeout") def request_timeout(self) -> Optional[int]: """ Request timeout in seconds. Application Gateway will fail the request if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400 seconds. """ return pulumi.get(self, "request_timeout") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayFrontendIPConfigurationResponse(dict): """ Frontend IP configuration of an application gateway. """ def __init__(__self__, *, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, private_ip_address: Optional[str] = None, private_ip_allocation_method: Optional[str] = None, provisioning_state: Optional[str] = None, public_ip_address: Optional['outputs.SubResourceResponse'] = None, subnet: Optional['outputs.SubResourceResponse'] = None): """ Frontend IP configuration of an application gateway. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param str private_ip_address: PrivateIPAddress of the network interface IP Configuration. :param str private_ip_allocation_method: PrivateIP allocation method. Possible values are: 'Static' and 'Dynamic'. :param str provisioning_state: Provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param 'SubResourceResponseArgs' public_ip_address: Reference of the PublicIP resource. :param 'SubResourceResponseArgs' subnet: Reference of the subnet resource. """ if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if private_ip_address is not None: pulumi.set(__self__, "private_ip_address", private_ip_address) if private_ip_allocation_method is not None: pulumi.set(__self__, "private_ip_allocation_method", private_ip_allocation_method) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if public_ip_address is not None: pulumi.set(__self__, "public_ip_address", public_ip_address) if subnet is not None: pulumi.set(__self__, "subnet", subnet) @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="privateIPAddress") def private_ip_address(self) -> Optional[str]: """ PrivateIPAddress of the network interface IP Configuration. """ return pulumi.get(self, "private_ip_address") @property @pulumi.getter(name="privateIPAllocationMethod") def private_ip_allocation_method(self) -> Optional[str]: """ PrivateIP allocation method. Possible values are: 'Static' and 'Dynamic'. """ return pulumi.get(self, "private_ip_allocation_method") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicIPAddress") def public_ip_address(self) -> Optional['outputs.SubResourceResponse']: """ Reference of the PublicIP resource. """ return pulumi.get(self, "public_ip_address") @property @pulumi.getter def subnet(self) -> Optional['outputs.SubResourceResponse']: """ Reference of the subnet resource. """ return pulumi.get(self, "subnet") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayFrontendPortResponse(dict): """ Frontend port of an application gateway. """ def __init__(__self__, *, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, port: Optional[int] = None, provisioning_state: Optional[str] = None): """ Frontend port of an application gateway. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param int port: Frontend port :param str provisioning_state: Provisioning state of the frontend port resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if port is not None: pulumi.set(__self__, "port", port) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def port(self) -> Optional[int]: """ Frontend port """ return pulumi.get(self, "port") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the frontend port resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayHttpListenerResponse(dict): """ Http listener of an application gateway. """ def __init__(__self__, *, etag: Optional[str] = None, frontend_ip_configuration: Optional['outputs.SubResourceResponse'] = None, frontend_port: Optional['outputs.SubResourceResponse'] = None, host_name: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, protocol: Optional[str] = None, provisioning_state: Optional[str] = None, require_server_name_indication: Optional[bool] = None, ssl_certificate: Optional['outputs.SubResourceResponse'] = None): """ Http listener of an application gateway. :param str etag: A unique read-only string that changes whenever the resource is updated. :param 'SubResourceResponseArgs' frontend_ip_configuration: Frontend IP configuration resource of an application gateway. :param 'SubResourceResponseArgs' frontend_port: Frontend port resource of an application gateway. :param str host_name: Host name of HTTP listener. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param str protocol: Protocol. Possible values are: 'Http' and 'Https'. :param str provisioning_state: Provisioning state of the HTTP listener resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param bool require_server_name_indication: Applicable only if protocol is https. Enables SNI for multi-hosting. :param 'SubResourceResponseArgs' ssl_certificate: SSL certificate resource of an application gateway. """ if etag is not None: pulumi.set(__self__, "etag", etag) if frontend_ip_configuration is not None: pulumi.set(__self__, "frontend_ip_configuration", frontend_ip_configuration) if frontend_port is not None: pulumi.set(__self__, "frontend_port", frontend_port) if host_name is not None: pulumi.set(__self__, "host_name", host_name) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if protocol is not None: pulumi.set(__self__, "protocol", protocol) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if require_server_name_indication is not None: pulumi.set(__self__, "require_server_name_indication", require_server_name_indication) if ssl_certificate is not None: pulumi.set(__self__, "ssl_certificate", ssl_certificate) @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="frontendIPConfiguration") def frontend_ip_configuration(self) -> Optional['outputs.SubResourceResponse']: """ Frontend IP configuration resource of an application gateway. """ return pulumi.get(self, "frontend_ip_configuration") @property @pulumi.getter(name="frontendPort") def frontend_port(self) -> Optional['outputs.SubResourceResponse']: """ Frontend port resource of an application gateway. """ return pulumi.get(self, "frontend_port") @property @pulumi.getter(name="hostName") def host_name(self) -> Optional[str]: """ Host name of HTTP listener. """ return pulumi.get(self, "host_name") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def protocol(self) -> Optional[str]: """ Protocol. Possible values are: 'Http' and 'Https'. """ return pulumi.get(self, "protocol") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the HTTP listener resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="requireServerNameIndication") def require_server_name_indication(self) -> Optional[bool]: """ Applicable only if protocol is https. Enables SNI for multi-hosting. """ return pulumi.get(self, "require_server_name_indication") @property @pulumi.getter(name="sslCertificate") def ssl_certificate(self) -> Optional['outputs.SubResourceResponse']: """ SSL certificate resource of an application gateway. """ return pulumi.get(self, "ssl_certificate") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayIPConfigurationResponse(dict): """ IP configuration of an application gateway. Currently 1 public and 1 private IP configuration is allowed. """ def __init__(__self__, *, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, provisioning_state: Optional[str] = None, subnet: Optional['outputs.SubResourceResponse'] = None): """ IP configuration of an application gateway. Currently 1 public and 1 private IP configuration is allowed. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param str provisioning_state: Provisioning state of the application gateway subnet resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param 'SubResourceResponseArgs' subnet: Reference of the subnet resource. A subnet from where application gateway gets its private address. """ if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if subnet is not None: pulumi.set(__self__, "subnet", subnet) @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the application gateway subnet resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def subnet(self) -> Optional['outputs.SubResourceResponse']: """ Reference of the subnet resource. A subnet from where application gateway gets its private address. """ return pulumi.get(self, "subnet") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayPathRuleResponse(dict): """ Path rule of URL path map of an application gateway. """ def __init__(__self__, *, backend_address_pool: Optional['outputs.SubResourceResponse'] = None, backend_http_settings: Optional['outputs.SubResourceResponse'] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, paths: Optional[Sequence[str]] = None, provisioning_state: Optional[str] = None): """ Path rule of URL path map of an application gateway. :param 'SubResourceResponseArgs' backend_address_pool: Backend address pool resource of URL path map. :param 'SubResourceResponseArgs' backend_http_settings: Backend http settings resource of URL path map. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param Sequence[str] paths: Path rules of URL path map. :param str provisioning_state: Path rule of URL path map resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ if backend_address_pool is not None: pulumi.set(__self__, "backend_address_pool", backend_address_pool) if backend_http_settings is not None: pulumi.set(__self__, "backend_http_settings", backend_http_settings) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if paths is not None: pulumi.set(__self__, "paths", paths) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="backendAddressPool") def backend_address_pool(self) -> Optional['outputs.SubResourceResponse']: """ Backend address pool resource of URL path map. """ return pulumi.get(self, "backend_address_pool") @property @pulumi.getter(name="backendHttpSettings") def backend_http_settings(self) -> Optional['outputs.SubResourceResponse']: """ Backend http settings resource of URL path map. """ return pulumi.get(self, "backend_http_settings") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def paths(self) -> Optional[Sequence[str]]: """ Path rules of URL path map. """ return pulumi.get(self, "paths") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Path rule of URL path map resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayProbeResponse(dict): """ Probe of the application gateway. """ def __init__(__self__, *, etag: Optional[str] = None, host: Optional[str] = None, id: Optional[str] = None, interval: Optional[int] = None, name: Optional[str] = None, path: Optional[str] = None, protocol: Optional[str] = None, provisioning_state: Optional[str] = None, timeout: Optional[int] = None, unhealthy_threshold: Optional[int] = None): """ Probe of the application gateway. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str host: Host name to send the probe to. :param str id: Resource ID. :param int interval: The probing interval in seconds. This is the time interval between two consecutive probes. Acceptable values are from 1 second to 86400 seconds. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param str path: Relative path of probe. Valid path starts from '/'. Probe is sent to <Protocol>://<host>:<port><path> :param str protocol: Protocol. Possible values are: 'Http' and 'Https'. :param str provisioning_state: Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param int timeout: the probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds. :param int unhealthy_threshold: The probe retry count. Backend server is marked down after consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second to 20. """ if etag is not None: pulumi.set(__self__, "etag", etag) if host is not None: pulumi.set(__self__, "host", host) if id is not None: pulumi.set(__self__, "id", id) if interval is not None: pulumi.set(__self__, "interval", interval) if name is not None: pulumi.set(__self__, "name", name) if path is not None: pulumi.set(__self__, "path", path) if protocol is not None: pulumi.set(__self__, "protocol", protocol) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if timeout is not None: pulumi.set(__self__, "timeout", timeout) if unhealthy_threshold is not None: pulumi.set(__self__, "unhealthy_threshold", unhealthy_threshold) @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def host(self) -> Optional[str]: """ Host name to send the probe to. """ return pulumi.get(self, "host") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def interval(self) -> Optional[int]: """ The probing interval in seconds. This is the time interval between two consecutive probes. Acceptable values are from 1 second to 86400 seconds. """ return pulumi.get(self, "interval") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def path(self) -> Optional[str]: """ Relative path of probe. Valid path starts from '/'. Probe is sent to <Protocol>://<host>:<port><path> """ return pulumi.get(self, "path") @property @pulumi.getter def protocol(self) -> Optional[str]: """ Protocol. Possible values are: 'Http' and 'Https'. """ return pulumi.get(self, "protocol") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def timeout(self) -> Optional[int]: """ the probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds. """ return pulumi.get(self, "timeout") @property @pulumi.getter(name="unhealthyThreshold") def unhealthy_threshold(self) -> Optional[int]: """ The probe retry count. Backend server is marked down after consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second to 20. """ return pulumi.get(self, "unhealthy_threshold") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayRequestRoutingRuleResponse(dict): """ Request routing rule of an application gateway. """ def __init__(__self__, *, backend_address_pool: Optional['outputs.SubResourceResponse'] = None, backend_http_settings: Optional['outputs.SubResourceResponse'] = None, etag: Optional[str] = None, http_listener: Optional['outputs.SubResourceResponse'] = None, id: Optional[str] = None, name: Optional[str] = None, provisioning_state: Optional[str] = None, rule_type: Optional[str] = None, url_path_map: Optional['outputs.SubResourceResponse'] = None): """ Request routing rule of an application gateway. :param 'SubResourceResponseArgs' backend_address_pool: Backend address pool resource of the application gateway. :param 'SubResourceResponseArgs' backend_http_settings: Frontend port resource of the application gateway. :param str etag: A unique read-only string that changes whenever the resource is updated. :param 'SubResourceResponseArgs' http_listener: Http listener resource of the application gateway. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param str provisioning_state: Provisioning state of the request routing rule resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str rule_type: Rule type. Possible values are: 'Basic' and 'PathBasedRouting'. :param 'SubResourceResponseArgs' url_path_map: URL path map resource of the application gateway. """ if backend_address_pool is not None: pulumi.set(__self__, "backend_address_pool", backend_address_pool) if backend_http_settings is not None: pulumi.set(__self__, "backend_http_settings", backend_http_settings) if etag is not None: pulumi.set(__self__, "etag", etag) if http_listener is not None: pulumi.set(__self__, "http_listener", http_listener) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if rule_type is not None: pulumi.set(__self__, "rule_type", rule_type) if url_path_map is not None: pulumi.set(__self__, "url_path_map", url_path_map) @property @pulumi.getter(name="backendAddressPool") def backend_address_pool(self) -> Optional['outputs.SubResourceResponse']: """ Backend address pool resource of the application gateway. """ return pulumi.get(self, "backend_address_pool") @property @pulumi.getter(name="backendHttpSettings") def backend_http_settings(self) -> Optional['outputs.SubResourceResponse']: """ Frontend port resource of the application gateway. """ return pulumi.get(self, "backend_http_settings") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="httpListener") def http_listener(self) -> Optional['outputs.SubResourceResponse']: """ Http listener resource of the application gateway. """ return pulumi.get(self, "http_listener") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the request routing rule resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="ruleType") def rule_type(self) -> Optional[str]: """ Rule type. Possible values are: 'Basic' and 'PathBasedRouting'. """ return pulumi.get(self, "rule_type") @property @pulumi.getter(name="urlPathMap") def url_path_map(self) -> Optional['outputs.SubResourceResponse']: """ URL path map resource of the application gateway. """ return pulumi.get(self, "url_path_map") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewaySkuResponse(dict): """ SKU of an application gateway """ def __init__(__self__, *, capacity: Optional[int] = None, name: Optional[str] = None, tier: Optional[str] = None): """ SKU of an application gateway :param int capacity: Capacity (instance count) of an application gateway. :param str name: Name of an application gateway SKU. Possible values are: 'Standard_Small', 'Standard_Medium', 'Standard_Large', 'WAF_Medium', and 'WAF_Large'. :param str tier: Tier of an application gateway. Possible values are: 'Standard' and 'WAF'. """ if capacity is not None: pulumi.set(__self__, "capacity", capacity) if name is not None: pulumi.set(__self__, "name", name) if tier is not None: pulumi.set(__self__, "tier", tier) @property @pulumi.getter def capacity(self) -> Optional[int]: """ Capacity (instance count) of an application gateway. """ return pulumi.get(self, "capacity") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of an application gateway SKU. Possible values are: 'Standard_Small', 'Standard_Medium', 'Standard_Large', 'WAF_Medium', and 'WAF_Large'. """ return pulumi.get(self, "name") @property @pulumi.getter def tier(self) -> Optional[str]: """ Tier of an application gateway. Possible values are: 'Standard' and 'WAF'. """ return pulumi.get(self, "tier") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewaySslCertificateResponse(dict): """ SSL certificates of an application gateway. """ def __init__(__self__, *, data: Optional[str] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, password: Optional[str] = None, provisioning_state: Optional[str] = None, public_cert_data: Optional[str] = None): """ SSL certificates of an application gateway. :param str data: Base-64 encoded pfx certificate. Only applicable in PUT Request. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param str password: Password for the pfx file specified in data. Only applicable in PUT request. :param str provisioning_state: Provisioning state of the SSL certificate resource Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str public_cert_data: Base-64 encoded Public cert data corresponding to pfx specified in data. Only applicable in GET request. """ if data is not None: pulumi.set(__self__, "data", data) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if password is not None: pulumi.set(__self__, "password", password) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if public_cert_data is not None: pulumi.set(__self__, "public_cert_data", public_cert_data) @property @pulumi.getter def data(self) -> Optional[str]: """ Base-64 encoded pfx certificate. Only applicable in PUT Request. """ return pulumi.get(self, "data") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def password(self) -> Optional[str]: """ Password for the pfx file specified in data. Only applicable in PUT request. """ return pulumi.get(self, "password") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the SSL certificate resource Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicCertData") def public_cert_data(self) -> Optional[str]: """ Base-64 encoded Public cert data corresponding to pfx specified in data. Only applicable in GET request. """ return pulumi.get(self, "public_cert_data") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewaySslPolicyResponse(dict): """ Application gateway SSL policy. """ def __init__(__self__, *, disabled_ssl_protocols: Optional[Sequence[str]] = None): """ Application gateway SSL policy. :param Sequence[str] disabled_ssl_protocols: SSL protocols to be disabled on application gateway. Possible values are: 'TLSv1_0', 'TLSv1_1', and 'TLSv1_2'. """ if disabled_ssl_protocols is not None: pulumi.set(__self__, "disabled_ssl_protocols", disabled_ssl_protocols) @property @pulumi.getter(name="disabledSslProtocols") def disabled_ssl_protocols(self) -> Optional[Sequence[str]]: """ SSL protocols to be disabled on application gateway. Possible values are: 'TLSv1_0', 'TLSv1_1', and 'TLSv1_2'. """ return pulumi.get(self, "disabled_ssl_protocols") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayUrlPathMapResponse(dict): """ UrlPathMaps give a url path to the backend mapping information for PathBasedRouting. """ def __init__(__self__, *, default_backend_address_pool: Optional['outputs.SubResourceResponse'] = None, default_backend_http_settings: Optional['outputs.SubResourceResponse'] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, path_rules: Optional[Sequence['outputs.ApplicationGatewayPathRuleResponse']] = None, provisioning_state: Optional[str] = None): """ UrlPathMaps give a url path to the backend mapping information for PathBasedRouting. :param 'SubResourceResponseArgs' default_backend_address_pool: Default backend address pool resource of URL path map. :param 'SubResourceResponseArgs' default_backend_http_settings: Default backend http settings resource of URL path map. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :param Sequence['ApplicationGatewayPathRuleResponseArgs'] path_rules: Path rule of URL path map resource. :param str provisioning_state: Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ if default_backend_address_pool is not None: pulumi.set(__self__, "default_backend_address_pool", default_backend_address_pool) if default_backend_http_settings is not None: pulumi.set(__self__, "default_backend_http_settings", default_backend_http_settings) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if path_rules is not None: pulumi.set(__self__, "path_rules", path_rules) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="defaultBackendAddressPool") def default_backend_address_pool(self) -> Optional['outputs.SubResourceResponse']: """ Default backend address pool resource of URL path map. """ return pulumi.get(self, "default_backend_address_pool") @property @pulumi.getter(name="defaultBackendHttpSettings") def default_backend_http_settings(self) -> Optional['outputs.SubResourceResponse']: """ Default backend http settings resource of URL path map. """ return pulumi.get(self, "default_backend_http_settings") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="pathRules") def path_rules(self) -> Optional[Sequence['outputs.ApplicationGatewayPathRuleResponse']]: """ Path rule of URL path map resource. """ return pulumi.get(self, "path_rules") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ApplicationGatewayWebApplicationFirewallConfigurationResponse(dict): """ Application gateway web application firewall configuration. """ def __init__(__self__, *, enabled: bool, firewall_mode: Optional[str] = None): """ Application gateway web application firewall configuration. :param bool enabled: Whether the web application firewall is enabled. :param str firewall_mode: Web application firewall mode. Possible values are: 'Detection' and 'Prevention'. """ pulumi.set(__self__, "enabled", enabled) if firewall_mode is not None: pulumi.set(__self__, "firewall_mode", firewall_mode) @property @pulumi.getter def enabled(self) -> bool: """ Whether the web application firewall is enabled. """ return pulumi.get(self, "enabled") @property @pulumi.getter(name="firewallMode") def firewall_mode(self) -> Optional[str]: """ Web application firewall mode. Possible values are: 'Detection' and 'Prevention'. """ return pulumi.get(self, "firewall_mode") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class BackendAddressPoolResponse(dict): """ Pool of backend IP addresses. """ def __init__(__self__, *, backend_ip_configurations: Sequence['outputs.NetworkInterfaceIPConfigurationResponse'], load_balancing_rules: Sequence['outputs.SubResourceResponse'], outbound_nat_rule: 'outputs.SubResourceResponse', etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, provisioning_state: Optional[str] = None): """ Pool of backend IP addresses. :param Sequence['NetworkInterfaceIPConfigurationResponseArgs'] backend_ip_configurations: Gets collection of references to IP addresses defined in network interfaces. :param Sequence['SubResourceResponseArgs'] load_balancing_rules: Gets load balancing rules that use this backend address pool. :param 'SubResourceResponseArgs' outbound_nat_rule: Gets outbound rules that use this backend address pool. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :param str provisioning_state: Get provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ pulumi.set(__self__, "backend_ip_configurations", backend_ip_configurations) pulumi.set(__self__, "load_balancing_rules", load_balancing_rules) pulumi.set(__self__, "outbound_nat_rule", outbound_nat_rule) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="backendIPConfigurations") def backend_ip_configurations(self) -> Sequence['outputs.NetworkInterfaceIPConfigurationResponse']: """ Gets collection of references to IP addresses defined in network interfaces. """ return pulumi.get(self, "backend_ip_configurations") @property @pulumi.getter(name="loadBalancingRules") def load_balancing_rules(self) -> Sequence['outputs.SubResourceResponse']: """ Gets load balancing rules that use this backend address pool. """ return pulumi.get(self, "load_balancing_rules") @property @pulumi.getter(name="outboundNatRule") def outbound_nat_rule(self) -> 'outputs.SubResourceResponse': """ Gets outbound rules that use this backend address pool. """ return pulumi.get(self, "outbound_nat_rule") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Gets name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Get provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class BgpPeerStatusResponseResult(dict): def __init__(__self__, *, asn: int, connected_duration: str, local_address: str, messages_received: float, messages_sent: float, neighbor: str, routes_received: float, state: str): """ :param int asn: The autonomous system number of the remote BGP peer :param str connected_duration: For how long the peering has been up :param str local_address: The virtual network gateway's local address :param float messages_received: The number of BGP messages received :param float messages_sent: The number of BGP messages sent :param str neighbor: The remote BGP peer :param float routes_received: The number of routes learned from this peer :param str state: The BGP peer state """ pulumi.set(__self__, "asn", asn) pulumi.set(__self__, "connected_duration", connected_duration) pulumi.set(__self__, "local_address", local_address) pulumi.set(__self__, "messages_received", messages_received) pulumi.set(__self__, "messages_sent", messages_sent) pulumi.set(__self__, "neighbor", neighbor) pulumi.set(__self__, "routes_received", routes_received) pulumi.set(__self__, "state", state) @property @pulumi.getter def asn(self) -> int: """ The autonomous system number of the remote BGP peer """ return pulumi.get(self, "asn") @property @pulumi.getter(name="connectedDuration") def connected_duration(self) -> str: """ For how long the peering has been up """ return pulumi.get(self, "connected_duration") @property @pulumi.getter(name="localAddress") def local_address(self) -> str: """ The virtual network gateway's local address """ return pulumi.get(self, "local_address") @property @pulumi.getter(name="messagesReceived") def messages_received(self) -> float: """ The number of BGP messages received """ return pulumi.get(self, "messages_received") @property @pulumi.getter(name="messagesSent") def messages_sent(self) -> float: """ The number of BGP messages sent """ return pulumi.get(self, "messages_sent") @property @pulumi.getter def neighbor(self) -> str: """ The remote BGP peer """ return pulumi.get(self, "neighbor") @property @pulumi.getter(name="routesReceived") def routes_received(self) -> float: """ The number of routes learned from this peer """ return pulumi.get(self, "routes_received") @property @pulumi.getter def state(self) -> str: """ The BGP peer state """ return pulumi.get(self, "state") @pulumi.output_type class BgpSettingsResponse(dict): def __init__(__self__, *, asn: Optional[float] = None, bgp_peering_address: Optional[str] = None, peer_weight: Optional[int] = None): """ :param float asn: The BGP speaker's ASN. :param str bgp_peering_address: The BGP peering address and BGP identifier of this BGP speaker. :param int peer_weight: The weight added to routes learned from this BGP speaker. """ if asn is not None: pulumi.set(__self__, "asn", asn) if bgp_peering_address is not None: pulumi.set(__self__, "bgp_peering_address", bgp_peering_address) if peer_weight is not None: pulumi.set(__self__, "peer_weight", peer_weight) @property @pulumi.getter def asn(self) -> Optional[float]: """ The BGP speaker's ASN. """ return pulumi.get(self, "asn") @property @pulumi.getter(name="bgpPeeringAddress") def bgp_peering_address(self) -> Optional[str]: """ The BGP peering address and BGP identifier of this BGP speaker. """ return pulumi.get(self, "bgp_peering_address") @property @pulumi.getter(name="peerWeight") def peer_weight(self) -> Optional[int]: """ The weight added to routes learned from this BGP speaker. """ return pulumi.get(self, "peer_weight") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DhcpOptionsResponse(dict): """ DhcpOptions contains an array of DNS servers available to VMs deployed in the virtual network. Standard DHCP option for a subnet overrides VNET DHCP options. """ def __init__(__self__, *, dns_servers: Optional[Sequence[str]] = None): """ DhcpOptions contains an array of DNS servers available to VMs deployed in the virtual network. Standard DHCP option for a subnet overrides VNET DHCP options. :param Sequence[str] dns_servers: The list of DNS servers IP addresses. """ if dns_servers is not None: pulumi.set(__self__, "dns_servers", dns_servers) @property @pulumi.getter(name="dnsServers") def dns_servers(self) -> Optional[Sequence[str]]: """ The list of DNS servers IP addresses. """ return pulumi.get(self, "dns_servers") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ExpressRouteCircuitAuthorizationResponse(dict): """ Authorization in an ExpressRouteCircuit resource. """ def __init__(__self__, *, authorization_key: Optional[str] = None, authorization_use_status: Optional[str] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, provisioning_state: Optional[str] = None): """ Authorization in an ExpressRouteCircuit resource. :param str authorization_key: The authorization key. :param str authorization_use_status: AuthorizationUseStatus. Possible values are: 'Available' and 'InUse'. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :param str provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ if authorization_key is not None: pulumi.set(__self__, "authorization_key", authorization_key) if authorization_use_status is not None: pulumi.set(__self__, "authorization_use_status", authorization_use_status) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="authorizationKey") def authorization_key(self) -> Optional[str]: """ The authorization key. """ return pulumi.get(self, "authorization_key") @property @pulumi.getter(name="authorizationUseStatus") def authorization_use_status(self) -> Optional[str]: """ AuthorizationUseStatus. Possible values are: 'Available' and 'InUse'. """ return pulumi.get(self, "authorization_use_status") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ Gets name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ExpressRouteCircuitPeeringConfigResponse(dict): """ Specifies the peering configuration. """ def __init__(__self__, *, advertised_public_prefixes: Optional[Sequence[str]] = None, advertised_public_prefixes_state: Optional[str] = None, customer_asn: Optional[int] = None, routing_registry_name: Optional[str] = None): """ Specifies the peering configuration. :param Sequence[str] advertised_public_prefixes: The reference of AdvertisedPublicPrefixes. :param str advertised_public_prefixes_state: AdvertisedPublicPrefixState of the Peering resource. Possible values are 'NotConfigured', 'Configuring', 'Configured', and 'ValidationNeeded'. :param int customer_asn: The CustomerASN of the peering. :param str routing_registry_name: The RoutingRegistryName of the configuration. """ if advertised_public_prefixes is not None: pulumi.set(__self__, "advertised_public_prefixes", advertised_public_prefixes) if advertised_public_prefixes_state is not None: pulumi.set(__self__, "advertised_public_prefixes_state", advertised_public_prefixes_state) if customer_asn is not None: pulumi.set(__self__, "customer_asn", customer_asn) if routing_registry_name is not None: pulumi.set(__self__, "routing_registry_name", routing_registry_name) @property @pulumi.getter(name="advertisedPublicPrefixes") def advertised_public_prefixes(self) -> Optional[Sequence[str]]: """ The reference of AdvertisedPublicPrefixes. """ return pulumi.get(self, "advertised_public_prefixes") @property @pulumi.getter(name="advertisedPublicPrefixesState") def advertised_public_prefixes_state(self) -> Optional[str]: """ AdvertisedPublicPrefixState of the Peering resource. Possible values are 'NotConfigured', 'Configuring', 'Configured', and 'ValidationNeeded'. """ return pulumi.get(self, "advertised_public_prefixes_state") @property @pulumi.getter(name="customerASN") def customer_asn(self) -> Optional[int]: """ The CustomerASN of the peering. """ return pulumi.get(self, "customer_asn") @property @pulumi.getter(name="routingRegistryName") def routing_registry_name(self) -> Optional[str]: """ The RoutingRegistryName of the configuration. """ return pulumi.get(self, "routing_registry_name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ExpressRouteCircuitPeeringResponse(dict): """ Peering in an ExpressRouteCircuit resource. """ def __init__(__self__, *, azure_asn: Optional[int] = None, etag: Optional[str] = None, gateway_manager_etag: Optional[str] = None, id: Optional[str] = None, last_modified_by: Optional[str] = None, microsoft_peering_config: Optional['outputs.ExpressRouteCircuitPeeringConfigResponse'] = None, name: Optional[str] = None, peer_asn: Optional[int] = None, peering_type: Optional[str] = None, primary_azure_port: Optional[str] = None, primary_peer_address_prefix: Optional[str] = None, provisioning_state: Optional[str] = None, secondary_azure_port: Optional[str] = None, secondary_peer_address_prefix: Optional[str] = None, shared_key: Optional[str] = None, state: Optional[str] = None, stats: Optional['outputs.ExpressRouteCircuitStatsResponse'] = None, vlan_id: Optional[int] = None): """ Peering in an ExpressRouteCircuit resource. :param int azure_asn: The Azure ASN. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str gateway_manager_etag: The GatewayManager Etag. :param str id: Resource ID. :param str last_modified_by: Gets whether the provider or the customer last modified the peering. :param 'ExpressRouteCircuitPeeringConfigResponseArgs' microsoft_peering_config: The Microsoft peering configuration. :param str name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :param int peer_asn: The peer ASN. :param str peering_type: The PeeringType. Possible values are: 'AzurePublicPeering', 'AzurePrivatePeering', and 'MicrosoftPeering'. :param str primary_azure_port: The primary port. :param str primary_peer_address_prefix: The primary address prefix. :param str provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str secondary_azure_port: The secondary port. :param str secondary_peer_address_prefix: The secondary address prefix. :param str shared_key: The shared key. :param str state: The state of peering. Possible values are: 'Disabled' and 'Enabled' :param 'ExpressRouteCircuitStatsResponseArgs' stats: Gets peering stats. :param int vlan_id: The VLAN ID. """ if azure_asn is not None: pulumi.set(__self__, "azure_asn", azure_asn) if etag is not None: pulumi.set(__self__, "etag", etag) if gateway_manager_etag is not None: pulumi.set(__self__, "gateway_manager_etag", gateway_manager_etag) if id is not None: pulumi.set(__self__, "id", id) if last_modified_by is not None: pulumi.set(__self__, "last_modified_by", last_modified_by) if microsoft_peering_config is not None: pulumi.set(__self__, "microsoft_peering_config", microsoft_peering_config) if name is not None: pulumi.set(__self__, "name", name) if peer_asn is not None: pulumi.set(__self__, "peer_asn", peer_asn) if peering_type is not None: pulumi.set(__self__, "peering_type", peering_type) if primary_azure_port is not None: pulumi.set(__self__, "primary_azure_port", primary_azure_port) if primary_peer_address_prefix is not None: pulumi.set(__self__, "primary_peer_address_prefix", primary_peer_address_prefix) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if secondary_azure_port is not None: pulumi.set(__self__, "secondary_azure_port", secondary_azure_port) if secondary_peer_address_prefix is not None: pulumi.set(__self__, "secondary_peer_address_prefix", secondary_peer_address_prefix) if shared_key is not None: pulumi.set(__self__, "shared_key", shared_key) if state is not None: pulumi.set(__self__, "state", state) if stats is not None: pulumi.set(__self__, "stats", stats) if vlan_id is not None: pulumi.set(__self__, "vlan_id", vlan_id) @property @pulumi.getter(name="azureASN") def azure_asn(self) -> Optional[int]: """ The Azure ASN. """ return pulumi.get(self, "azure_asn") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="gatewayManagerEtag") def gateway_manager_etag(self) -> Optional[str]: """ The GatewayManager Etag. """ return pulumi.get(self, "gateway_manager_etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter(name="lastModifiedBy") def last_modified_by(self) -> Optional[str]: """ Gets whether the provider or the customer last modified the peering. """ return pulumi.get(self, "last_modified_by") @property @pulumi.getter(name="microsoftPeeringConfig") def microsoft_peering_config(self) -> Optional['outputs.ExpressRouteCircuitPeeringConfigResponse']: """ The Microsoft peering configuration. """ return pulumi.get(self, "microsoft_peering_config") @property @pulumi.getter def name(self) -> Optional[str]: """ Gets name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="peerASN") def peer_asn(self) -> Optional[int]: """ The peer ASN. """ return pulumi.get(self, "peer_asn") @property @pulumi.getter(name="peeringType") def peering_type(self) -> Optional[str]: """ The PeeringType. Possible values are: 'AzurePublicPeering', 'AzurePrivatePeering', and 'MicrosoftPeering'. """ return pulumi.get(self, "peering_type") @property @pulumi.getter(name="primaryAzurePort") def primary_azure_port(self) -> Optional[str]: """ The primary port. """ return pulumi.get(self, "primary_azure_port") @property @pulumi.getter(name="primaryPeerAddressPrefix") def primary_peer_address_prefix(self) -> Optional[str]: """ The primary address prefix. """ return pulumi.get(self, "primary_peer_address_prefix") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="secondaryAzurePort") def secondary_azure_port(self) -> Optional[str]: """ The secondary port. """ return pulumi.get(self, "secondary_azure_port") @property @pulumi.getter(name="secondaryPeerAddressPrefix") def secondary_peer_address_prefix(self) -> Optional[str]: """ The secondary address prefix. """ return pulumi.get(self, "secondary_peer_address_prefix") @property @pulumi.getter(name="sharedKey") def shared_key(self) -> Optional[str]: """ The shared key. """ return pulumi.get(self, "shared_key") @property @pulumi.getter def state(self) -> Optional[str]: """ The state of peering. Possible values are: 'Disabled' and 'Enabled' """ return pulumi.get(self, "state") @property @pulumi.getter def stats(self) -> Optional['outputs.ExpressRouteCircuitStatsResponse']: """ Gets peering stats. """ return pulumi.get(self, "stats") @property @pulumi.getter(name="vlanId") def vlan_id(self) -> Optional[int]: """ The VLAN ID. """ return pulumi.get(self, "vlan_id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ExpressRouteCircuitServiceProviderPropertiesResponse(dict): """ Contains ServiceProviderProperties in an ExpressRouteCircuit. """ def __init__(__self__, *, bandwidth_in_mbps: Optional[int] = None, peering_location: Optional[str] = None, service_provider_name: Optional[str] = None): """ Contains ServiceProviderProperties in an ExpressRouteCircuit. :param int bandwidth_in_mbps: The BandwidthInMbps. :param str peering_location: The peering location. :param str service_provider_name: The serviceProviderName. """ if bandwidth_in_mbps is not None: pulumi.set(__self__, "bandwidth_in_mbps", bandwidth_in_mbps) if peering_location is not None: pulumi.set(__self__, "peering_location", peering_location) if service_provider_name is not None: pulumi.set(__self__, "service_provider_name", service_provider_name) @property @pulumi.getter(name="bandwidthInMbps") def bandwidth_in_mbps(self) -> Optional[int]: """ The BandwidthInMbps. """ return pulumi.get(self, "bandwidth_in_mbps") @property @pulumi.getter(name="peeringLocation") def peering_location(self) -> Optional[str]: """ The peering location. """ return pulumi.get(self, "peering_location") @property @pulumi.getter(name="serviceProviderName") def service_provider_name(self) -> Optional[str]: """ The serviceProviderName. """ return pulumi.get(self, "service_provider_name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ExpressRouteCircuitSkuResponse(dict): """ Contains SKU in an ExpressRouteCircuit. """ def __init__(__self__, *, family: Optional[str] = None, name: Optional[str] = None, tier: Optional[str] = None): """ Contains SKU in an ExpressRouteCircuit. :param str family: The family of the SKU. Possible values are: 'UnlimitedData' and 'MeteredData'. :param str name: The name of the SKU. :param str tier: The tier of the SKU. Possible values are 'Standard' and 'Premium'. """ if family is not None: pulumi.set(__self__, "family", family) if name is not None: pulumi.set(__self__, "name", name) if tier is not None: pulumi.set(__self__, "tier", tier) @property @pulumi.getter def family(self) -> Optional[str]: """ The family of the SKU. Possible values are: 'UnlimitedData' and 'MeteredData'. """ return pulumi.get(self, "family") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the SKU. """ return pulumi.get(self, "name") @property @pulumi.getter def tier(self) -> Optional[str]: """ The tier of the SKU. Possible values are 'Standard' and 'Premium'. """ return pulumi.get(self, "tier") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ExpressRouteCircuitStatsResponse(dict): """ Contains stats associated with the peering. """ def __init__(__self__, *, primarybytes_in: Optional[float] = None, primarybytes_out: Optional[float] = None, secondarybytes_in: Optional[float] = None, secondarybytes_out: Optional[float] = None): """ Contains stats associated with the peering. :param float primarybytes_in: Gets BytesIn of the peering. :param float primarybytes_out: Gets BytesOut of the peering. :param float secondarybytes_in: Gets BytesIn of the peering. :param float secondarybytes_out: Gets BytesOut of the peering. """ if primarybytes_in is not None: pulumi.set(__self__, "primarybytes_in", primarybytes_in) if primarybytes_out is not None: pulumi.set(__self__, "primarybytes_out", primarybytes_out) if secondarybytes_in is not None: pulumi.set(__self__, "secondarybytes_in", secondarybytes_in) if secondarybytes_out is not None: pulumi.set(__self__, "secondarybytes_out", secondarybytes_out) @property @pulumi.getter(name="primarybytesIn") def primarybytes_in(self) -> Optional[float]: """ Gets BytesIn of the peering. """ return pulumi.get(self, "primarybytes_in") @property @pulumi.getter(name="primarybytesOut") def primarybytes_out(self) -> Optional[float]: """ Gets BytesOut of the peering. """ return pulumi.get(self, "primarybytes_out") @property @pulumi.getter(name="secondarybytesIn") def secondarybytes_in(self) -> Optional[float]: """ Gets BytesIn of the peering. """ return pulumi.get(self, "secondarybytes_in") @property @pulumi.getter(name="secondarybytesOut") def secondarybytes_out(self) -> Optional[float]: """ Gets BytesOut of the peering. """ return pulumi.get(self, "secondarybytes_out") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class FrontendIPConfigurationResponse(dict): """ Frontend IP address of the load balancer. """ def __init__(__self__, *, inbound_nat_pools: Sequence['outputs.SubResourceResponse'], inbound_nat_rules: Sequence['outputs.SubResourceResponse'], load_balancing_rules: Sequence['outputs.SubResourceResponse'], outbound_nat_rules: Sequence['outputs.SubResourceResponse'], etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, private_ip_address: Optional[str] = None, private_ip_allocation_method: Optional[str] = None, provisioning_state: Optional[str] = None, public_ip_address: Optional['outputs.PublicIPAddressResponse'] = None, subnet: Optional['outputs.SubnetResponse'] = None): """ Frontend IP address of the load balancer. :param Sequence['SubResourceResponseArgs'] inbound_nat_pools: Read only. Inbound pools URIs that use this frontend IP. :param Sequence['SubResourceResponseArgs'] inbound_nat_rules: Read only. Inbound rules URIs that use this frontend IP. :param Sequence['SubResourceResponseArgs'] load_balancing_rules: Gets load balancing rules URIs that use this frontend IP. :param Sequence['SubResourceResponseArgs'] outbound_nat_rules: Read only. Outbound rules URIs that use this frontend IP. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param str private_ip_address: The private IP address of the IP configuration. :param str private_ip_allocation_method: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param str provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param 'PublicIPAddressResponseArgs' public_ip_address: The reference of the Public IP resource. :param 'SubnetResponseArgs' subnet: The reference of the subnet resource. """ pulumi.set(__self__, "inbound_nat_pools", inbound_nat_pools) pulumi.set(__self__, "inbound_nat_rules", inbound_nat_rules) pulumi.set(__self__, "load_balancing_rules", load_balancing_rules) pulumi.set(__self__, "outbound_nat_rules", outbound_nat_rules) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if private_ip_address is not None: pulumi.set(__self__, "private_ip_address", private_ip_address) if private_ip_allocation_method is not None: pulumi.set(__self__, "private_ip_allocation_method", private_ip_allocation_method) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if public_ip_address is not None: pulumi.set(__self__, "public_ip_address", public_ip_address) if subnet is not None: pulumi.set(__self__, "subnet", subnet) @property @pulumi.getter(name="inboundNatPools") def inbound_nat_pools(self) -> Sequence['outputs.SubResourceResponse']: """ Read only. Inbound pools URIs that use this frontend IP. """ return pulumi.get(self, "inbound_nat_pools") @property @pulumi.getter(name="inboundNatRules") def inbound_nat_rules(self) -> Sequence['outputs.SubResourceResponse']: """ Read only. Inbound rules URIs that use this frontend IP. """ return pulumi.get(self, "inbound_nat_rules") @property @pulumi.getter(name="loadBalancingRules") def load_balancing_rules(self) -> Sequence['outputs.SubResourceResponse']: """ Gets load balancing rules URIs that use this frontend IP. """ return pulumi.get(self, "load_balancing_rules") @property @pulumi.getter(name="outboundNatRules") def outbound_nat_rules(self) -> Sequence['outputs.SubResourceResponse']: """ Read only. Outbound rules URIs that use this frontend IP. """ return pulumi.get(self, "outbound_nat_rules") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="privateIPAddress") def private_ip_address(self) -> Optional[str]: """ The private IP address of the IP configuration. """ return pulumi.get(self, "private_ip_address") @property @pulumi.getter(name="privateIPAllocationMethod") def private_ip_allocation_method(self) -> Optional[str]: """ The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. """ return pulumi.get(self, "private_ip_allocation_method") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicIPAddress") def public_ip_address(self) -> Optional['outputs.PublicIPAddressResponse']: """ The reference of the Public IP resource. """ return pulumi.get(self, "public_ip_address") @property @pulumi.getter def subnet(self) -> Optional['outputs.SubnetResponse']: """ The reference of the subnet resource. """ return pulumi.get(self, "subnet") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GatewayRouteResponseResult(dict): def __init__(__self__, *, as_path: str, local_address: str, network: str, next_hop: str, origin: str, source_peer: str, weight: int): """ :param str as_path: The route's AS path sequence :param str local_address: The gateway's local address :param str network: The route's network prefix :param str next_hop: The route's next hop :param str origin: The source this route was learned from :param str source_peer: The peer this route was learned from :param int weight: The route's weight """ pulumi.set(__self__, "as_path", as_path) pulumi.set(__self__, "local_address", local_address) pulumi.set(__self__, "network", network) pulumi.set(__self__, "next_hop", next_hop) pulumi.set(__self__, "origin", origin) pulumi.set(__self__, "source_peer", source_peer) pulumi.set(__self__, "weight", weight) @property @pulumi.getter(name="asPath") def as_path(self) -> str: """ The route's AS path sequence """ return pulumi.get(self, "as_path") @property @pulumi.getter(name="localAddress") def local_address(self) -> str: """ The gateway's local address """ return pulumi.get(self, "local_address") @property @pulumi.getter def network(self) -> str: """ The route's network prefix """ return pulumi.get(self, "network") @property @pulumi.getter(name="nextHop") def next_hop(self) -> str: """ The route's next hop """ return pulumi.get(self, "next_hop") @property @pulumi.getter def origin(self) -> str: """ The source this route was learned from """ return pulumi.get(self, "origin") @property @pulumi.getter(name="sourcePeer") def source_peer(self) -> str: """ The peer this route was learned from """ return pulumi.get(self, "source_peer") @property @pulumi.getter def weight(self) -> int: """ The route's weight """ return pulumi.get(self, "weight") @pulumi.output_type class IPConfigurationResponse(dict): """ IPConfiguration """ def __init__(__self__, *, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, private_ip_address: Optional[str] = None, private_ip_allocation_method: Optional[str] = None, provisioning_state: Optional[str] = None, public_ip_address: Optional['outputs.PublicIPAddressResponse'] = None, subnet: Optional['outputs.SubnetResponse'] = None): """ IPConfiguration :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param str private_ip_address: The private IP address of the IP configuration. :param str private_ip_allocation_method: The private IP allocation method. Possible values are 'Static' and 'Dynamic'. :param str provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param 'PublicIPAddressResponseArgs' public_ip_address: The reference of the public IP resource. :param 'SubnetResponseArgs' subnet: The reference of the subnet resource. """ if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if private_ip_address is not None: pulumi.set(__self__, "private_ip_address", private_ip_address) if private_ip_allocation_method is not None: pulumi.set(__self__, "private_ip_allocation_method", private_ip_allocation_method) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if public_ip_address is not None: pulumi.set(__self__, "public_ip_address", public_ip_address) if subnet is not None: pulumi.set(__self__, "subnet", subnet) @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="privateIPAddress") def private_ip_address(self) -> Optional[str]: """ The private IP address of the IP configuration. """ return pulumi.get(self, "private_ip_address") @property @pulumi.getter(name="privateIPAllocationMethod") def private_ip_allocation_method(self) -> Optional[str]: """ The private IP allocation method. Possible values are 'Static' and 'Dynamic'. """ return pulumi.get(self, "private_ip_allocation_method") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicIPAddress") def public_ip_address(self) -> Optional['outputs.PublicIPAddressResponse']: """ The reference of the public IP resource. """ return pulumi.get(self, "public_ip_address") @property @pulumi.getter def subnet(self) -> Optional['outputs.SubnetResponse']: """ The reference of the subnet resource. """ return pulumi.get(self, "subnet") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class InboundNatPoolResponse(dict): """ Inbound NAT pool of the load balancer. """ def __init__(__self__, *, backend_port: int, frontend_port_range_end: int, frontend_port_range_start: int, protocol: str, etag: Optional[str] = None, frontend_ip_configuration: Optional['outputs.SubResourceResponse'] = None, id: Optional[str] = None, name: Optional[str] = None, provisioning_state: Optional[str] = None): """ Inbound NAT pool of the load balancer. :param int backend_port: The port used for internal connections on the endpoint. Acceptable values are between 1 and 65535. :param int frontend_port_range_end: The last port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65535. :param int frontend_port_range_start: The first port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65534. :param str protocol: The transport protocol for the endpoint. Possible values are: 'Udp' or 'Tcp'. :param str etag: A unique read-only string that changes whenever the resource is updated. :param 'SubResourceResponseArgs' frontend_ip_configuration: A reference to frontend IP addresses. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param str provisioning_state: Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ pulumi.set(__self__, "backend_port", backend_port) pulumi.set(__self__, "frontend_port_range_end", frontend_port_range_end) pulumi.set(__self__, "frontend_port_range_start", frontend_port_range_start) pulumi.set(__self__, "protocol", protocol) if etag is not None: pulumi.set(__self__, "etag", etag) if frontend_ip_configuration is not None: pulumi.set(__self__, "frontend_ip_configuration", frontend_ip_configuration) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="backendPort") def backend_port(self) -> int: """ The port used for internal connections on the endpoint. Acceptable values are between 1 and 65535. """ return pulumi.get(self, "backend_port") @property @pulumi.getter(name="frontendPortRangeEnd") def frontend_port_range_end(self) -> int: """ The last port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65535. """ return pulumi.get(self, "frontend_port_range_end") @property @pulumi.getter(name="frontendPortRangeStart") def frontend_port_range_start(self) -> int: """ The first port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65534. """ return pulumi.get(self, "frontend_port_range_start") @property @pulumi.getter def protocol(self) -> str: """ The transport protocol for the endpoint. Possible values are: 'Udp' or 'Tcp'. """ return pulumi.get(self, "protocol") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="frontendIPConfiguration") def frontend_ip_configuration(self) -> Optional['outputs.SubResourceResponse']: """ A reference to frontend IP addresses. """ return pulumi.get(self, "frontend_ip_configuration") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class InboundNatRuleResponse(dict): """ Inbound NAT rule of the load balancer. """ def __init__(__self__, *, backend_ip_configuration: 'outputs.NetworkInterfaceIPConfigurationResponse', backend_port: Optional[int] = None, enable_floating_ip: Optional[bool] = None, etag: Optional[str] = None, frontend_ip_configuration: Optional['outputs.SubResourceResponse'] = None, frontend_port: Optional[int] = None, id: Optional[str] = None, idle_timeout_in_minutes: Optional[int] = None, name: Optional[str] = None, protocol: Optional[str] = None, provisioning_state: Optional[str] = None): """ Inbound NAT rule of the load balancer. :param 'NetworkInterfaceIPConfigurationResponseArgs' backend_ip_configuration: A reference to a private IP address defined on a network interface of a VM. Traffic sent to the frontend port of each of the frontend IP configurations is forwarded to the backed IP. :param int backend_port: The port used for the internal endpoint. Acceptable values range from 1 to 65535. :param bool enable_floating_ip: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param str etag: A unique read-only string that changes whenever the resource is updated. :param 'SubResourceResponseArgs' frontend_ip_configuration: A reference to frontend IP addresses. :param int frontend_port: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. :param str id: Resource ID. :param int idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. :param str name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :param str protocol: The transport protocol for the endpoint. Possible values are: 'Udp' or 'Tcp' :param str provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ pulumi.set(__self__, "backend_ip_configuration", backend_ip_configuration) if backend_port is not None: pulumi.set(__self__, "backend_port", backend_port) if enable_floating_ip is not None: pulumi.set(__self__, "enable_floating_ip", enable_floating_ip) if etag is not None: pulumi.set(__self__, "etag", etag) if frontend_ip_configuration is not None: pulumi.set(__self__, "frontend_ip_configuration", frontend_ip_configuration) if frontend_port is not None: pulumi.set(__self__, "frontend_port", frontend_port) if id is not None: pulumi.set(__self__, "id", id) if idle_timeout_in_minutes is not None: pulumi.set(__self__, "idle_timeout_in_minutes", idle_timeout_in_minutes) if name is not None: pulumi.set(__self__, "name", name) if protocol is not None: pulumi.set(__self__, "protocol", protocol) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="backendIPConfiguration") def backend_ip_configuration(self) -> 'outputs.NetworkInterfaceIPConfigurationResponse': """ A reference to a private IP address defined on a network interface of a VM. Traffic sent to the frontend port of each of the frontend IP configurations is forwarded to the backed IP. """ return pulumi.get(self, "backend_ip_configuration") @property @pulumi.getter(name="backendPort") def backend_port(self) -> Optional[int]: """ The port used for the internal endpoint. Acceptable values range from 1 to 65535. """ return pulumi.get(self, "backend_port") @property @pulumi.getter(name="enableFloatingIP") def enable_floating_ip(self) -> Optional[bool]: """ Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. """ return pulumi.get(self, "enable_floating_ip") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="frontendIPConfiguration") def frontend_ip_configuration(self) -> Optional['outputs.SubResourceResponse']: """ A reference to frontend IP addresses. """ return pulumi.get(self, "frontend_ip_configuration") @property @pulumi.getter(name="frontendPort") def frontend_port(self) -> Optional[int]: """ The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. """ return pulumi.get(self, "frontend_port") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter(name="idleTimeoutInMinutes") def idle_timeout_in_minutes(self) -> Optional[int]: """ The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. """ return pulumi.get(self, "idle_timeout_in_minutes") @property @pulumi.getter def name(self) -> Optional[str]: """ Gets name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def protocol(self) -> Optional[str]: """ The transport protocol for the endpoint. Possible values are: 'Udp' or 'Tcp' """ return pulumi.get(self, "protocol") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class LoadBalancingRuleResponse(dict): """ A load balancing rule for a load balancer. """ def __init__(__self__, *, frontend_port: int, protocol: str, backend_address_pool: Optional['outputs.SubResourceResponse'] = None, backend_port: Optional[int] = None, enable_floating_ip: Optional[bool] = None, etag: Optional[str] = None, frontend_ip_configuration: Optional['outputs.SubResourceResponse'] = None, id: Optional[str] = None, idle_timeout_in_minutes: Optional[int] = None, load_distribution: Optional[str] = None, name: Optional[str] = None, probe: Optional['outputs.SubResourceResponse'] = None, provisioning_state: Optional[str] = None): """ A load balancing rule for a load balancer. :param int frontend_port: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 1 and 65534. :param str protocol: The transport protocol for the external endpoint. Possible values are 'Udp' or 'Tcp' :param 'SubResourceResponseArgs' backend_address_pool: A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param int backend_port: The port used for internal connections on the endpoint. Acceptable values are between 1 and 65535. :param bool enable_floating_ip: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param str etag: A unique read-only string that changes whenever the resource is updated. :param 'SubResourceResponseArgs' frontend_ip_configuration: A reference to frontend IP addresses. :param str id: Resource ID. :param int idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. :param str load_distribution: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param 'SubResourceResponseArgs' probe: The reference of the load balancer probe used by the load balancing rule. :param str provisioning_state: Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ pulumi.set(__self__, "frontend_port", frontend_port) pulumi.set(__self__, "protocol", protocol) if backend_address_pool is not None: pulumi.set(__self__, "backend_address_pool", backend_address_pool) if backend_port is not None: pulumi.set(__self__, "backend_port", backend_port) if enable_floating_ip is not None: pulumi.set(__self__, "enable_floating_ip", enable_floating_ip) if etag is not None: pulumi.set(__self__, "etag", etag) if frontend_ip_configuration is not None: pulumi.set(__self__, "frontend_ip_configuration", frontend_ip_configuration) if id is not None: pulumi.set(__self__, "id", id) if idle_timeout_in_minutes is not None: pulumi.set(__self__, "idle_timeout_in_minutes", idle_timeout_in_minutes) if load_distribution is not None: pulumi.set(__self__, "load_distribution", load_distribution) if name is not None: pulumi.set(__self__, "name", name) if probe is not None: pulumi.set(__self__, "probe", probe) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="frontendPort") def frontend_port(self) -> int: """ The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 1 and 65534. """ return pulumi.get(self, "frontend_port") @property @pulumi.getter def protocol(self) -> str: """ The transport protocol for the external endpoint. Possible values are 'Udp' or 'Tcp' """ return pulumi.get(self, "protocol") @property @pulumi.getter(name="backendAddressPool") def backend_address_pool(self) -> Optional['outputs.SubResourceResponse']: """ A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs. """ return pulumi.get(self, "backend_address_pool") @property @pulumi.getter(name="backendPort") def backend_port(self) -> Optional[int]: """ The port used for internal connections on the endpoint. Acceptable values are between 1 and 65535. """ return pulumi.get(self, "backend_port") @property @pulumi.getter(name="enableFloatingIP") def enable_floating_ip(self) -> Optional[bool]: """ Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. """ return pulumi.get(self, "enable_floating_ip") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="frontendIPConfiguration") def frontend_ip_configuration(self) -> Optional['outputs.SubResourceResponse']: """ A reference to frontend IP addresses. """ return pulumi.get(self, "frontend_ip_configuration") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter(name="idleTimeoutInMinutes") def idle_timeout_in_minutes(self) -> Optional[int]: """ The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. """ return pulumi.get(self, "idle_timeout_in_minutes") @property @pulumi.getter(name="loadDistribution") def load_distribution(self) -> Optional[str]: """ The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. """ return pulumi.get(self, "load_distribution") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def probe(self) -> Optional['outputs.SubResourceResponse']: """ The reference of the load balancer probe used by the load balancing rule. """ return pulumi.get(self, "probe") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class LocalNetworkGatewayResponse(dict): """ A common class for general resource information """ def __init__(__self__, *, local_network_address_space: 'outputs.AddressSpaceResponse', name: str, provisioning_state: str, type: str, bgp_settings: Optional['outputs.BgpSettingsResponse'] = None, etag: Optional[str] = None, gateway_ip_address: Optional[str] = None, id: Optional[str] = None, location: Optional[str] = None, resource_guid: Optional[str] = None, tags: Optional[Mapping[str, str]] = None): """ A common class for general resource information :param 'AddressSpaceResponseArgs' local_network_address_space: Local network site address space. :param str name: Resource name. :param str provisioning_state: The provisioning state of the LocalNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str type: Resource type. :param 'BgpSettingsResponseArgs' bgp_settings: Local network gateway's BGP speaker settings. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str gateway_ip_address: IP address of local network gateway. :param str id: Resource ID. :param str location: Resource location. :param str resource_guid: The resource GUID property of the LocalNetworkGateway resource. :param Mapping[str, str] tags: Resource tags. """ pulumi.set(__self__, "local_network_address_space", local_network_address_space) pulumi.set(__self__, "name", name) pulumi.set(__self__, "provisioning_state", provisioning_state) pulumi.set(__self__, "type", type) if bgp_settings is not None: pulumi.set(__self__, "bgp_settings", bgp_settings) if etag is not None: pulumi.set(__self__, "etag", etag) if gateway_ip_address is not None: pulumi.set(__self__, "gateway_ip_address", gateway_ip_address) if id is not None: pulumi.set(__self__, "id", id) if location is not None: pulumi.set(__self__, "location", location) if resource_guid is not None: pulumi.set(__self__, "resource_guid", resource_guid) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="localNetworkAddressSpace") def local_network_address_space(self) -> 'outputs.AddressSpaceResponse': """ Local network site address space. """ return pulumi.get(self, "local_network_address_space") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the LocalNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="bgpSettings") def bgp_settings(self) -> Optional['outputs.BgpSettingsResponse']: """ Local network gateway's BGP speaker settings. """ return pulumi.get(self, "bgp_settings") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="gatewayIpAddress") def gateway_ip_address(self) -> Optional[str]: """ IP address of local network gateway. """ return pulumi.get(self, "gateway_ip_address") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> Optional[str]: """ The resource GUID property of the LocalNetworkGateway resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class NetworkInterfaceDnsSettingsResponse(dict): """ DNS settings of a network interface. """ def __init__(__self__, *, applied_dns_servers: Optional[Sequence[str]] = None, dns_servers: Optional[Sequence[str]] = None, internal_dns_name_label: Optional[str] = None, internal_domain_name_suffix: Optional[str] = None, internal_fqdn: Optional[str] = None): """ DNS settings of a network interface. :param Sequence[str] applied_dns_servers: If the VM that uses this NIC is part of an Availability Set, then this list will have the union of all DNS servers from all NICs that are part of the Availability Set. This property is what is configured on each of those VMs. :param Sequence[str] dns_servers: List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dnsServers collection. :param str internal_dns_name_label: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. :param str internal_domain_name_suffix: Even if internalDnsNameLabel is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internalDomainNameSuffix. :param str internal_fqdn: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. """ if applied_dns_servers is not None: pulumi.set(__self__, "applied_dns_servers", applied_dns_servers) if dns_servers is not None: pulumi.set(__self__, "dns_servers", dns_servers) if internal_dns_name_label is not None: pulumi.set(__self__, "internal_dns_name_label", internal_dns_name_label) if internal_domain_name_suffix is not None: pulumi.set(__self__, "internal_domain_name_suffix", internal_domain_name_suffix) if internal_fqdn is not None: pulumi.set(__self__, "internal_fqdn", internal_fqdn) @property @pulumi.getter(name="appliedDnsServers") def applied_dns_servers(self) -> Optional[Sequence[str]]: """ If the VM that uses this NIC is part of an Availability Set, then this list will have the union of all DNS servers from all NICs that are part of the Availability Set. This property is what is configured on each of those VMs. """ return pulumi.get(self, "applied_dns_servers") @property @pulumi.getter(name="dnsServers") def dns_servers(self) -> Optional[Sequence[str]]: """ List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dnsServers collection. """ return pulumi.get(self, "dns_servers") @property @pulumi.getter(name="internalDnsNameLabel") def internal_dns_name_label(self) -> Optional[str]: """ Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. """ return pulumi.get(self, "internal_dns_name_label") @property @pulumi.getter(name="internalDomainNameSuffix") def internal_domain_name_suffix(self) -> Optional[str]: """ Even if internalDnsNameLabel is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internalDomainNameSuffix. """ return pulumi.get(self, "internal_domain_name_suffix") @property @pulumi.getter(name="internalFqdn") def internal_fqdn(self) -> Optional[str]: """ Fully qualified DNS name supporting internal communications between VMs in the same virtual network. """ return pulumi.get(self, "internal_fqdn") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class NetworkInterfaceIPConfigurationResponse(dict): """ IPConfiguration in a network interface. """ def __init__(__self__, *, application_gateway_backend_address_pools: Optional[Sequence['outputs.ApplicationGatewayBackendAddressPoolResponse']] = None, etag: Optional[str] = None, id: Optional[str] = None, load_balancer_backend_address_pools: Optional[Sequence['outputs.BackendAddressPoolResponse']] = None, load_balancer_inbound_nat_rules: Optional[Sequence['outputs.InboundNatRuleResponse']] = None, name: Optional[str] = None, primary: Optional[bool] = None, private_ip_address: Optional[str] = None, private_ip_address_version: Optional[str] = None, private_ip_allocation_method: Optional[str] = None, provisioning_state: Optional[str] = None, public_ip_address: Optional['outputs.PublicIPAddressResponse'] = None, subnet: Optional['outputs.SubnetResponse'] = None): """ IPConfiguration in a network interface. :param Sequence['ApplicationGatewayBackendAddressPoolResponseArgs'] application_gateway_backend_address_pools: The reference of ApplicationGatewayBackendAddressPool resource. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param Sequence['BackendAddressPoolResponseArgs'] load_balancer_backend_address_pools: The reference of LoadBalancerBackendAddressPool resource. :param Sequence['InboundNatRuleResponseArgs'] load_balancer_inbound_nat_rules: A list of references of LoadBalancerInboundNatRules. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param bool primary: Gets whether this is a primary customer address on the network interface. :param str private_ip_address_version: Available from Api-Version 2016-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. :param str private_ip_allocation_method: Defines how a private IP address is assigned. Possible values are: 'Static' and 'Dynamic'. :param 'PublicIPAddressResponseArgs' public_ip_address: Public IP address resource. :param 'SubnetResponseArgs' subnet: Subnet in a virtual network resource. """ if application_gateway_backend_address_pools is not None: pulumi.set(__self__, "application_gateway_backend_address_pools", application_gateway_backend_address_pools) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if load_balancer_backend_address_pools is not None: pulumi.set(__self__, "load_balancer_backend_address_pools", load_balancer_backend_address_pools) if load_balancer_inbound_nat_rules is not None: pulumi.set(__self__, "load_balancer_inbound_nat_rules", load_balancer_inbound_nat_rules) if name is not None: pulumi.set(__self__, "name", name) if primary is not None: pulumi.set(__self__, "primary", primary) if private_ip_address is not None: pulumi.set(__self__, "private_ip_address", private_ip_address) if private_ip_address_version is not None: pulumi.set(__self__, "private_ip_address_version", private_ip_address_version) if private_ip_allocation_method is not None: pulumi.set(__self__, "private_ip_allocation_method", private_ip_allocation_method) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if public_ip_address is not None: pulumi.set(__self__, "public_ip_address", public_ip_address) if subnet is not None: pulumi.set(__self__, "subnet", subnet) @property @pulumi.getter(name="applicationGatewayBackendAddressPools") def application_gateway_backend_address_pools(self) -> Optional[Sequence['outputs.ApplicationGatewayBackendAddressPoolResponse']]: """ The reference of ApplicationGatewayBackendAddressPool resource. """ return pulumi.get(self, "application_gateway_backend_address_pools") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter(name="loadBalancerBackendAddressPools") def load_balancer_backend_address_pools(self) -> Optional[Sequence['outputs.BackendAddressPoolResponse']]: """ The reference of LoadBalancerBackendAddressPool resource. """ return pulumi.get(self, "load_balancer_backend_address_pools") @property @pulumi.getter(name="loadBalancerInboundNatRules") def load_balancer_inbound_nat_rules(self) -> Optional[Sequence['outputs.InboundNatRuleResponse']]: """ A list of references of LoadBalancerInboundNatRules. """ return pulumi.get(self, "load_balancer_inbound_nat_rules") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def primary(self) -> Optional[bool]: """ Gets whether this is a primary customer address on the network interface. """ return pulumi.get(self, "primary") @property @pulumi.getter(name="privateIPAddress") def private_ip_address(self) -> Optional[str]: return pulumi.get(self, "private_ip_address") @property @pulumi.getter(name="privateIPAddressVersion") def private_ip_address_version(self) -> Optional[str]: """ Available from Api-Version 2016-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. """ return pulumi.get(self, "private_ip_address_version") @property @pulumi.getter(name="privateIPAllocationMethod") def private_ip_allocation_method(self) -> Optional[str]: """ Defines how a private IP address is assigned. Possible values are: 'Static' and 'Dynamic'. """ return pulumi.get(self, "private_ip_allocation_method") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicIPAddress") def public_ip_address(self) -> Optional['outputs.PublicIPAddressResponse']: """ Public IP address resource. """ return pulumi.get(self, "public_ip_address") @property @pulumi.getter def subnet(self) -> Optional['outputs.SubnetResponse']: """ Subnet in a virtual network resource. """ return pulumi.get(self, "subnet") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class NetworkInterfaceResponse(dict): """ A network interface in a resource group. """ def __init__(__self__, *, name: str, type: str, dns_settings: Optional['outputs.NetworkInterfaceDnsSettingsResponse'] = None, enable_accelerated_networking: Optional[bool] = None, enable_ip_forwarding: Optional[bool] = None, etag: Optional[str] = None, id: Optional[str] = None, ip_configurations: Optional[Sequence['outputs.NetworkInterfaceIPConfigurationResponse']] = None, location: Optional[str] = None, mac_address: Optional[str] = None, network_security_group: Optional['outputs.NetworkSecurityGroupResponse'] = None, primary: Optional[bool] = None, provisioning_state: Optional[str] = None, resource_guid: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, virtual_machine: Optional['outputs.SubResourceResponse'] = None): """ A network interface in a resource group. :param str name: Resource name. :param str type: Resource type. :param 'NetworkInterfaceDnsSettingsResponseArgs' dns_settings: The DNS settings in network interface. :param bool enable_accelerated_networking: If the network interface is accelerated networking enabled. :param bool enable_ip_forwarding: Indicates whether IP forwarding is enabled on this network interface. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param Sequence['NetworkInterfaceIPConfigurationResponseArgs'] ip_configurations: A list of IPConfigurations of the network interface. :param str location: Resource location. :param str mac_address: The MAC address of the network interface. :param 'NetworkSecurityGroupResponseArgs' network_security_group: The reference of the NetworkSecurityGroup resource. :param bool primary: Gets whether this is a primary network interface on a virtual machine. :param str provisioning_state: The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str resource_guid: The resource GUID property of the network interface resource. :param Mapping[str, str] tags: Resource tags. :param 'SubResourceResponseArgs' virtual_machine: The reference of a virtual machine. """ pulumi.set(__self__, "name", name) pulumi.set(__self__, "type", type) if dns_settings is not None: pulumi.set(__self__, "dns_settings", dns_settings) if enable_accelerated_networking is not None: pulumi.set(__self__, "enable_accelerated_networking", enable_accelerated_networking) if enable_ip_forwarding is not None: pulumi.set(__self__, "enable_ip_forwarding", enable_ip_forwarding) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if ip_configurations is not None: pulumi.set(__self__, "ip_configurations", ip_configurations) if location is not None: pulumi.set(__self__, "location", location) if mac_address is not None: pulumi.set(__self__, "mac_address", mac_address) if network_security_group is not None: pulumi.set(__self__, "network_security_group", network_security_group) if primary is not None: pulumi.set(__self__, "primary", primary) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if resource_guid is not None: pulumi.set(__self__, "resource_guid", resource_guid) if tags is not None: pulumi.set(__self__, "tags", tags) if virtual_machine is not None: pulumi.set(__self__, "virtual_machine", virtual_machine) @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="dnsSettings") def dns_settings(self) -> Optional['outputs.NetworkInterfaceDnsSettingsResponse']: """ The DNS settings in network interface. """ return pulumi.get(self, "dns_settings") @property @pulumi.getter(name="enableAcceleratedNetworking") def enable_accelerated_networking(self) -> Optional[bool]: """ If the network interface is accelerated networking enabled. """ return pulumi.get(self, "enable_accelerated_networking") @property @pulumi.getter(name="enableIPForwarding") def enable_ip_forwarding(self) -> Optional[bool]: """ Indicates whether IP forwarding is enabled on this network interface. """ return pulumi.get(self, "enable_ip_forwarding") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter(name="ipConfigurations") def ip_configurations(self) -> Optional[Sequence['outputs.NetworkInterfaceIPConfigurationResponse']]: """ A list of IPConfigurations of the network interface. """ return pulumi.get(self, "ip_configurations") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter(name="macAddress") def mac_address(self) -> Optional[str]: """ The MAC address of the network interface. """ return pulumi.get(self, "mac_address") @property @pulumi.getter(name="networkSecurityGroup") def network_security_group(self) -> Optional['outputs.NetworkSecurityGroupResponse']: """ The reference of the NetworkSecurityGroup resource. """ return pulumi.get(self, "network_security_group") @property @pulumi.getter def primary(self) -> Optional[bool]: """ Gets whether this is a primary network interface on a virtual machine. """ return pulumi.get(self, "primary") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> Optional[str]: """ The resource GUID property of the network interface resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter(name="virtualMachine") def virtual_machine(self) -> Optional['outputs.SubResourceResponse']: """ The reference of a virtual machine. """ return pulumi.get(self, "virtual_machine") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class NetworkSecurityGroupResponse(dict): """ NetworkSecurityGroup resource. """ def __init__(__self__, *, name: str, network_interfaces: Sequence['outputs.NetworkInterfaceResponse'], subnets: Sequence['outputs.SubnetResponse'], type: str, default_security_rules: Optional[Sequence['outputs.SecurityRuleResponse']] = None, etag: Optional[str] = None, id: Optional[str] = None, location: Optional[str] = None, provisioning_state: Optional[str] = None, resource_guid: Optional[str] = None, security_rules: Optional[Sequence['outputs.SecurityRuleResponse']] = None, tags: Optional[Mapping[str, str]] = None): """ NetworkSecurityGroup resource. :param str name: Resource name. :param Sequence['NetworkInterfaceResponseArgs'] network_interfaces: A collection of references to network interfaces. :param Sequence['SubnetResponseArgs'] subnets: A collection of references to subnets. :param str type: Resource type. :param Sequence['SecurityRuleResponseArgs'] default_security_rules: The default security rules of network security group. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str location: Resource location. :param str provisioning_state: The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str resource_guid: The resource GUID property of the network security group resource. :param Sequence['SecurityRuleResponseArgs'] security_rules: A collection of security rules of the network security group. :param Mapping[str, str] tags: Resource tags. """ pulumi.set(__self__, "name", name) pulumi.set(__self__, "network_interfaces", network_interfaces) pulumi.set(__self__, "subnets", subnets) pulumi.set(__self__, "type", type) if default_security_rules is not None: pulumi.set(__self__, "default_security_rules", default_security_rules) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if location is not None: pulumi.set(__self__, "location", location) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if resource_guid is not None: pulumi.set(__self__, "resource_guid", resource_guid) if security_rules is not None: pulumi.set(__self__, "security_rules", security_rules) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="networkInterfaces") def network_interfaces(self) -> Sequence['outputs.NetworkInterfaceResponse']: """ A collection of references to network interfaces. """ return pulumi.get(self, "network_interfaces") @property @pulumi.getter def subnets(self) -> Sequence['outputs.SubnetResponse']: """ A collection of references to subnets. """ return pulumi.get(self, "subnets") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="defaultSecurityRules") def default_security_rules(self) -> Optional[Sequence['outputs.SecurityRuleResponse']]: """ The default security rules of network security group. """ return pulumi.get(self, "default_security_rules") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> Optional[str]: """ The resource GUID property of the network security group resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter(name="securityRules") def security_rules(self) -> Optional[Sequence['outputs.SecurityRuleResponse']]: """ A collection of security rules of the network security group. """ return pulumi.get(self, "security_rules") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class OutboundNatRuleResponse(dict): """ Outbound NAT pool of the load balancer. """ def __init__(__self__, *, backend_address_pool: 'outputs.SubResourceResponse', allocated_outbound_ports: Optional[int] = None, etag: Optional[str] = None, frontend_ip_configurations: Optional[Sequence['outputs.SubResourceResponse']] = None, id: Optional[str] = None, name: Optional[str] = None, provisioning_state: Optional[str] = None): """ Outbound NAT pool of the load balancer. :param 'SubResourceResponseArgs' backend_address_pool: A reference to a pool of DIPs. Outbound traffic is randomly load balanced across IPs in the backend IPs. :param int allocated_outbound_ports: The number of outbound ports to be used for NAT. :param str etag: A unique read-only string that changes whenever the resource is updated. :param Sequence['SubResourceResponseArgs'] frontend_ip_configurations: The Frontend IP addresses of the load balancer. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param str provisioning_state: Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ pulumi.set(__self__, "backend_address_pool", backend_address_pool) if allocated_outbound_ports is not None: pulumi.set(__self__, "allocated_outbound_ports", allocated_outbound_ports) if etag is not None: pulumi.set(__self__, "etag", etag) if frontend_ip_configurations is not None: pulumi.set(__self__, "frontend_ip_configurations", frontend_ip_configurations) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="backendAddressPool") def backend_address_pool(self) -> 'outputs.SubResourceResponse': """ A reference to a pool of DIPs. Outbound traffic is randomly load balanced across IPs in the backend IPs. """ return pulumi.get(self, "backend_address_pool") @property @pulumi.getter(name="allocatedOutboundPorts") def allocated_outbound_ports(self) -> Optional[int]: """ The number of outbound ports to be used for NAT. """ return pulumi.get(self, "allocated_outbound_ports") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="frontendIPConfigurations") def frontend_ip_configurations(self) -> Optional[Sequence['outputs.SubResourceResponse']]: """ The Frontend IP addresses of the load balancer. """ return pulumi.get(self, "frontend_ip_configurations") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PacketCaptureFilterResponse(dict): """ Filter that is applied to packet capture request. Multiple filters can be applied. """ def __init__(__self__, *, local_ip_address: Optional[str] = None, local_port: Optional[str] = None, protocol: Optional[str] = None, remote_ip_address: Optional[str] = None, remote_port: Optional[str] = None): """ Filter that is applied to packet capture request. Multiple filters can be applied. :param str local_ip_address: Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. :param str local_port: Local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. :param str protocol: Protocol to be filtered on. :param str remote_ip_address: Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. :param str remote_port: Remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. """ if local_ip_address is not None: pulumi.set(__self__, "local_ip_address", local_ip_address) if local_port is not None: pulumi.set(__self__, "local_port", local_port) if protocol is None: protocol = 'Any' if protocol is not None: pulumi.set(__self__, "protocol", protocol) if remote_ip_address is not None: pulumi.set(__self__, "remote_ip_address", remote_ip_address) if remote_port is not None: pulumi.set(__self__, "remote_port", remote_port) @property @pulumi.getter(name="localIPAddress") def local_ip_address(self) -> Optional[str]: """ Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. """ return pulumi.get(self, "local_ip_address") @property @pulumi.getter(name="localPort") def local_port(self) -> Optional[str]: """ Local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. """ return pulumi.get(self, "local_port") @property @pulumi.getter def protocol(self) -> Optional[str]: """ Protocol to be filtered on. """ return pulumi.get(self, "protocol") @property @pulumi.getter(name="remoteIPAddress") def remote_ip_address(self) -> Optional[str]: """ Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. """ return pulumi.get(self, "remote_ip_address") @property @pulumi.getter(name="remotePort") def remote_port(self) -> Optional[str]: """ Remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. """ return pulumi.get(self, "remote_port") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PacketCaptureStorageLocationResponse(dict): """ Describes the storage location for a packet capture session. """ def __init__(__self__, *, file_path: Optional[str] = None, storage_id: Optional[str] = None, storage_path: Optional[str] = None): """ Describes the storage location for a packet capture session. :param str file_path: A valid local path on the targeting VM. Must include the name of the capture file (*.cap). For linux virtual machine it must start with /var/captures. Required if no storage ID is provided, otherwise optional. :param str storage_id: The ID of the storage account to save the packet capture session. Required if no local file path is provided. :param str storage_path: The URI of the storage path to save the packet capture. Must be a well-formed URI describing the location to save the packet capture. """ if file_path is not None: pulumi.set(__self__, "file_path", file_path) if storage_id is not None: pulumi.set(__self__, "storage_id", storage_id) if storage_path is not None: pulumi.set(__self__, "storage_path", storage_path) @property @pulumi.getter(name="filePath") def file_path(self) -> Optional[str]: """ A valid local path on the targeting VM. Must include the name of the capture file (*.cap). For linux virtual machine it must start with /var/captures. Required if no storage ID is provided, otherwise optional. """ return pulumi.get(self, "file_path") @property @pulumi.getter(name="storageId") def storage_id(self) -> Optional[str]: """ The ID of the storage account to save the packet capture session. Required if no local file path is provided. """ return pulumi.get(self, "storage_id") @property @pulumi.getter(name="storagePath") def storage_path(self) -> Optional[str]: """ The URI of the storage path to save the packet capture. Must be a well-formed URI describing the location to save the packet capture. """ return pulumi.get(self, "storage_path") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ProbeResponse(dict): """ A load balancer probe. """ def __init__(__self__, *, load_balancing_rules: Sequence['outputs.SubResourceResponse'], port: int, protocol: str, etag: Optional[str] = None, id: Optional[str] = None, interval_in_seconds: Optional[int] = None, name: Optional[str] = None, number_of_probes: Optional[int] = None, provisioning_state: Optional[str] = None, request_path: Optional[str] = None): """ A load balancer probe. :param Sequence['SubResourceResponseArgs'] load_balancing_rules: The load balancer rules that use this probe. :param int port: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. :param str protocol: The protocol of the end point. Possible values are: 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specifies URI is required for the probe to be successful. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param int interval_in_seconds: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. :param str name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :param int number_of_probes: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. :param str provisioning_state: Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str request_path: The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is not allowed. There is no default value. """ pulumi.set(__self__, "load_balancing_rules", load_balancing_rules) pulumi.set(__self__, "port", port) pulumi.set(__self__, "protocol", protocol) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if interval_in_seconds is not None: pulumi.set(__self__, "interval_in_seconds", interval_in_seconds) if name is not None: pulumi.set(__self__, "name", name) if number_of_probes is not None: pulumi.set(__self__, "number_of_probes", number_of_probes) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if request_path is not None: pulumi.set(__self__, "request_path", request_path) @property @pulumi.getter(name="loadBalancingRules") def load_balancing_rules(self) -> Sequence['outputs.SubResourceResponse']: """ The load balancer rules that use this probe. """ return pulumi.get(self, "load_balancing_rules") @property @pulumi.getter def port(self) -> int: """ The port for communicating the probe. Possible values range from 1 to 65535, inclusive. """ return pulumi.get(self, "port") @property @pulumi.getter def protocol(self) -> str: """ The protocol of the end point. Possible values are: 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specifies URI is required for the probe to be successful. """ return pulumi.get(self, "protocol") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter(name="intervalInSeconds") def interval_in_seconds(self) -> Optional[int]: """ The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. """ return pulumi.get(self, "interval_in_seconds") @property @pulumi.getter def name(self) -> Optional[str]: """ Gets name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="numberOfProbes") def number_of_probes(self) -> Optional[int]: """ The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. """ return pulumi.get(self, "number_of_probes") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Gets the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="requestPath") def request_path(self) -> Optional[str]: """ The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is not allowed. There is no default value. """ return pulumi.get(self, "request_path") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PublicIPAddressDnsSettingsResponse(dict): """ Contains FQDN of the DNS record associated with the public IP address """ def __init__(__self__, *, domain_name_label: Optional[str] = None, fqdn: Optional[str] = None, reverse_fqdn: Optional[str] = None): """ Contains FQDN of the DNS record associated with the public IP address :param str domain_name_label: Gets or sets the Domain name label.The concatenation of the domain name label and the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. :param str fqdn: Gets the FQDN, Fully qualified domain name of the A DNS record associated with the public IP. This is the concatenation of the domainNameLabel and the regionalized DNS zone. :param str reverse_fqdn: Gets or Sets the Reverse FQDN. A user-visible, fully qualified domain name that resolves to this public IP address. If the reverseFqdn is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. """ if domain_name_label is not None: pulumi.set(__self__, "domain_name_label", domain_name_label) if fqdn is not None: pulumi.set(__self__, "fqdn", fqdn) if reverse_fqdn is not None: pulumi.set(__self__, "reverse_fqdn", reverse_fqdn) @property @pulumi.getter(name="domainNameLabel") def domain_name_label(self) -> Optional[str]: """ Gets or sets the Domain name label.The concatenation of the domain name label and the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. """ return pulumi.get(self, "domain_name_label") @property @pulumi.getter def fqdn(self) -> Optional[str]: """ Gets the FQDN, Fully qualified domain name of the A DNS record associated with the public IP. This is the concatenation of the domainNameLabel and the regionalized DNS zone. """ return pulumi.get(self, "fqdn") @property @pulumi.getter(name="reverseFqdn") def reverse_fqdn(self) -> Optional[str]: """ Gets or Sets the Reverse FQDN. A user-visible, fully qualified domain name that resolves to this public IP address. If the reverseFqdn is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. """ return pulumi.get(self, "reverse_fqdn") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PublicIPAddressResponse(dict): """ Public IP address resource. """ def __init__(__self__, *, ip_configuration: 'outputs.IPConfigurationResponse', name: str, type: str, dns_settings: Optional['outputs.PublicIPAddressDnsSettingsResponse'] = None, etag: Optional[str] = None, id: Optional[str] = None, idle_timeout_in_minutes: Optional[int] = None, ip_address: Optional[str] = None, location: Optional[str] = None, provisioning_state: Optional[str] = None, public_ip_address_version: Optional[str] = None, public_ip_allocation_method: Optional[str] = None, resource_guid: Optional[str] = None, tags: Optional[Mapping[str, str]] = None): """ Public IP address resource. :param 'IPConfigurationResponseArgs' ip_configuration: IPConfiguration :param str name: Resource name. :param str type: Resource type. :param 'PublicIPAddressDnsSettingsResponseArgs' dns_settings: The FQDN of the DNS record associated with the public IP address. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param int idle_timeout_in_minutes: The idle timeout of the public IP address. :param str location: Resource location. :param str provisioning_state: The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param str public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param str resource_guid: The resource GUID property of the public IP resource. :param Mapping[str, str] tags: Resource tags. """ pulumi.set(__self__, "ip_configuration", ip_configuration) pulumi.set(__self__, "name", name) pulumi.set(__self__, "type", type) if dns_settings is not None: pulumi.set(__self__, "dns_settings", dns_settings) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if idle_timeout_in_minutes is not None: pulumi.set(__self__, "idle_timeout_in_minutes", idle_timeout_in_minutes) if ip_address is not None: pulumi.set(__self__, "ip_address", ip_address) if location is not None: pulumi.set(__self__, "location", location) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if public_ip_address_version is not None: pulumi.set(__self__, "public_ip_address_version", public_ip_address_version) if public_ip_allocation_method is not None: pulumi.set(__self__, "public_ip_allocation_method", public_ip_allocation_method) if resource_guid is not None: pulumi.set(__self__, "resource_guid", resource_guid) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="ipConfiguration") def ip_configuration(self) -> 'outputs.IPConfigurationResponse': """ IPConfiguration """ return pulumi.get(self, "ip_configuration") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="dnsSettings") def dns_settings(self) -> Optional['outputs.PublicIPAddressDnsSettingsResponse']: """ The FQDN of the DNS record associated with the public IP address. """ return pulumi.get(self, "dns_settings") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter(name="idleTimeoutInMinutes") def idle_timeout_in_minutes(self) -> Optional[int]: """ The idle timeout of the public IP address. """ return pulumi.get(self, "idle_timeout_in_minutes") @property @pulumi.getter(name="ipAddress") def ip_address(self) -> Optional[str]: return pulumi.get(self, "ip_address") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicIPAddressVersion") def public_ip_address_version(self) -> Optional[str]: """ The public IP address version. Possible values are: 'IPv4' and 'IPv6'. """ return pulumi.get(self, "public_ip_address_version") @property @pulumi.getter(name="publicIPAllocationMethod") def public_ip_allocation_method(self) -> Optional[str]: """ The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. """ return pulumi.get(self, "public_ip_allocation_method") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> Optional[str]: """ The resource GUID property of the public IP resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ResourceNavigationLinkResponse(dict): """ ResourceNavigationLink resource. """ def __init__(__self__, *, etag: str, provisioning_state: str, id: Optional[str] = None, link: Optional[str] = None, linked_resource_type: Optional[str] = None, name: Optional[str] = None): """ ResourceNavigationLink resource. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str provisioning_state: Provisioning state of the ResourceNavigationLink resource. :param str id: Resource ID. :param str link: Link to the external resource :param str linked_resource_type: Resource type of the linked resource. :param str name: Name of the resource that is unique within a resource group. This name can be used to access the resource. """ pulumi.set(__self__, "etag", etag) pulumi.set(__self__, "provisioning_state", provisioning_state) if id is not None: pulumi.set(__self__, "id", id) if link is not None: pulumi.set(__self__, "link", link) if linked_resource_type is not None: pulumi.set(__self__, "linked_resource_type", linked_resource_type) if name is not None: pulumi.set(__self__, "name", name) @property @pulumi.getter def etag(self) -> str: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ Provisioning state of the ResourceNavigationLink resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def link(self) -> Optional[str]: """ Link to the external resource """ return pulumi.get(self, "link") @property @pulumi.getter(name="linkedResourceType") def linked_resource_type(self) -> Optional[str]: """ Resource type of the linked resource. """ return pulumi.get(self, "linked_resource_type") @property @pulumi.getter def name(self) -> Optional[str]: """ Name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class RouteResponse(dict): """ Route resource """ def __init__(__self__, *, next_hop_type: str, address_prefix: Optional[str] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, next_hop_ip_address: Optional[str] = None, provisioning_state: Optional[str] = None): """ Route resource :param str next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None' :param str address_prefix: The destination CIDR to which the route applies. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param str next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. :param str provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ pulumi.set(__self__, "next_hop_type", next_hop_type) if address_prefix is not None: pulumi.set(__self__, "address_prefix", address_prefix) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if next_hop_ip_address is not None: pulumi.set(__self__, "next_hop_ip_address", next_hop_ip_address) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) @property @pulumi.getter(name="nextHopType") def next_hop_type(self) -> str: """ The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None' """ return pulumi.get(self, "next_hop_type") @property @pulumi.getter(name="addressPrefix") def address_prefix(self) -> Optional[str]: """ The destination CIDR to which the route applies. """ return pulumi.get(self, "address_prefix") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="nextHopIpAddress") def next_hop_ip_address(self) -> Optional[str]: """ The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. """ return pulumi.get(self, "next_hop_ip_address") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class RouteTableResponse(dict): """ Route table resource. """ def __init__(__self__, *, name: str, subnets: Sequence['outputs.SubnetResponse'], type: str, etag: Optional[str] = None, id: Optional[str] = None, location: Optional[str] = None, provisioning_state: Optional[str] = None, routes: Optional[Sequence['outputs.RouteResponse']] = None, tags: Optional[Mapping[str, str]] = None): """ Route table resource. :param str name: Resource name. :param Sequence['SubnetResponseArgs'] subnets: A collection of references to subnets. :param str type: Resource type. :param str etag: Gets a unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str location: Resource location. :param str provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param Sequence['RouteResponseArgs'] routes: Collection of routes contained within a route table. :param Mapping[str, str] tags: Resource tags. """ pulumi.set(__self__, "name", name) pulumi.set(__self__, "subnets", subnets) pulumi.set(__self__, "type", type) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if location is not None: pulumi.set(__self__, "location", location) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if routes is not None: pulumi.set(__self__, "routes", routes) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter def subnets(self) -> Sequence['outputs.SubnetResponse']: """ A collection of references to subnets. """ return pulumi.get(self, "subnets") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter def etag(self) -> Optional[str]: """ Gets a unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def routes(self) -> Optional[Sequence['outputs.RouteResponse']]: """ Collection of routes contained within a route table. """ return pulumi.get(self, "routes") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SecurityRuleResponse(dict): """ Network security rule. """ def __init__(__self__, *, access: str, destination_address_prefix: str, direction: str, protocol: str, source_address_prefix: str, description: Optional[str] = None, destination_port_range: Optional[str] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, priority: Optional[int] = None, provisioning_state: Optional[str] = None, source_port_range: Optional[str] = None): """ Network security rule. :param str access: The network traffic is allowed or denied. Possible values are: 'Allow' and 'Deny'. :param str destination_address_prefix: The destination address prefix. CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. :param str direction: The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. Possible values are: 'Inbound' and 'Outbound'. :param str protocol: Network protocol this rule applies to. Possible values are 'Tcp', 'Udp', and '*'. :param str source_address_prefix: The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param str description: A description for this rule. Restricted to 140 chars. :param str destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param int priority: The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. :param str provisioning_state: The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str source_port_range: The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. """ pulumi.set(__self__, "access", access) pulumi.set(__self__, "destination_address_prefix", destination_address_prefix) pulumi.set(__self__, "direction", direction) pulumi.set(__self__, "protocol", protocol) pulumi.set(__self__, "source_address_prefix", source_address_prefix) if description is not None: pulumi.set(__self__, "description", description) if destination_port_range is not None: pulumi.set(__self__, "destination_port_range", destination_port_range) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if priority is not None: pulumi.set(__self__, "priority", priority) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if source_port_range is not None: pulumi.set(__self__, "source_port_range", source_port_range) @property @pulumi.getter def access(self) -> str: """ The network traffic is allowed or denied. Possible values are: 'Allow' and 'Deny'. """ return pulumi.get(self, "access") @property @pulumi.getter(name="destinationAddressPrefix") def destination_address_prefix(self) -> str: """ The destination address prefix. CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. """ return pulumi.get(self, "destination_address_prefix") @property @pulumi.getter def direction(self) -> str: """ The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. Possible values are: 'Inbound' and 'Outbound'. """ return pulumi.get(self, "direction") @property @pulumi.getter def protocol(self) -> str: """ Network protocol this rule applies to. Possible values are 'Tcp', 'Udp', and '*'. """ return pulumi.get(self, "protocol") @property @pulumi.getter(name="sourceAddressPrefix") def source_address_prefix(self) -> str: """ The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. """ return pulumi.get(self, "source_address_prefix") @property @pulumi.getter def description(self) -> Optional[str]: """ A description for this rule. Restricted to 140 chars. """ return pulumi.get(self, "description") @property @pulumi.getter(name="destinationPortRange") def destination_port_range(self) -> Optional[str]: """ The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. """ return pulumi.get(self, "destination_port_range") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def priority(self) -> Optional[int]: """ The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. """ return pulumi.get(self, "priority") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="sourcePortRange") def source_port_range(self) -> Optional[str]: """ The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. """ return pulumi.get(self, "source_port_range") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SubResourceResponse(dict): def __init__(__self__, *, id: Optional[str] = None): """ :param str id: Resource ID. """ if id is not None: pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SubnetResponse(dict): """ Subnet in a virtual network resource. """ def __init__(__self__, *, ip_configurations: Sequence['outputs.IPConfigurationResponse'], address_prefix: Optional[str] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, network_security_group: Optional['outputs.NetworkSecurityGroupResponse'] = None, provisioning_state: Optional[str] = None, resource_navigation_links: Optional[Sequence['outputs.ResourceNavigationLinkResponse']] = None, route_table: Optional['outputs.RouteTableResponse'] = None): """ Subnet in a virtual network resource. :param Sequence['IPConfigurationResponseArgs'] ip_configurations: Gets an array of references to the network interface IP configurations using subnet. :param str address_prefix: The address prefix for the subnet. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param 'NetworkSecurityGroupResponseArgs' network_security_group: The reference of the NetworkSecurityGroup resource. :param str provisioning_state: The provisioning state of the resource. :param Sequence['ResourceNavigationLinkResponseArgs'] resource_navigation_links: Gets an array of references to the external resources using subnet. :param 'RouteTableResponseArgs' route_table: The reference of the RouteTable resource. """ pulumi.set(__self__, "ip_configurations", ip_configurations) if address_prefix is not None: pulumi.set(__self__, "address_prefix", address_prefix) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if network_security_group is not None: pulumi.set(__self__, "network_security_group", network_security_group) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if resource_navigation_links is not None: pulumi.set(__self__, "resource_navigation_links", resource_navigation_links) if route_table is not None: pulumi.set(__self__, "route_table", route_table) @property @pulumi.getter(name="ipConfigurations") def ip_configurations(self) -> Sequence['outputs.IPConfigurationResponse']: """ Gets an array of references to the network interface IP configurations using subnet. """ return pulumi.get(self, "ip_configurations") @property @pulumi.getter(name="addressPrefix") def address_prefix(self) -> Optional[str]: """ The address prefix for the subnet. """ return pulumi.get(self, "address_prefix") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="networkSecurityGroup") def network_security_group(self) -> Optional['outputs.NetworkSecurityGroupResponse']: """ The reference of the NetworkSecurityGroup resource. """ return pulumi.get(self, "network_security_group") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceNavigationLinks") def resource_navigation_links(self) -> Optional[Sequence['outputs.ResourceNavigationLinkResponse']]: """ Gets an array of references to the external resources using subnet. """ return pulumi.get(self, "resource_navigation_links") @property @pulumi.getter(name="routeTable") def route_table(self) -> Optional['outputs.RouteTableResponse']: """ The reference of the RouteTable resource. """ return pulumi.get(self, "route_table") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class TunnelConnectionHealthResponse(dict): """ VirtualNetworkGatewayConnection properties """ def __init__(__self__, *, connection_status: str, egress_bytes_transferred: float, ingress_bytes_transferred: float, last_connection_established_utc_time: str, tunnel: str): """ VirtualNetworkGatewayConnection properties :param str connection_status: Virtual network Gateway connection status :param float egress_bytes_transferred: The Egress Bytes Transferred in this connection :param float ingress_bytes_transferred: The Ingress Bytes Transferred in this connection :param str last_connection_established_utc_time: The time at which connection was established in Utc format. :param str tunnel: Tunnel name. """ pulumi.set(__self__, "connection_status", connection_status) pulumi.set(__self__, "egress_bytes_transferred", egress_bytes_transferred) pulumi.set(__self__, "ingress_bytes_transferred", ingress_bytes_transferred) pulumi.set(__self__, "last_connection_established_utc_time", last_connection_established_utc_time) pulumi.set(__self__, "tunnel", tunnel) @property @pulumi.getter(name="connectionStatus") def connection_status(self) -> str: """ Virtual network Gateway connection status """ return pulumi.get(self, "connection_status") @property @pulumi.getter(name="egressBytesTransferred") def egress_bytes_transferred(self) -> float: """ The Egress Bytes Transferred in this connection """ return pulumi.get(self, "egress_bytes_transferred") @property @pulumi.getter(name="ingressBytesTransferred") def ingress_bytes_transferred(self) -> float: """ The Ingress Bytes Transferred in this connection """ return pulumi.get(self, "ingress_bytes_transferred") @property @pulumi.getter(name="lastConnectionEstablishedUtcTime") def last_connection_established_utc_time(self) -> str: """ The time at which connection was established in Utc format. """ return pulumi.get(self, "last_connection_established_utc_time") @property @pulumi.getter def tunnel(self) -> str: """ Tunnel name. """ return pulumi.get(self, "tunnel") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class VirtualNetworkGatewayIPConfigurationResponse(dict): """ IP configuration for virtual network gateway """ def __init__(__self__, *, provisioning_state: str, public_ip_address: 'outputs.SubResourceResponse', subnet: 'outputs.SubResourceResponse', etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, private_ip_allocation_method: Optional[str] = None): """ IP configuration for virtual network gateway :param str provisioning_state: The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param 'SubResourceResponseArgs' public_ip_address: The reference of the public IP resource. :param 'SubResourceResponseArgs' subnet: The reference of the subnet resource. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param str private_ip_allocation_method: The private IP allocation method. Possible values are: 'Static' and 'Dynamic'. """ pulumi.set(__self__, "provisioning_state", provisioning_state) pulumi.set(__self__, "public_ip_address", public_ip_address) pulumi.set(__self__, "subnet", subnet) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if private_ip_allocation_method is not None: pulumi.set(__self__, "private_ip_allocation_method", private_ip_allocation_method) @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicIPAddress") def public_ip_address(self) -> 'outputs.SubResourceResponse': """ The reference of the public IP resource. """ return pulumi.get(self, "public_ip_address") @property @pulumi.getter def subnet(self) -> 'outputs.SubResourceResponse': """ The reference of the subnet resource. """ return pulumi.get(self, "subnet") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="privateIPAllocationMethod") def private_ip_allocation_method(self) -> Optional[str]: """ The private IP allocation method. Possible values are: 'Static' and 'Dynamic'. """ return pulumi.get(self, "private_ip_allocation_method") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class VirtualNetworkGatewayResponse(dict): """ A common class for general resource information """ def __init__(__self__, *, gateway_type: str, ip_configurations: Sequence['outputs.VirtualNetworkGatewayIPConfigurationResponse'], name: str, provisioning_state: str, type: str, vpn_type: str, active_active: Optional[bool] = None, bgp_settings: Optional['outputs.BgpSettingsResponse'] = None, enable_bgp: Optional[bool] = None, etag: Optional[str] = None, gateway_default_site: Optional['outputs.SubResourceResponse'] = None, id: Optional[str] = None, location: Optional[str] = None, resource_guid: Optional[str] = None, sku: Optional['outputs.VirtualNetworkGatewaySkuResponse'] = None, tags: Optional[Mapping[str, str]] = None, vpn_client_configuration: Optional['outputs.VpnClientConfigurationResponse'] = None): """ A common class for general resource information :param str gateway_type: The type of this virtual network gateway. Possible values are: 'Vpn' and 'ExpressRoute'. :param Sequence['VirtualNetworkGatewayIPConfigurationResponseArgs'] ip_configurations: IP configurations for virtual network gateway. :param str name: Resource name. :param str provisioning_state: The provisioning state of the VirtualNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str type: Resource type. :param str vpn_type: The type of this virtual network gateway. Possible values are: 'PolicyBased' and 'RouteBased'. :param bool active_active: ActiveActive flag :param 'BgpSettingsResponseArgs' bgp_settings: Virtual network gateway's BGP speaker settings. :param bool enable_bgp: Whether BGP is enabled for this virtual network gateway or not. :param str etag: Gets a unique read-only string that changes whenever the resource is updated. :param 'SubResourceResponseArgs' gateway_default_site: The reference of the LocalNetworkGateway resource which represents local network site having default routes. Assign Null value in case of removing existing default site setting. :param str id: Resource ID. :param str location: Resource location. :param str resource_guid: The resource GUID property of the VirtualNetworkGateway resource. :param 'VirtualNetworkGatewaySkuResponseArgs' sku: The reference of the VirtualNetworkGatewaySku resource which represents the SKU selected for Virtual network gateway. :param Mapping[str, str] tags: Resource tags. :param 'VpnClientConfigurationResponseArgs' vpn_client_configuration: The reference of the VpnClientConfiguration resource which represents the P2S VpnClient configurations. """ pulumi.set(__self__, "gateway_type", gateway_type) pulumi.set(__self__, "ip_configurations", ip_configurations) pulumi.set(__self__, "name", name) pulumi.set(__self__, "provisioning_state", provisioning_state) pulumi.set(__self__, "type", type) pulumi.set(__self__, "vpn_type", vpn_type) if active_active is not None: pulumi.set(__self__, "active_active", active_active) if bgp_settings is not None: pulumi.set(__self__, "bgp_settings", bgp_settings) if enable_bgp is not None: pulumi.set(__self__, "enable_bgp", enable_bgp) if etag is not None: pulumi.set(__self__, "etag", etag) if gateway_default_site is not None: pulumi.set(__self__, "gateway_default_site", gateway_default_site) if id is not None: pulumi.set(__self__, "id", id) if location is not None: pulumi.set(__self__, "location", location) if resource_guid is not None: pulumi.set(__self__, "resource_guid", resource_guid) if sku is not None: pulumi.set(__self__, "sku", sku) if tags is not None: pulumi.set(__self__, "tags", tags) if vpn_client_configuration is not None: pulumi.set(__self__, "vpn_client_configuration", vpn_client_configuration) @property @pulumi.getter(name="gatewayType") def gateway_type(self) -> str: """ The type of this virtual network gateway. Possible values are: 'Vpn' and 'ExpressRoute'. """ return pulumi.get(self, "gateway_type") @property @pulumi.getter(name="ipConfigurations") def ip_configurations(self) -> Sequence['outputs.VirtualNetworkGatewayIPConfigurationResponse']: """ IP configurations for virtual network gateway. """ return pulumi.get(self, "ip_configurations") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the VirtualNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="vpnType") def vpn_type(self) -> str: """ The type of this virtual network gateway. Possible values are: 'PolicyBased' and 'RouteBased'. """ return pulumi.get(self, "vpn_type") @property @pulumi.getter(name="activeActive") def active_active(self) -> Optional[bool]: """ ActiveActive flag """ return pulumi.get(self, "active_active") @property @pulumi.getter(name="bgpSettings") def bgp_settings(self) -> Optional['outputs.BgpSettingsResponse']: """ Virtual network gateway's BGP speaker settings. """ return pulumi.get(self, "bgp_settings") @property @pulumi.getter(name="enableBgp") def enable_bgp(self) -> Optional[bool]: """ Whether BGP is enabled for this virtual network gateway or not. """ return pulumi.get(self, "enable_bgp") @property @pulumi.getter def etag(self) -> Optional[str]: """ Gets a unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="gatewayDefaultSite") def gateway_default_site(self) -> Optional['outputs.SubResourceResponse']: """ The reference of the LocalNetworkGateway resource which represents local network site having default routes. Assign Null value in case of removing existing default site setting. """ return pulumi.get(self, "gateway_default_site") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def location(self) -> Optional[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> Optional[str]: """ The resource GUID property of the VirtualNetworkGateway resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter def sku(self) -> Optional['outputs.VirtualNetworkGatewaySkuResponse']: """ The reference of the VirtualNetworkGatewaySku resource which represents the SKU selected for Virtual network gateway. """ return pulumi.get(self, "sku") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter(name="vpnClientConfiguration") def vpn_client_configuration(self) -> Optional['outputs.VpnClientConfigurationResponse']: """ The reference of the VpnClientConfiguration resource which represents the P2S VpnClient configurations. """ return pulumi.get(self, "vpn_client_configuration") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class VirtualNetworkGatewaySkuResponse(dict): """ VirtualNetworkGatewaySku details """ def __init__(__self__, *, name: str, tier: str, capacity: Optional[int] = None): """ VirtualNetworkGatewaySku details :param str name: Gateway SKU name. Possible values are: 'Basic', 'HighPerformance','Standard', and 'UltraPerformance'. :param str tier: Gateway SKU tier. Possible values are: 'Basic', 'HighPerformance','Standard', and 'UltraPerformance'. :param int capacity: The capacity. """ pulumi.set(__self__, "name", name) pulumi.set(__self__, "tier", tier) if capacity is not None: pulumi.set(__self__, "capacity", capacity) @property @pulumi.getter def name(self) -> str: """ Gateway SKU name. Possible values are: 'Basic', 'HighPerformance','Standard', and 'UltraPerformance'. """ return pulumi.get(self, "name") @property @pulumi.getter def tier(self) -> str: """ Gateway SKU tier. Possible values are: 'Basic', 'HighPerformance','Standard', and 'UltraPerformance'. """ return pulumi.get(self, "tier") @property @pulumi.getter def capacity(self) -> Optional[int]: """ The capacity. """ return pulumi.get(self, "capacity") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class VirtualNetworkPeeringResponse(dict): """ Peerings in a virtual network resource. """ def __init__(__self__, *, allow_forwarded_traffic: Optional[bool] = None, allow_gateway_transit: Optional[bool] = None, allow_virtual_network_access: Optional[bool] = None, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, peering_state: Optional[str] = None, provisioning_state: Optional[str] = None, remote_virtual_network: Optional['outputs.SubResourceResponse'] = None, use_remote_gateways: Optional[bool] = None): """ Peerings in a virtual network resource. :param bool allow_forwarded_traffic: Whether the forwarded traffic from the VMs in the remote virtual network will be allowed/disallowed. :param bool allow_gateway_transit: If gateway links can be used in remote virtual networking to link to this virtual network. :param bool allow_virtual_network_access: Whether the VMs in the linked virtual network space would be able to access all the VMs in local Virtual network space. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param str peering_state: The status of the virtual network peering. Possible values are 'Initiated', 'Connected', and 'Disconnected'. :param str provisioning_state: The provisioning state of the resource. :param 'SubResourceResponseArgs' remote_virtual_network: The reference of the remote virtual network. :param bool use_remote_gateways: If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network will use gateways of remote virtual network for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway. """ if allow_forwarded_traffic is not None: pulumi.set(__self__, "allow_forwarded_traffic", allow_forwarded_traffic) if allow_gateway_transit is not None: pulumi.set(__self__, "allow_gateway_transit", allow_gateway_transit) if allow_virtual_network_access is not None: pulumi.set(__self__, "allow_virtual_network_access", allow_virtual_network_access) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if peering_state is not None: pulumi.set(__self__, "peering_state", peering_state) if provisioning_state is not None: pulumi.set(__self__, "provisioning_state", provisioning_state) if remote_virtual_network is not None: pulumi.set(__self__, "remote_virtual_network", remote_virtual_network) if use_remote_gateways is not None: pulumi.set(__self__, "use_remote_gateways", use_remote_gateways) @property @pulumi.getter(name="allowForwardedTraffic") def allow_forwarded_traffic(self) -> Optional[bool]: """ Whether the forwarded traffic from the VMs in the remote virtual network will be allowed/disallowed. """ return pulumi.get(self, "allow_forwarded_traffic") @property @pulumi.getter(name="allowGatewayTransit") def allow_gateway_transit(self) -> Optional[bool]: """ If gateway links can be used in remote virtual networking to link to this virtual network. """ return pulumi.get(self, "allow_gateway_transit") @property @pulumi.getter(name="allowVirtualNetworkAccess") def allow_virtual_network_access(self) -> Optional[bool]: """ Whether the VMs in the linked virtual network space would be able to access all the VMs in local Virtual network space. """ return pulumi.get(self, "allow_virtual_network_access") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="peeringState") def peering_state(self) -> Optional[str]: """ The status of the virtual network peering. Possible values are 'Initiated', 'Connected', and 'Disconnected'. """ return pulumi.get(self, "peering_state") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ The provisioning state of the resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="remoteVirtualNetwork") def remote_virtual_network(self) -> Optional['outputs.SubResourceResponse']: """ The reference of the remote virtual network. """ return pulumi.get(self, "remote_virtual_network") @property @pulumi.getter(name="useRemoteGateways") def use_remote_gateways(self) -> Optional[bool]: """ If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network will use gateways of remote virtual network for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway. """ return pulumi.get(self, "use_remote_gateways") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class VpnClientConfigurationResponse(dict): """ VpnClientConfiguration for P2S client. """ def __init__(__self__, *, vpn_client_address_pool: Optional['outputs.AddressSpaceResponse'] = None, vpn_client_revoked_certificates: Optional[Sequence['outputs.VpnClientRevokedCertificateResponse']] = None, vpn_client_root_certificates: Optional[Sequence['outputs.VpnClientRootCertificateResponse']] = None): """ VpnClientConfiguration for P2S client. :param 'AddressSpaceResponseArgs' vpn_client_address_pool: The reference of the address space resource which represents Address space for P2S VpnClient. :param Sequence['VpnClientRevokedCertificateResponseArgs'] vpn_client_revoked_certificates: VpnClientRevokedCertificate for Virtual network gateway. :param Sequence['VpnClientRootCertificateResponseArgs'] vpn_client_root_certificates: VpnClientRootCertificate for virtual network gateway. """ if vpn_client_address_pool is not None: pulumi.set(__self__, "vpn_client_address_pool", vpn_client_address_pool) if vpn_client_revoked_certificates is not None: pulumi.set(__self__, "vpn_client_revoked_certificates", vpn_client_revoked_certificates) if vpn_client_root_certificates is not None: pulumi.set(__self__, "vpn_client_root_certificates", vpn_client_root_certificates) @property @pulumi.getter(name="vpnClientAddressPool") def vpn_client_address_pool(self) -> Optional['outputs.AddressSpaceResponse']: """ The reference of the address space resource which represents Address space for P2S VpnClient. """ return pulumi.get(self, "vpn_client_address_pool") @property @pulumi.getter(name="vpnClientRevokedCertificates") def vpn_client_revoked_certificates(self) -> Optional[Sequence['outputs.VpnClientRevokedCertificateResponse']]: """ VpnClientRevokedCertificate for Virtual network gateway. """ return pulumi.get(self, "vpn_client_revoked_certificates") @property @pulumi.getter(name="vpnClientRootCertificates") def vpn_client_root_certificates(self) -> Optional[Sequence['outputs.VpnClientRootCertificateResponse']]: """ VpnClientRootCertificate for virtual network gateway. """ return pulumi.get(self, "vpn_client_root_certificates") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class VpnClientRevokedCertificateResponse(dict): """ VPN client revoked certificate of virtual network gateway. """ def __init__(__self__, *, provisioning_state: str, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None, thumbprint: Optional[str] = None): """ VPN client revoked certificate of virtual network gateway. :param str provisioning_state: The provisioning state of the VPN client revoked certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param str thumbprint: The revoked VPN client certificate thumbprint. """ pulumi.set(__self__, "provisioning_state", provisioning_state) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) if thumbprint is not None: pulumi.set(__self__, "thumbprint", thumbprint) @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the VPN client revoked certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter def thumbprint(self) -> Optional[str]: """ The revoked VPN client certificate thumbprint. """ return pulumi.get(self, "thumbprint") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class VpnClientRootCertificateResponse(dict): """ VPN client root certificate of virtual network gateway """ def __init__(__self__, *, provisioning_state: str, public_cert_data: str, etag: Optional[str] = None, id: Optional[str] = None, name: Optional[str] = None): """ VPN client root certificate of virtual network gateway :param str provisioning_state: The provisioning state of the VPN client root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :param str public_cert_data: The certificate public data. :param str etag: A unique read-only string that changes whenever the resource is updated. :param str id: Resource ID. :param str name: The name of the resource that is unique within a resource group. This name can be used to access the resource. """ pulumi.set(__self__, "provisioning_state", provisioning_state) pulumi.set(__self__, "public_cert_data", public_cert_data) if etag is not None: pulumi.set(__self__, "etag", etag) if id is not None: pulumi.set(__self__, "id", id) if name is not None: pulumi.set(__self__, "name", name) @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the VPN client root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="publicCertData") def public_cert_data(self) -> str: """ The certificate public data. """ return pulumi.get(self, "public_cert_data") @property @pulumi.getter def etag(self) -> Optional[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
imdb_data.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from __future__ import print_function from builtins import range import sys, os from helpers import * import scipy.sparse import scipy.io as sio import pickle as cp import numpy as np import fastRCNN class imdb_data(fastRCNN.imdb): def __init__(self, image_set, classes, maxNrRois, imgDir, roiDir, cacheDir, boAddGroundTruthRois): fastRCNN.imdb.__init__(self, image_set + ".cache") #'data_' + image_set) self._image_set = image_set self._maxNrRois = maxNrRois self._imgDir = imgDir self._roiDir = roiDir self._cacheDir = cacheDir #cache_path self._imgSubdirs ={'train': ['positive', 'negative'], 'test': ['testImages']} self._classes = classes self._class_to_ind = dict(zip(self.classes, range(self.num_classes))) self._image_ext = '.jpg' self._image_index, self._image_subdirs = self._load_image_set_index() self._roidb_handler = self.selective_search_roidb self._boAddGroundTruthRois = boAddGroundTruthRois #overwrite parent definition @property def cache_path(self): return self._cacheDir def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self._image_subdirs[i], self._image_index[i]) def image_path_from_index(self, subdir, fname): """ Construct an image path from the image's "index" identifier. """ image_path = os.path.join(self._imgDir, subdir, fname) assert os.path.exists(image_path), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Compile list of image indices and the subdirectories they are in. """ image_index = [] image_subdirs = [] for subdir in self._imgSubdirs[self._image_set]: imgFilenames = getFilesInDirectory(os.path.join(self._imgDir,subdir), self._image_ext) image_index += imgFilenames image_subdirs += [subdir] * len(imgFilenames) return image_index, image_subdirs def
(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cp.load(fid) print ('{} gt roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = [self._load_annotation(i) for i in range(self.num_images)] with open(cache_file, 'wb') as fid: cp.dump(gt_roidb, fid, cp.HIGHEST_PROTOCOL) print ('wrote gt roidb to {}'.format(cache_file)) return gt_roidb def selective_search_roidb(self): """ Return the database of selective search regions of interest. Ground-truth ROIs are also included. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_selective_search_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: if sys.version_info[0] < 3: roidb = cp.load(fid) else: roidb = cp.load(fid, encoding='latin1') print ('{} ss roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = self.gt_roidb() ss_roidb = self._load_selective_search_roidb(gt_roidb) #add ground truth ROIs if self._boAddGroundTruthRois: roidb = self.merge_roidbs(gt_roidb, ss_roidb) else: roidb = ss_roidb #Keep max of e.g. 2000 rois if self._maxNrRois and self._maxNrRois > 0: print ("Only keeping the first %d ROIs.." % self._maxNrRois) for i in range(self.num_images): gt_overlaps = roidb[i]['gt_overlaps'] gt_overlaps = gt_overlaps.todense()[:self._maxNrRois] gt_overlaps = scipy.sparse.csr_matrix(gt_overlaps) roidb[i]['gt_overlaps'] = gt_overlaps roidb[i]['boxes'] = roidb[i]['boxes'][:self._maxNrRois,:] roidb[i]['gt_classes'] = roidb[i]['gt_classes'][:self._maxNrRois] with open(cache_file, 'wb') as fid: cp.dump(roidb, fid, cp.HIGHEST_PROTOCOL) print ('wrote ss roidb to {}'.format(cache_file)) return roidb def _load_selective_search_roidb(self, gt_roidb): # box_list = nrImages x nrBoxes x 4 box_list = [] for imgFilename, subdir in zip(self._image_index, self._image_subdirs): roiPath = "{}/{}/{}.roi.txt".format(self._roiDir, subdir, imgFilename[:-4]) assert os.path.exists(roiPath), "Error: rois file not found: " + roiPath rois = np.loadtxt(roiPath, np.int32) box_list.append(rois) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_annotation(self, imgIndex): """ Load image and bounding boxes info from human annotations. """ #negative images do not have any ground truth annotations if self._image_subdirs[imgIndex].lower() == "negative": return None imgPath = self.image_path_at(imgIndex) bboxesPaths = imgPath[:-4] + ".bboxes.tsv" labelsPaths = imgPath[:-4] + ".bboxes.labels.tsv" assert os.path.exists(bboxesPaths), "Error: ground truth bounding boxes file not found: " + bboxesPaths assert os.path.exists(labelsPaths), "Error: ground truth labels file not found: " + bboxesPaths bboxes = np.loadtxt(bboxesPaths, np.float32) labels = readFile(labelsPaths) # in case there's only one annotation and numpy read the array as single array, # we need to make sure the input is treated as a multi dimensional array instead of a list/ 1D array #if len(bboxes.shape) == 1: if len(bboxes)>0 and type(bboxes[0]) == np.float32: bboxes = np.array([bboxes]) #remove boxes marked as 'undecided' or 'exclude' indicesToKeep = find(labels, lambda x: x!='EXCLUDE' and x!='UNDECIDED') bboxes = [bboxes[i] for i in indicesToKeep] labels = [labels[i] for i in indicesToKeep] # Load object bounding boxes into a data frame. num_objs = len(bboxes) boxes = np.zeros((num_objs,4), dtype=np.uint16) gt_classes = np.zeros(num_objs, dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) for bboxIndex,(bbox,label) in enumerate(zip(bboxes,labels)): cls = self._class_to_ind[label] #.decode('utf-8')] boxes[bboxIndex, :] = bbox gt_classes[bboxIndex] = cls overlaps[bboxIndex, cls] = 1.0 overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes' : boxes, 'gt_classes': gt_classes, 'gt_overlaps' : overlaps, 'flipped' : False} # main call to compute per-calass average precision # shape of all_boxes: e.g. 21 classes x 4952 images x 58 rois x 5 coords+score # (see also test_net() in fastRCNN\test.py) def evaluate_detections(self, all_boxes, output_dir, use_07_metric=False, overlapThreshold = 0.5): aps = [] for classIndex, className in enumerate(self._classes): if className != '__background__': rec, prec, ap = self._evaluate_detections(classIndex, all_boxes, use_07_metric, overlapThreshold) aps += [[className,ap]] print('AP for {:>15} = {:.4f}'.format(className, ap)) print('Mean AP = {:.4f}'.format(np.nanmean(getColumn(aps,1)))) return aps def _evaluate_detections(self, classIndex, all_boxes, use_07_metric = False, overlapThreshold = 0.5): """ Top level function that does the PASCAL VOC evaluation. [overlapThreshold]: Overlap threshold (default = 0.5) [use_07_metric]: Whether to use VOC07's 11 point AP computation (default False) """ assert (len(all_boxes) == self.num_classes) assert (len(all_boxes[0]) == self.num_images) # load ground truth annotations for this class gtInfos = [] for imgIndex in range(self.num_images): imgPath = self.image_path_at(imgIndex) imgSubir = os.path.normpath(imgPath).split(os.path.sep)[-2] if imgSubir != 'negative': gtBoxes, gtLabels = readGtAnnotation(imgPath) gtBoxes = [box for box, label in zip(gtBoxes, gtLabels) if label == self.classes[classIndex]] #.decode('utf-8') else: gtBoxes = [] gtInfos.append({'bbox': np.array(gtBoxes), 'difficult': [False] * len(gtBoxes), 'det': [False] * len(gtBoxes)}) # parse detections for this class # shape of all_boxes: e.g. 21 classes x 4952 images x 58 rois x 5 coords+score detBboxes = [] detImgIndices = [] detConfidences = [] for imgIndex in range(self.num_images): dets = all_boxes[classIndex][imgIndex] if dets != []: for k in range(dets.shape[0]): detImgIndices.append(imgIndex) detConfidences.append(dets[k, -1]) # the VOCdevkit expects 1-based indices detBboxes.append([dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1]) detBboxes = np.array(detBboxes) detConfidences = np.array(detConfidences) # debug: visualize GT and detections # if classIndex == 15: # and imgPath.endswith("WIN_20160803_11_42_36_Pro.jpg"): # imgIndex = 6 # imgPath = self.image_path_at(imgIndex) # img = imread(imgPath) # tmp_gtBoxes = gtInfos[imgIndex]['bbox'] # inds = np.where(np.array(detImgIndices) == 1)[0] # tmp_detBoxes = detBboxes[inds] # print(detConfidences[inds]) # drawRectangles(img, tmp_gtBoxes, color = (255, 0, 0)) #thickness=thickness) # drawRectangles(img, tmp_detBoxes, color= (0, 255, 0)) # thickness=thickness) # imshow(img, maxDim=800) # compute precision / recall / ap rec, prec, ap = self._voc_computePrecisionRecallAp( class_recs=gtInfos, confidence=detConfidences, image_ids=detImgIndices, BB=detBboxes, ovthresh=overlapThreshold, use_07_metric=use_07_metric) return rec, prec, ap ######################################################################### # Python evaluation functions (copied/refactored from faster-RCNN) ########################################################################## def _voc_computePrecisionRecallAp(self, class_recs, confidence, image_ids, BB, ovthresh=0.5, use_07_metric=False): # sort by confidence sorted_ind = np.argsort(-confidence) BB = BB[sorted_ind, :] image_ids = [image_ids[x] for x in sorted_ind] # go down dets and mark TPs and FPs nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) ovmax = -np.inf BBGT = R['bbox'].astype(float) if BBGT.size > 0: # compute overlaps ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin = np.maximum(BBGT[:, 1], bb[1]) ixmax = np.minimum(BBGT[:, 2], bb[2]) iymax = np.minimum(BBGT[:, 3], bb[3]) iw = np.maximum(ixmax - ixmin + 1., 0.) ih = np.maximum(iymax - iymin + 1., 0.) inters = iw * ih # union uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + (BBGT[:, 2] - BBGT[:, 0] + 1.) * (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters) overlaps = inters / uni ovmax = np.max(overlaps) jmax = np.argmax(overlaps) if ovmax > ovthresh: if not R['difficult'][jmax]: if not R['det'][jmax]: tp[d] = 1. R['det'][jmax] = 1 else: fp[d] = 1. else: fp[d] = 1. # compute precision recall npos = sum([len(cr['bbox']) for cr in class_recs]) fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / float(npos) # avoid divide by zero in case the first detection matches a difficult # ground truth prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = computeAveragePrecision(rec, prec, use_07_metric) return rec, prec, ap
gt_roidb
plot_evalrep.py
#!/usr/bin/env python3 # # Plots the power spectra and Fourier-space biases for the HI. # import numpy as np import os, sys import matplotlib.pyplot as plt from pmesh.pm import ParticleMesh from scipy.interpolate import InterpolatedUnivariateSpline as ius from nbodykit.lab import BigFileMesh, BigFileCatalog, FFTPower from nbodykit.cosmology import Planck15, EHPower, Cosmology sys.path.append('../utils/') sys.path.append('../recon/') sys.path.append('../recon/cosmo4d/') from lab import mapbias as mapp from lab import report as rp from lab import dg from getbiasparams import getbias import tools # from matplotlib import rc, rcParams, font_manager rcParams['font.family'] = 'serif' fsize = 12 fontmanage = font_manager.FontProperties(family='serif', style='normal', size=fsize, weight='normal', stretch='normal') font = {'family': fontmanage.get_family()[0], 'style': fontmanage.get_style(), 'weight': fontmanage.get_weight(), 'size': fontmanage.get_size(), } print(font) # import argparse parser = argparse.ArgumentParser() #parser.add_argument('-m', '--model', help='model name to use') parser.add_argument('-a', '--aa', help='scale factor', default=0.3333, type=float) parser.add_argument('-l', '--bs', help='boxsize', default=256, type=float) parser.add_argument('-n', '--nmesh', help='nmesh', default=128, type=int) parser.add_argument('-t', '--angle', help='angle of the wedge', default=50, type=float) parser.add_argument('-k', '--kmin', help='kmin of the wedge', default=0.01, type=float) args = parser.parse_args() figpath = './figs/' bs, nc, aa = args.bs, args.nmesh, args.aa zz = 1/aa- 1 kmin = args.kmin ang = args.angle pm = ParticleMesh(BoxSize=bs, Nmesh=[nc, nc, nc]) rank = pm.comm.rank dpath = '/global/cscratch1/sd/chmodi/m3127/21cm_cleaning/recon/fastpm_%0.4f/wedge_kmin%0.2f_ang%0.1f/'%(aa, kmin, ang) dpath += 'L%04d-N%04d/'%(bs, nc) ################ def
(): """Does the work of making the real-space xi(r) and b(r) figure.""" noises = np.loadtxt('/global/u1/c/chmodi/Programs/21cm/21cm_cleaning/data/summaryHI.txt').T for i in range(noises[0].size): if noises[0][i] == np.round(1/aa-1, 2): noise = noises[3][i] print(noise) datap = mapp.Observable.load(dpath+'ZA/opt_s999_h1massA_fourier/datap') dataprsd = mapp.Observable.load(dpath+'ZA/opt_s999_h1massA_fourier_rsdpos/datap') try: datapup = mapp.Observable.load(dpath+'ZA/opt_s999_h1massA_fourier/datap_up') dataprsdup = mapp.Observable.load(dpath+'ZA/opt_s999_h1massA_fourier_rsdpos/datap_up') except Exception as e: print(e) fig, ax = plt.subplots(1, 2, figsize=(9, 4)) def makeplot(bfit, datapp, lss, lww, cc, lbl=None): rpfit = rp.evaluate1(bfit, datapp, field='mapp')[:-2] ax[0].plot(rpfit[0]['k'], rpfit[0]['power']/(rpfit[1]['power']*rpfit[2]['power'])**0.5, ls=lss, lw=lww, color=cc, label=lbl) ax[1].plot(rpfit[0]['k'], (rpfit[1]['power']/rpfit[2]['power'])**0.5, ls=lss, lw=lww, color=cc) #fits try: basepath = dpath+'ZA/opt_s999_h1massA_fourier/%d-0.00/'%(nc) bpaths = [basepath+'/best-fit'] + [basepath + '/%04d/fit_p/'%i for i in range(100, -1, -20)] print(bpaths) for path in bpaths: if os.path.isdir(path): break print(path) bfit = mapp.Observable.load(path) datapp = datap lss, lww, cc, lbl = '-', 2, 'C0', 'Fid' makeplot(bfit, datapp, lss, lww, cc, lbl) print('%s done'%lbl) except Exception as e: print(e) try: basepath = dpath+'ZA/opt_s999_h1massA_fourier/upsample1/%d-0.00/'%(2*nc) bpaths = [basepath+'/best-fit'] + [basepath + '/%04d/fit_p/'%i for i in range(100, -1, -20)] for path in bpaths: if os.path.isdir(path): break print(path) bfit = mapp.Observable.load(path) datapp = datapup lss, lww, cc, lbl = '-', 2, 'C1', 'Up1' makeplot(bfit, datapp, lss, lww, cc, lbl) print('%s done'%lbl) except Exception as e: print(e) try: basepath = dpath+'ZA/opt_s999_h1massA_fourier/upsample2/%d-0.00/'%(2*nc) bpaths = [basepath+'/best-fit'] + [basepath + '/%04d/fit_p/'%i for i in range(100, -1, -20)] for path in bpaths: if os.path.isdir(path): break print(path) bfit = mapp.Observable.load(path) datapp = datapup lss, lww, cc, lbl = '-', 2, 'C2', 'Up2' makeplot(bfit, datapp, lss, lww, cc, lbl) print('%s done'%lbl) except Exception as e: print(e) #rsd try: basepath = dpath+'ZA/opt_s999_h1massA_fourier_rsdpos/%d-0.00/'%(nc) bpaths = [basepath+'/best-fit'] + [basepath + '/%04d/fit_p/'%i for i in range(100, -1, -20)] for path in bpaths: if os.path.isdir(path): break print(path) bfit = mapp.Observable.load(path) datapp = dataprsd lss, lww, cc, lbl = '--', 2, 'C0', 'rsd' makeplot(bfit, datapp, lss, lww, cc, lbl) print('%s done'%lbl) except Exception as e: print(e) try: basepath = dpath+'ZA/opt_s999_h1massA_fourier_rsdpos/upsample1/%d-0.00/'%(2*nc) bpaths = [basepath+'/best-fit'] + [basepath + '/%04d/fit_p/'%i for i in range(100, -1, -20)] for path in bpaths: if os.path.isdir(path): break print(path) bfit = mapp.Observable.load(path) datapp = dataprsdup lss, lww, cc, lbl = '--', 2, 'C1', 'rsd up' makeplot(bfit, datapp, lss, lww, cc, lbl) print('%s done'%lbl) except Exception as e: print(e) try: basepath = dpath+'ZA/opt_s999_h1massA_fourier_rsdpos/upsample2/%d-0.00/'%(2*nc) bpaths = [basepath+'/best-fit'] + [basepath + '/%04d/fit_p/'%i for i in range(100, -1, -20)] for path in bpaths: if os.path.isdir(path): break print(path) bfit = mapp.Observable.load(path) datapp = dataprsdup lss, lww, cc, lbl = '--', 2, 'C2', 'rsd up2' makeplot(bfit, datapp, lss, lww, cc, lbl) print('%s done'%lbl) except Exception as e: print(e) ax[0].set_ylabel('$r_{cc}$', fontdict=font) ax[1].set_ylabel(r'$\sqrt{P_{\rm mod}/P_{hh}}$', fontdict=font) for axis in ax: axis.set_xlabel(r'$k\quad [h\,{\rm Mpc}^{-1}]$', fontdict=font) axis.set_xscale('log') axis.grid(which='both', lw=0.2, alpha=0.2, color='gray') axis.legend(prop=fontmanage) # Put on some more labels. for axis in ax: axis.set_xscale('log') for tick in axis.xaxis.get_major_ticks(): tick.label.set_fontproperties(fontmanage) for tick in axis.yaxis.get_major_ticks(): tick.label.set_fontproperties(fontmanage) ##and finish plt.tight_layout(rect=[0, 0, 1, 0.95]) if rank == 0: plt.savefig(figpath + '/rep_L%04d_%04d.pdf'%(bs, aa*10000)) ################ if __name__=="__main__": make_rep_plot() #
make_rep_plot
forms.py
from django import forms from django.core.exceptions import ValidationError from django.utils.translation import pgettext_lazy from ...error_codes import PaymentErrorCode from ...interface import PaymentData class BraintreePaymentForm(forms.Form): amount = forms.DecimalField() # Unique transaction identifier returned by Braintree # for testing in the sandbox mode please refer to # https://developers.braintreepayments.com/reference/general/testing/python#nonces-representing-cards # as it's values should be hardcoded to simulate each payment gateway # response payment_method_nonce = forms.CharField() env = forms.CharField(widget=forms.HiddenInput(), required=False) def __init__(self, payment_information: PaymentData, *args, **kwargs): config = kwargs.pop("config") super().__init__(*args, **kwargs) self.payment_information = payment_information self.fields["amount"].initial = payment_information.amount self.fields["env"].initial = ( "sandbox" if config.connection_params["sandbox_mode"] else "production" ) def
(self): cleaned_data = super().clean() # Amount is sent client-side # authorizing different amount than payments' total could happen only # when manually adjusting the template value as we do not allow # partial-payments at this moment, error is returned instead. amount = cleaned_data.get("amount") if amount and amount != self.payment_information.amount: msg = pgettext_lazy( "payment error", "Unable to process transaction. Please try again in a moment", ) raise ValidationError(msg, code=PaymentErrorCode.PAYMENT_ERROR) return cleaned_data def get_payment_token(self): return self.cleaned_data["payment_method_nonce"]
clean
esp8266_devicecloud.py
""" Example for posting data to Device Cloud for data graphing, storage and analysis. (digi.com/products/cloud/digi-device-cloud) by Rob Faludi, faludi.com """ import time import httpclient import ubinascii version = '1.0.0' username = 'your username here' #enter your username! password = 'your password here' #enter your password! # Device Cloud connection info url = 'http://devicecloud.digi.com/ws/v1/streams/history' headers= {'authorization': 'Basic ' + auth} stream_id = 'myStream' stream_type = 'DOUBLE' auth = ubinascii.b2a_base64(username + ':' + password).decode().strip() #base64 encoding # posts data to Digi Device Cloud def dc_post(data):
# example program: posts 0 to 499 to a Device Cloud data stream if __name__ == "__main__": for data in range(500): try: status = dc_post(data) # post data to Device Cloud except Exception as e: status = type(e).__name__ + ': ' + str(e) print('exception:', e) print('post', data, 'status:', status) time.sleep(1)
json={"stream_id": stream_id, "stream_type": stream_type, "value": str(data)} r = httpclient.post(url, headers=headers, json=json) r.close() return r.status_code
bench_function_base.py
from __future__ import absolute_import, division, print_function from .common import Benchmark import numpy as np class Histogram1D(Benchmark): def setup(self): self.d = np.linspace(0, 100, 100000) def time_full_coverage(self): np.histogram(self.d, 200, (0, 100)) def time_small_coverage(self): np.histogram(self.d, 200, (50, 51)) def time_fine_binning(self): np.histogram(self.d, 10000, (0, 100)) class Histogram2D(Benchmark): def setup(self): self.d = np.linspace(0, 100, 200000).reshape((-1,2)) def time_full_coverage(self): np.histogramdd(self.d, (200, 200), ((0, 100), (0, 100))) def time_small_coverage(self): np.histogramdd(self.d, (200, 200), ((50, 51), (50, 51))) def time_fine_binning(self): np.histogramdd(self.d, (10000, 10000), ((0, 100), (0, 100))) class Bincount(Benchmark): def setup(self): self.d = np.arange(80000, dtype=np.intp) self.e = self.d.astype(np.float64) def time_bincount(self): np.bincount(self.d) def time_weights(self): np.bincount(self.d, weights=self.e) class Median(Benchmark): def setup(self): self.e = np.arange(10000, dtype=np.float32) self.o = np.arange(10001, dtype=np.float32) def time_even(self):
def time_odd(self): np.median(self.o) def time_even_inplace(self): np.median(self.e, overwrite_input=True) def time_odd_inplace(self): np.median(self.o, overwrite_input=True) def time_even_small(self): np.median(self.e[:500], overwrite_input=True) def time_odd_small(self): np.median(self.o[:500], overwrite_input=True) class Percentile(Benchmark): def setup(self): self.e = np.arange(10000, dtype=np.float32) self.o = np.arange(10001, dtype=np.float32) def time_quartile(self): np.percentile(self.e, [25, 75]) def time_percentile(self): np.percentile(self.e, [25, 35, 55, 65, 75]) class Select(Benchmark): def setup(self): self.d = np.arange(20000) self.e = self.d.copy() self.cond = [(self.d > 4), (self.d < 2)] self.cond_large = [(self.d > 4), (self.d < 2)] * 10 def time_select(self): np.select(self.cond, [self.d, self.e]) def time_select_larger(self): np.select(self.cond_large, ([self.d, self.e] * 10)) def memoize(f): _memoized = {} def wrapped(*args): if args not in _memoized: _memoized[args] = f(*args) return _memoized[args].copy() return f class SortGenerator(object): # The size of the unsorted area in the "random unsorted area" # benchmarks AREA_SIZE = 100 # The size of the "partially ordered" sub-arrays BUBBLE_SIZE = 100 @staticmethod @memoize def random(size, dtype): """ Returns a randomly-shuffled array. """ arr = np.arange(size, dtype=dtype) np.random.shuffle(arr) return arr @staticmethod @memoize def ordered(size, dtype): """ Returns an ordered array. """ return np.arange(size, dtype=dtype) @staticmethod @memoize def reversed(size, dtype): """ Returns an array that's in descending order. """ return np.arange(size-1, -1, -1, dtype=dtype) @staticmethod @memoize def uniform(size, dtype): """ Returns an array that has the same value everywhere. """ return np.ones(size, dtype=dtype) @staticmethod @memoize def swapped_pair(size, dtype, swap_frac): """ Returns an ordered array, but one that has ``swap_frac * size`` pairs swapped. """ a = np.arange(size, dtype=dtype) for _ in range(int(size * swap_frac)): x, y = np.random.randint(0, size, 2) a[x], a[y] = a[y], a[x] return a @staticmethod @memoize def sorted_block(size, dtype, block_size): """ Returns an array with blocks that are all sorted. """ a = np.arange(size, dtype=dtype) b = [] if size < block_size: return a block_num = size // block_size for i in range(block_num): b.extend(a[i::block_num]) return np.array(b) @classmethod @memoize def random_unsorted_area(cls, size, dtype, frac, area_size=None): """ This type of array has random unsorted areas such that they compose the fraction ``frac`` of the original array. """ if area_size is None: area_size = cls.AREA_SIZE area_num = int(size * frac / area_size) a = np.arange(size, dtype=dtype) for _ in range(area_num): start = np.random.randint(size-area_size) end = start + area_size np.random.shuffle(a[start:end]) return a @classmethod @memoize def random_bubble(cls, size, dtype, bubble_num, bubble_size=None): """ This type of array has ``bubble_num`` random unsorted areas. """ if bubble_size is None: bubble_size = cls.BUBBLE_SIZE frac = bubble_size * bubble_num / size return cls.random_unsorted_area(size, dtype, frac, bubble_size) class Sort(Benchmark): """ This benchmark tests sorting performance with several different types of arrays that are likely to appear in real-world applications. """ params = [ # In NumPy 1.17 and newer, 'merge' can be one of several # stable sorts, it isn't necessarily merge sort. ['quick', 'merge', 'heap'], ['float64', 'int64', 'int16'], [ ('random',), ('ordered',), ('reversed',), ('uniform',), ('sorted_block', 10), ('sorted_block', 100), ('sorted_block', 1000), # ('swapped_pair', 0.01), # ('swapped_pair', 0.1), # ('swapped_pair', 0.5), # ('random_unsorted_area', 0.5), # ('random_unsorted_area', 0.1), # ('random_unsorted_area', 0.01), # ('random_bubble', 1), # ('random_bubble', 5), # ('random_bubble', 10), ], ] param_names = ['kind', 'dtype', 'array_type'] # The size of the benchmarked arrays. ARRAY_SIZE = 10000 def setup(self, kind, dtype, array_type): np.random.seed(1234) array_class = array_type[0] self.arr = getattr(SortGenerator, array_class)(self.ARRAY_SIZE, dtype, *array_type[1:]) def time_sort(self, kind, dtype, array_type): # Using np.sort(...) instead of arr.sort(...) because it makes a copy. # This is important because the data is prepared once per benchmark, but # used across multiple runs. np.sort(self.arr, kind=kind) def time_argsort(self, kind, dtype, array_type): np.argsort(self.arr, kind=kind) class SortWorst(Benchmark): def setup(self): # quicksort median of 3 worst case self.worst = np.arange(1000000) x = self.worst while x.size > 3: mid = x.size // 2 x[mid], x[-2] = x[-2], x[mid] x = x[:-2] def time_sort_worst(self): np.sort(self.worst) # Retain old benchmark name for backward compatability time_sort_worst.benchmark_name = "bench_function_base.Sort.time_sort_worst" class Where(Benchmark): def setup(self): self.d = np.arange(20000) self.e = self.d.copy() self.cond = (self.d > 5000) def time_1(self): np.where(self.cond) def time_2(self): np.where(self.cond, self.d, self.e) def time_2_broadcast(self): np.where(self.cond, self.d, 0)
np.median(self.e)
surveyvalidatortests.ts
import { SurveyValidator, NumericValidator, EmailValidator, ValidatorResult } from "../src/validator"; import { CustomError } from "../src/error"; import { SurveyModel } from "../src/survey"; import { QuestionTextModel } from "../src/question_text"; import { QuestionMultipleTextModel } from "../src/question_multipletext"; import { JsonObject } from "../src/jsonobject"; export default QUnit.module("Validators"); QUnit.test("Numeric validator", function(assert) { var validator = new NumericValidator(); assert.notEqual( validator.validate("s5").error, null, "Could not convert to numeric" ); assert.equal(validator.validate(5), null, "There are no limits (non-zero)"); assert.equal(validator.validate(0), null, "There are no limits (zero)"); assert.equal( validator.validate("5").value, 5, "Convert to numeric (non-zero)" ); assert.equal( validator.validate("5").error, null, "There is no error (non-zero)" ); assert.equal(validator.validate("0").value, 0, "Convert to numeric (zero)"); assert.equal(validator.validate("0").error, null, "There is no error (zero)"); validator.minValue = 10; validator.maxValue = 20; assert.notEqual( validator.validate(5).error, null, "Value is too low. Limits are not 0." ); assert.notEqual( validator.validate(25).error, null, "Value is too high. Limits are not 0." ); assert.equal( validator.validate("15").error, null, "Value is between minValue and maxValue. Limits are not 0." ); assert.equal( validator.validate(15), null, "Value is between minValue and maxValue. Return no errors. Limits are not 0." ); validator.minValue = 0; validator.maxValue = 20; assert.notEqual( validator.validate(-1).error, null, "Value is too low. Low limit is 0." ); assert.notEqual( validator.validate(25).error, null, "Value is too high. Low limit is 0." ); assert.equal( validator.validate("15").error, null, "Value is between minValue and maxValue. Low limit is 0." ); assert.equal( validator.validate(15), null, "Value is between minValue and maxValue. Return no errors. Low limit is 0." ); validator.minValue = -20; validator.maxValue = 0; assert.notEqual( validator.validate(-21).error, null, "Value is too low. High limit is 0." ); assert.notEqual( validator.validate(1).error, null, "Value is too high. High limit is 0." ); assert.equal( validator.validate("-5").error, null, "Value is between minValue and maxValue. High limit is 0." ); assert.equal( validator.validate(-5), null, "Value is between minValue and maxValue. Return no errors. High limit is 0." ); }); QUnit.test("Email validator", function(assert) { var validator = new EmailValidator(); assert.equal( validator.validate("[email protected]"), null, "Could convert the correct e-mail" ); assert.notEqual( validator.validate("@mail.com").error, null, "Could convert the incorrect correct e-mail" ); }); export class CamelCaseValidator extends SurveyValidator { public getType(): string { return "CamelCaseValidator"; } public validate(value: any, name: string = null): ValidatorResult { if (!value) return null; if (value.indexOf("CamelCase") < 0) return new ValidatorResult(value, new CustomError("No Camel Case")); return null; } } JsonObject.metaData.addClass( "CamelCaseValidator", [], function() { return new CamelCaseValidator(); }, "surveyvalidator" ); QUnit.test("Support camel names in validators, Bug#994", function(assert) { var json = { elements: [ { type: "text", name: "qSame", validators: [{ type: "CamelCaseValidator" }] }, { type: "text", name: "qLow", validators: [{ type: "camelcasevalidator" }] }, { type: "text", name: "qUpper", validators: [{ type: "CAMELCASEVALIDATOR" }] } ] }; var survey = new SurveyModel(json); var qSame = <QuestionTextModel>survey.getQuestionByName("qSame"); var qLow = <QuestionTextModel>survey.getQuestionByName("qLow"); var qUpper = <QuestionTextModel>survey.getQuestionByName("qUpper"); assert.equal(qSame.validators.length, 1, "same case - validtor is here"); assert.equal(qLow.validators.length, 1, "low case - validtor is here"); assert.equal(qUpper.validators.length, 1, "upper case - validtor is here"); }); QUnit.test( "Validators and isRequired in multipletext items, Bug#1055", function(assert) { var json = { questions: [ { type: "multipletext", name: "pricelimit", items: [ { name: "leastamount", validators: [ { type: "numeric", minValue: 0, maxValue: 100 } ] }, { name: "mostamount", isRequired: true, validators: [ { type: "numeric", minValue: 0, maxValue: 100 } ] } ] } ] };
var survey = new SurveyModel(json); var question = <QuestionMultipleTextModel>survey.getQuestionByName( "pricelimit" ); question.items[1].value = 3; assert.equal( question.hasErrors(), false, "Everything is fine, there is no errors" ); } );
stack.py
#!python from linkedlist import LinkedList class LinkedStack(object): def __init__(self, iterable=None): """Initialize this stack and push the given items, if any.""" # Initialize a new linked list to store the items self.list = LinkedList() if iterable is not None: for item in iterable: self.push(item) def __repr__(self): """Return a string representation of this stack.""" return 'Stack({} items, top={})'.format(self.length(), self.peek()) def is_empty(self): """Return True if this stack is empty, or False otherwise.""" return self.list.is_empty() def length(self): """Return the number of items in this stack.""" return self.list.length() def push(self, item): """Insert the given item on the top of this stack. Running time: O(???) – Why? [TODO]""" return self.list.append(item) def peek(self): """Return the item on the top of this stack without removing it, or None if this stack is empty.""" if self.is_empty(): return None return self.list.tail.data def pop(self): """Remove and return the item on the top of this stack, or raise ValueError if this stack is empty. Running time: O(???) – Why? [TODO]""" if self.is_empty(): raise ValueError else: node = self.list.tail.data self.list.delete(node) return node # Implement ArrayStack below, then change the assignment at the bottom # to use this Stack implementation to verify it passes all tests class ArrayStack(object): def __init__(self, iterable=None): """Initialize this stack and push the given items, if any.""" self.list = list() # Initialize a new list (dynamic array) to store the items if iterable is not None: for item in iterable: self.push(item) def __repr__(self): """Return a string representation of this stack.""" return 'Stack({} items, top={})'.format(self.length(), self.peek()) def is_empty(self): """Return True if this stack is empty, or False otherwise.""" if len(self.list) == 0: return True return False def length
: """Return the number of items in this stack.""" return len(self.list) def push(self, item): """Insert the given item on the top of this stack. Running time: O(???) – Why? [TODO]""" return self.list.append(item) def peek(self): """Return the item on the top of this stack without removing it, or None if this stack is empty.""" if self.is_empty(): return None return self.list[-1] def pop(self): """Remove and return the item on the top of this stack Running time: O(???) – Why? [TODO]""" if self.is_empty(): # if this stack is empty raise ValueError() #raise ValueError else: return self.list.pop() # Stack = LinkedStack Stack = ArrayStack
(self)
setup.py
# -*- coding: utf-8 -*- __author__ = 'zhnlk' import os from setuptools import setup import cores def getSubpackages(name):
r', version=cores.__version__, author=cores.__author__, author_email='[email protected]', license='MIT', url='http://github.com/zhnlk/nbcrawler', description='A crawler framework for NewBanker', long_description=__doc__, keywords='crawler newbanker spider distribute ', classifiers=['Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries', 'Programming Language :: Python :: Implementation :: CPython', 'License :: OSI Approved :: MIT License'], packages=getSubpackages('vnpy'), )
"""获取该模块下所有的子模块名称""" splist = [] for dirpath, _dirnames, _filenames in os.walk(name): if os.path.isfile(os.path.join(dirpath, '__init__.py')): splist.append(".".join(dirpath.split(os.sep))) return splist setup( name='nbcrawle
handlers_test.go
package handlers import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "database/sql" "encoding/hex" "encoding/json" "errors" "net/http" "net/http/httptest" "os" "reflect" "sync" "testing" "time" "github.com/SIGBlockchain/project_aurum/internal/accountstable" "github.com/SIGBlockchain/project_aurum/internal/block" "github.com/SIGBlockchain/project_aurum/internal/constants" "github.com/SIGBlockchain/project_aurum/internal/contracts" "github.com/SIGBlockchain/project_aurum/internal/hashing" "github.com/SIGBlockchain/project_aurum/internal/mock" "github.com/SIGBlockchain/project_aurum/internal/pendingpool" "github.com/SIGBlockchain/project_aurum/internal/publickey" "github.com/SIGBlockchain/project_aurum/internal/sqlstatements" "github.com/SIGBlockchain/project_aurum/internal/requests" _ "github.com/mattn/go-sqlite3" ) func TestHandleAccountInfoRequest(t *testing.T) { req, err := requests.NewAccountInfoRequest("", "xyz") if err != nil { t.Errorf("failed to create new account info request : %v", err) } rr := httptest.NewRecorder() dbConn, err := sql.Open("sqlite3", constants.AccountsTable) if err != nil { t.Errorf("failed to open database connection : %v", err) } defer func() { if err := dbConn.Close(); err != nil { t.Errorf("failed to close database connection : %v", err) } if err := os.Remove(constants.AccountsTable); err != nil { t.Errorf("failed to remove database : %v", err) } }() statement, _ := dbConn.Prepare(sqlstatements.CREATE_ACCOUNT_BALANCES_TABLE) statement.Exec() var pLock = new(sync.Mutex) // Check empty table var emptyPMap pendingpool.PendingMap handler := http.HandlerFunc(HandleAccountInfoRequest(dbConn, emptyPMap, pLock)) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned with wrong status code: got %v want %v", status, http.StatusNotFound) } body := rr.Body.String() if body != NOT_FOUND_ERR_MSG { t.Errorf("Wrong body message.\nExpexted %s\nFound %s", NOT_FOUND_ERR_MSG, body) } // Insert key into table privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedSenderPublicKey, _ := publickey.Encode(&privateKey.PublicKey) var walletAddress = hashing.New(encodedSenderPublicKey) err = accountstable.InsertAccountIntoAccountBalanceTable(dbConn, walletAddress, 1337) if err != nil { t.Errorf("failed to insert sender account") } req, err = requests.NewAccountInfoRequest("", hex.EncodeToString(walletAddress)) if err != nil { t.Errorf("failed to create new account info request : %v", err) } rr = httptest.NewRecorder() handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned with wrong status code: got %v want %v", status, http.StatusOK) } type AccountInfo struct { WalletAddress string Balance uint64 StateNonce uint64 } var accInfo AccountInfo if err := json.Unmarshal(rr.Body.Bytes(), &accInfo); err != nil { t.Errorf("failed to unmarshall response body: %v", err) } if accInfo.WalletAddress != hex.EncodeToString(walletAddress) { t.Errorf("failed to get correct wallet address: got %s want %s", accInfo.WalletAddress, walletAddress) } if accInfo.Balance != 1337 { t.Errorf("failed to get correct balance: got %d want %d", accInfo.Balance, 1337) } if accInfo.StateNonce != 0 { t.Errorf("failed to get correct state nonce: got %d want %d", accInfo.StateNonce, 0) } // Pending case privateKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedSenderPublicKey, _ = publickey.Encode(&privateKey.PublicKey) walletAddress = hashing.New(encodedSenderPublicKey) pData := pendingpool.NewPendingData(1234, 5678) pMap := pendingpool.NewPendingMap() pMap.Sender[hex.EncodeToString(walletAddress)] = &pData req, err = requests.NewAccountInfoRequest("", hex.EncodeToString(walletAddress)) rr = httptest.NewRecorder() handler = http.HandlerFunc(HandleAccountInfoRequest(dbConn, pMap, pLock)) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned with wrong status code: got %v want %v", status, http.StatusOK) } if err := json.Unmarshal(rr.Body.Bytes(), &accInfo); err != nil { t.Errorf("failed to unmarshall response body: %v", err) } if accInfo.WalletAddress != hex.EncodeToString(walletAddress) { t.Errorf("failed to get correct wallet address: got %s want %s", accInfo.WalletAddress, walletAddress) } if accInfo.Balance != 1234 { t.Errorf("failed to get correct balance: got %d want %d", accInfo.Balance, 1234) } if accInfo.StateNonce != 5678 { t.Errorf("failed to get correct state nonce: got %d want %d", accInfo.StateNonce, 5678) } } func createContractNReq(version uint16, sender *ecdsa.PrivateKey, recip []byte, bal uint64, nonce uint64) (c *contracts.Contract, r *http.Request, e error) { returnContract, err := contracts.New(version, sender, recip, bal, nonce) if err != nil { return nil, nil, errors.New("failed to make contract : " + err.Error()) } returnContract.Sign(sender) req, err := requests.NewContractRequest("", *returnContract) if err != nil { return nil, nil, errors.New("failed to create new contract request: " + err.Error()) } return returnContract, req, nil } func TestContractRequestHandler(t *testing.T) { dbConn, err := sql.Open("sqlite3", constants.AccountsTable) if err != nil { t.Errorf("failed to open database connection : %v", err) } defer func() { if err := dbConn.Close(); err != nil { t.Errorf("failed to close database connection : %v", err) } if err := os.Remove(constants.AccountsTable); err != nil { t.Errorf("failed to remove database : %v", err) } }() statement, _ := dbConn.Prepare(sqlstatements.CREATE_ACCOUNT_BALANCES_TABLE) statement.Exec() pMap := pendingpool.NewPendingMap() contractChan := make(chan contracts.Contract, 2) pLock := new(sync.Mutex) handler := http.HandlerFunc(HandleContractRequest(dbConn, contractChan, pMap, pLock)) senderPrivateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedSenderPublicKey, _ := publickey.Encode(&senderPrivateKey.PublicKey) encodedSenderStr := hex.EncodeToString(hashing.New(encodedSenderPublicKey)) recipientPrivateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedRecipientPublicKey, _ := publickey.Encode(&recipientPrivateKey.PublicKey) var recipientWalletAddress = hashing.New(encodedRecipientPublicKey) sender2PrivateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedSender2PublicKey, _ := publickey.Encode(&sender2PrivateKey.PublicKey) encodedSender2Str := hex.EncodeToString(hashing.New(encodedSender2PublicKey)) var walletAddress2 = hashing.New(encodedSender2PublicKey) if err := accountstable.InsertAccountIntoAccountBalanceTable(dbConn, walletAddress2, 5000); err != nil { t.Errorf("failed to insert sender account") } testContract, req, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 25, 1) if err != nil { t.Errorf("failed to make contract : %v", err) } testContract2, req2, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 59, 2) if err != nil { t.Errorf("failed to make contract : %v", err) } invalidNonceContract, invalidNonceReq, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 10, 4) if err != nil { t.Errorf("failed to make contract : %v", err) } invalidBalanceContract, invalidBalanceReq, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 100000, 3) if err != nil { t.Errorf("failed to make contract : %v", err) } testContract3, req3, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 100, 3) if err != nil { t.Errorf("failed to make contract : %v", err) } diffSenderContract, diffSenderReq, err := createContractNReq(1, sender2PrivateKey, recipientWalletAddress, 10, 1) if err != nil { t.Errorf("failed to make contract : %v", err) } rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusBadRequest { t.Errorf("handler returned with wrong status code: got %v want %v", status, http.StatusBadRequest) t.Logf("%s", rr.Body.String()) } var walletAddress = hashing.New(encodedSenderPublicKey) if err := accountstable.InsertAccountIntoAccountBalanceTable(dbConn, walletAddress, 1337); err != nil { t.Errorf("failed to insert sender account") } req, err = requests.NewContractRequest("", *testContract) if err != nil { t.Errorf("failed to create new contract request: %v", err) } tests := []struct { name string c *contracts.Contract req *http.Request wantBal uint64 wantNonce uint64 key string status int }{ { "valid contract", testContract, req, 1312, 1, encodedSenderStr, http.StatusOK, }, { "valid contract2", testContract2, req2, 1337 - 25 - 59, 2, encodedSenderStr, http.StatusOK, }, { "invalid nonce contract", invalidNonceContract, invalidNonceReq, 1337 - 25 - 59, 2, encodedSenderStr, http.StatusBadRequest, }, { "invalid balance contract", invalidBalanceContract, invalidBalanceReq, 1337 - 25 - 59, 2, encodedSenderStr, http.StatusBadRequest, }, { "valid contract3", testContract3, req3, 1337 - 25 - 59 - 100, 3, encodedSenderStr, http.StatusOK, }, { "Diff sender contract", diffSenderContract, diffSenderReq, 5000 - 10, 1, encodedSender2Str, http.StatusOK, }, } var wG sync.WaitGroup for i, tt := range tests { t.Run(tt.name, func(t *testing.T) { rr = httptest.NewRecorder() wG.Add(1) go func() { handler.ServeHTTP(rr, tt.req) wG.Done() }() wG.Wait() status := rr.Code if status != tt.status { t.Errorf("handler returned with wrong status code: got %v want %v", status, tt.status) } if status == http.StatusOK { channelledContract := <-contractChan if !tt.c.Equals(channelledContract) { t.Errorf("contracts do not match: got %+v want %+v", *tt.c, channelledContract) } if pMap.Sender[tt.key].PendingBal != tt.wantBal { t.Errorf("balance do not match") } if pMap.Sender[tt.key].PendingNonce != tt.wantNonce { t.Errorf("state nonce do not match") } } if i < 5 { if l := len(pMap.Sender); l != 1 { t.Errorf("number of key-value pairs in map does not match: got %v want %v", l, 1) } } else { if l := len(pMap.Sender); l != 2 { t.Errorf("number of key-value pairs in map does not match: got %v want %v", l, 2) } } }) } } func TestGetJSONBlockByHeight(t *testing.T) { // Arrange tt := []struct { name string expectedBlock block.Block height uint64 e error expectedStatus int }{ { "Valid Block", block.Block{ Version: 3,
Height: 584, PreviousHash: []byte("guavapineapplemango1234567890abc"), MerkleRootHash: []byte("grapewatermeloncoconut1emonsabcd"), Timestamp: time.Now().UnixNano(), Data: [][]byte{{12, 13}, {232, 190, 123}, {123}}, DataLen: 3, }, 584, nil, http.StatusOK, }, { "Block not found", block.Block{}, 1043, errors.New("This block was not found"), http.StatusBadRequest, }, } // Create the mock object m := mock.MockBlockFetcher{} for _, test := range tt { t.Run(test.name, func(t *testing.T) { // Configure the mock object // When the Mock object called "FetchBlockByHeight" given the test case's height, // Return that test case's serialized block and corresponding expected error m.When("FetchBlockByHeight").Given(test.height).Return(test.expectedBlock.Serialize(), test.e) // Set up the handler handler := http.HandlerFunc(HandleGetJSONBlockByHeight(m)) // Form the request req, err := requests.GetBlockByHeightRequest(test.height) if err != nil { t.Error(err) } // Set up the recorder for the response rr := httptest.NewRecorder() // Serve the request handler.ServeHTTP(rr, req) // Actual block that is recorded in the response actualJSONBlock := block.JSONBlock{} json.Unmarshal(rr.Body.Bytes(), &actualJSONBlock) // Expected block from the test case expectedJSONBlock := test.expectedBlock.Marshal() // Assert if rr.Code != test.expectedStatus { t.Errorf("Expected HTTP Status OK, recieved: %v", rr.Code) } if rr.Code == http.StatusOK { if !reflect.DeepEqual(expectedJSONBlock, actualJSONBlock) { t.Errorf("Body of response not what expected.\nExpected: %v\nActual: %v", expectedJSONBlock, actualJSONBlock) } } }) } } func TestGetBlockFromResponse(t *testing.T) { // Arrange tt := []struct { name string expectedBlock block.Block height uint64 e error expectedStatus int }{ { "Valid Block", block.Block{ Version: 3, Height: 584, PreviousHash: hashing.New([]byte("0x34")), MerkleRootHash: hashing.New([]byte("0x34")), Timestamp: time.Now().UnixNano(), Data: [][]byte{{12, 13}, {232, 190, 123}, {123}}, DataLen: 3, }, 584, nil, http.StatusOK, }, { "Block not found", block.Block{}, 1043, errors.New("StatusBadRequest"), http.StatusBadRequest, }, } // Create the mock object m := mock.MockBlockFetcher{} for _, test := range tt { t.Run(test.name, func(t *testing.T) { // Configure the mock object // When the Mock object called "FetchBlockByHeight" given the test case's height, // Return that test case's serialized block and corresponding expected error m.When("FetchBlockByHeight").Given(test.height).Return(test.expectedBlock.Serialize(), test.e) // Set up the handler handler := http.HandlerFunc(HandleGetJSONBlockByHeight(m)) // Form the request req, err := requests.GetBlockByHeightRequest(test.height) if err != nil { t.Error(err) } // Set up the recorder for the response rr := httptest.NewRecorder() // Serve the request handler.ServeHTTP(rr, req) // Actual block that is recorded in the response actualBlock, err := GetBlockFromResponse(rr.Result()) // Assert if !test.expectedBlock.Equals(actualBlock) { t.Errorf("Body of response not what expected.\nExpected: %v\nActual: %v", test.expectedBlock, actualBlock) } }) } }
optionGroup.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 rds import ( "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/go/pulumi" ) // Provides an RDS DB option group resource. Documentation of the available options for various RDS engines can be found at: // * [MariaDB Options](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.MariaDB.Options.html) // * [Microsoft SQL Server Options](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.SQLServer.Options.html) // * [MySQL Options](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.MySQL.Options.html) // * [Oracle Options](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.Oracle.Options.html) type OptionGroup struct { s *pulumi.ResourceState } // NewOptionGroup registers a new resource with the given unique name, arguments, and options. func NewOptionGroup(ctx *pulumi.Context, name string, args *OptionGroupArgs, opts ...pulumi.ResourceOpt) (*OptionGroup, error) { if args == nil || args.EngineName == nil { return nil, errors.New("missing required argument 'EngineName'") } if args == nil || args.MajorEngineVersion == nil { return nil, errors.New("missing required argument 'MajorEngineVersion'") } inputs := make(map[string]interface{}) inputs["optionGroupDescription"] = "Managed by Pulumi" if args == nil { inputs["engineName"] = nil inputs["majorEngineVersion"] = nil inputs["name"] = nil inputs["namePrefix"] = nil inputs["options"] = nil inputs["tags"] = nil } else { inputs["engineName"] = args.EngineName inputs["majorEngineVersion"] = args.MajorEngineVersion inputs["name"] = args.Name inputs["namePrefix"] = args.NamePrefix inputs["options"] = args.Options inputs["optionGroupDescription"] = args.OptionGroupDescription inputs["tags"] = args.Tags } inputs["arn"] = nil s, err := ctx.RegisterResource("aws:rds/optionGroup:OptionGroup", name, true, inputs, opts...) if err != nil { return nil, err } return &OptionGroup{s: s}, nil } // GetOptionGroup gets an existing OptionGroup 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
(ctx *pulumi.Context, name string, id pulumi.ID, state *OptionGroupState, opts ...pulumi.ResourceOpt) (*OptionGroup, error) { inputs := make(map[string]interface{}) if state != nil { inputs["arn"] = state.Arn inputs["engineName"] = state.EngineName inputs["majorEngineVersion"] = state.MajorEngineVersion inputs["name"] = state.Name inputs["namePrefix"] = state.NamePrefix inputs["options"] = state.Options inputs["optionGroupDescription"] = state.OptionGroupDescription inputs["tags"] = state.Tags } s, err := ctx.ReadResource("aws:rds/optionGroup:OptionGroup", name, id, inputs, opts...) if err != nil { return nil, err } return &OptionGroup{s: s}, nil } // URN is this resource's unique name assigned by Pulumi. func (r *OptionGroup) URN() *pulumi.URNOutput { return r.s.URN() } // ID is this resource's unique identifier assigned by its provider. func (r *OptionGroup) ID() *pulumi.IDOutput { return r.s.ID() } // The ARN of the db option group. func (r *OptionGroup) Arn() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["arn"]) } // Specifies the name of the engine that this option group should be associated with. func (r *OptionGroup) EngineName() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["engineName"]) } // Specifies the major version of the engine that this option group should be associated with. func (r *OptionGroup) MajorEngineVersion() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["majorEngineVersion"]) } // The Name of the setting. func (r *OptionGroup) Name() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["name"]) } // Creates a unique name beginning with the specified prefix. Conflicts with `name`. Must be lowercase, to match as it is stored in AWS. func (r *OptionGroup) NamePrefix() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["namePrefix"]) } // A list of Options to apply. func (r *OptionGroup) Options() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["options"]) } // The description of the option group. Defaults to "Managed by Terraform". func (r *OptionGroup) OptionGroupDescription() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["optionGroupDescription"]) } // A mapping of tags to assign to the resource. func (r *OptionGroup) Tags() *pulumi.MapOutput { return (*pulumi.MapOutput)(r.s.State["tags"]) } // Input properties used for looking up and filtering OptionGroup resources. type OptionGroupState struct { // The ARN of the db option group. Arn interface{} // Specifies the name of the engine that this option group should be associated with. EngineName interface{} // Specifies the major version of the engine that this option group should be associated with. MajorEngineVersion interface{} // The Name of the setting. Name interface{} // Creates a unique name beginning with the specified prefix. Conflicts with `name`. Must be lowercase, to match as it is stored in AWS. NamePrefix interface{} // A list of Options to apply. Options interface{} // The description of the option group. Defaults to "Managed by Terraform". OptionGroupDescription interface{} // A mapping of tags to assign to the resource. Tags interface{} } // The set of arguments for constructing a OptionGroup resource. type OptionGroupArgs struct { // Specifies the name of the engine that this option group should be associated with. EngineName interface{} // Specifies the major version of the engine that this option group should be associated with. MajorEngineVersion interface{} // The Name of the setting. Name interface{} // Creates a unique name beginning with the specified prefix. Conflicts with `name`. Must be lowercase, to match as it is stored in AWS. NamePrefix interface{} // A list of Options to apply. Options interface{} // The description of the option group. Defaults to "Managed by Terraform". OptionGroupDescription interface{} // A mapping of tags to assign to the resource. Tags interface{} }
GetOptionGroup
client_test.go
// Copyright 2018 Twitch Interactive, Inc. 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://www.apache.org/licenses/LICENSE-2.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. package twirptest import ( "context" "fmt" "io" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "github.com/pkg/errors" "github.com/twitchtv/twirp" ) // reqInspector is a tool to check inspect HTTP Requests as they pass // through an http.Client. It implements the http.RoundTripper // interface by calling its callback, and then using the default // RoundTripper. type reqInspector struct { callback func(*http.Request) } func (i *reqInspector) RoundTrip(r *http.Request) (*http.Response, error) { i.callback(r) return http.DefaultTransport.RoundTrip(r) } func TestClientSuccessAndErrorResponses(t *testing.T) { // Service that succeeds only if requested size is 1, otherwise errors h := PickyHatmaker(1) s := httptest.NewServer(NewHaberdasherServer(h, nil)) defer s.Close() // Clients protoCli := NewHaberdasherProtobufClient(s.URL, &http.Client{}) jsonCli := NewHaberdasherJSONClient(s.URL, &http.Client{}) ctx := context.Background() var resp *Hat var err error // Test proto success resp, err = protoCli.MakeHat(ctx, &Size{Inches: 1}) if err != nil { t.Fatalf("Proto client method returned unexpected error: %s", err) } if resp == nil { t.Fatalf("Proto client method expected to return non-nil response, but it is nil") } // Test proto failure resp, err = protoCli.MakeHat(ctx, &Size{Inches: 666}) if err == nil { t.Fatalf("Proto client method expected to fail, but error is nil") } if resp != nil { t.Fatalf("Proto client method expected to return nil response on error, but returned non-nil") } // Test json success resp, err = jsonCli.MakeHat(ctx, &Size{Inches: 1}) if err != nil { t.Fatalf("JSON client method returned unexpected error: %s", err) } if resp == nil { t.Fatalf("JSON client method expected to return non-nil response, but it is nil") } // Test json failure resp, err = jsonCli.MakeHat(ctx, &Size{Inches: 666}) if err == nil { t.Fatalf("JSON client method expected to fail, but error is nil") } if resp != nil { t.Fatalf("JSON client method expected to return nil response on error, but returned non-nil") } } func TestClientSetsRequestContext(t *testing.T) { // Start up a server just so we can make a working client later. h := PickyHatmaker(1) s := httptest.NewServer(NewHaberdasherServer(h, nil)) defer s.Close() // Make an *http.Client that validates that the key-value is present // in the context. httpClient := &http.Client{ Transport: &reqInspector{ callback: func(req *http.Request) { ctx := req.Context() pkgName, exists := twirp.PackageName(ctx) if !exists { t.Error("packageName not found in context") return } if pkgName != "twirp.internal.twirptest" { t.Errorf("packageName has wrong value, have=%s, want=%s", pkgName, "twirp.internal.twirptest") } serviceName, exists := twirp.ServiceName(ctx) if !exists { t.Error("serviceName not found in context") return } if serviceName != "Haberdasher" { t.Errorf("serviceName has wrong value, have=%s, want=%s", pkgName, "Haberdasher") } methodName, exists := twirp.MethodName(ctx) if !exists { t.Error("methodName not found in context") return } if methodName != "MakeHat" { t.Errorf("methodName has wrong value, have=%s, want=%s", pkgName, "Haberdasher") } }, }, } // Test the JSON client and the Protobuf client. client := NewHaberdasherJSONClient(s.URL, httpClient) _, err := client.MakeHat(context.Background(), &Size{Inches: 1}) if err != nil { t.Errorf("MakeHat err=%s", err) } client = NewHaberdasherProtobufClient(s.URL, httpClient) _, err = client.MakeHat(context.Background(), &Size{Inches: 1}) if err != nil { t.Errorf("MakeHat err=%s", err) } } func TestClientSetsAcceptHeader(t *testing.T) { // Start up a server just so we can make a working client later. h := PickyHatmaker(1) s := httptest.NewServer(NewHaberdasherServer(h, nil)) defer s.Close() // Make an *http.Client that validates that the correct accept header is present // in the request. httpClient := &http.Client{ Transport: &reqInspector{ callback: func(req *http.Request) { if req.Header.Get("Accept") != "application/json" { t.Error("Accept header not found in req") return } }, }, } // Test the JSON client client := NewHaberdasherJSONClient(s.URL, httpClient) _, err := client.MakeHat(context.Background(), &Size{Inches: 1}) if err != nil { t.Errorf("MakeHat err=%s", err) } // Make an *http.Client that validates that the correct accept header is present // in the request. httpClient = &http.Client{ Transport: &reqInspector{ callback: func(req *http.Request) { if req.Header.Get("Accept") != "application/protobuf" { t.Error("Accept header not found in req") return } }, }, } // test the Protobuf client. client = NewHaberdasherProtobufClient(s.URL, httpClient) _, err = client.MakeHat(context.Background(), &Size{Inches: 1}) if err != nil { t.Errorf("MakeHat err=%s", err) } } // If a server returns a 3xx response, give a clear error message func TestClientRedirectError(t *testing.T) { testcase := func(code int, clientMaker func(string, HTTPClient) Haberdasher) func(*testing.T) { return func(t *testing.T) { // Make a server that redirects all requests redirecter := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "http://bogus/notreal", code) }) s := httptest.NewServer(redirecter) defer s.Close() client := clientMaker(s.URL, http.DefaultClient) _, err := client.MakeHat(context.Background(), &Size{Inches: 1}) if err == nil { t.Fatal("MakeHat err=nil, expected an error because redirects aren't allowed") } if twerr, ok := err.(twirp.Error); !ok { t.Fatalf("expected twirp.Error typed err, have=%T", err) } else { // error message should mention the code if !strings.Contains(twerr.Error(), strconv.Itoa(code)) {
t.Errorf("expected error message to mention the redirect location, but its missing: %q", twerr) } // error meta should include http_error_from_intermediary if twerr.Meta("http_error_from_intermediary") != "true" { t.Errorf("expected error.Meta('http_error_from_intermediary') to be %q, but found %q", "true", twerr.Meta("http_error_from_intermediary")) } // error meta should include status if twerr.Meta("status_code") != strconv.Itoa(code) { t.Errorf("expected error.Meta('status_code') to be %q, but found %q", code, twerr.Meta("status_code")) } // error meta should include location if twerr.Meta("location") != "http://bogus/notreal" { t.Errorf("expected error.Meta('location') to be the redirect from intermediary, but found %q", twerr.Meta("location")) } } } } // It's important to test all redirect codes because Go actually handles them differently. 302 and // 303 get automatically redirected, even POSTs. The others do not (although this may change in // go1.8). We want all of them to have the same output. t.Run("json client", func(t *testing.T) { for code := 300; code <= 308; code++ { t.Run(strconv.Itoa(code), testcase(code, NewHaberdasherJSONClient)) } }) t.Run("protobuf client", func(t *testing.T) { for code := 300; code <= 308; code++ { t.Run(strconv.Itoa(code), testcase(code, NewHaberdasherProtobufClient)) } }) } func TestClientIntermediaryErrors(t *testing.T) { testcase := func(code int, expectedErrorCode twirp.ErrorCode, clientMaker func(string, HTTPClient) Haberdasher) func(*testing.T) { return func(t *testing.T) { // Make a server that returns invalid twirp error responses, // simulating a network intermediary. s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(code) _, err := w.Write([]byte("response from intermediary")) if err != nil { t.Fatalf("Unexpected error: %s", err.Error()) } })) defer s.Close() client := clientMaker(s.URL, http.DefaultClient) _, err := client.MakeHat(context.Background(), &Size{Inches: 1}) if err == nil { t.Fatal("Expected error, but found nil") } if twerr, ok := err.(twirp.Error); !ok { t.Fatalf("expected twirp.Error typed err, have=%T", err) } else { // error message should mention the code if !strings.Contains(twerr.Msg(), fmt.Sprintf("Error from intermediary with HTTP status code %d", code)) { t.Errorf("unexpected error message: %q", twerr.Msg()) } // error meta should include http_error_from_intermediary if twerr.Meta("http_error_from_intermediary") != "true" { t.Errorf("expected error.Meta('http_error_from_intermediary') to be %q, but found %q", "true", twerr.Meta("http_error_from_intermediary")) } // error meta should include status if twerr.Meta("status_code") != strconv.Itoa(code) { t.Errorf("expected error.Meta('status_code') to be %q, but found %q", code, twerr.Meta("status_code")) } // error meta should include body if twerr.Meta("body") != "response from intermediary" { t.Errorf("expected error.Meta('body') to be the response from intermediary, but found %q", twerr.Meta("body")) } // error code should be properly mapped from HTTP Code if twerr.Code() != expectedErrorCode { t.Errorf("expected to map HTTP status %q to twirp.ErrorCode %q, but found %q", code, expectedErrorCode, twerr.Code()) } } } } var cases = []struct { httpStatusCode int twirpErrorCode twirp.ErrorCode }{ // Map meaningful HTTP codes to semantic equivalent twirp.ErrorCodes {400, twirp.Internal}, {401, twirp.Unauthenticated}, {403, twirp.PermissionDenied}, {404, twirp.BadRoute}, {429, twirp.Unavailable}, {502, twirp.Unavailable}, {503, twirp.Unavailable}, {504, twirp.Unavailable}, // all other codes are unknown {505, twirp.Unknown}, {410, twirp.Unknown}, {408, twirp.Unknown}, } for _, c := range cases { jsonTestName := fmt.Sprintf("json_client/%d_to_%s", c.httpStatusCode, c.twirpErrorCode) t.Run(jsonTestName, testcase(c.httpStatusCode, c.twirpErrorCode, NewHaberdasherJSONClient)) protoTestName := fmt.Sprintf("proto_client/%d_to_%s", c.httpStatusCode, c.twirpErrorCode) t.Run(protoTestName, testcase(c.httpStatusCode, c.twirpErrorCode, NewHaberdasherProtobufClient)) } } func TestJSONClientAllowUnknownFields(t *testing.T) { // Make a server that always returns JSON with extra fields s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json := `{"size":1, "color":"black", "extra1":"foo", "EXTRAMORE":"bar"}` w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") _, err := w.Write([]byte(json)) if err != nil { t.Fatalf("Unexpected error: %s", err.Error()) } })) defer s.Close() client := NewHaberdasherJSONClient(s.URL, http.DefaultClient) resp, err := client.MakeHat(context.Background(), &Size{Inches: 1}) if err != nil { t.Fatalf("Unexpected error: %s", err.Error()) } // resp should have the values from the response json if resp.Size != 1 { t.Errorf("expected resp.Size to be %d, found %d", 1, resp.Size) } if resp.Color != "black" { t.Errorf("expected resp.Color to be %q, found %q", "black", resp.Color) } if resp.Name != "" { // not included in the response, should default to zero-value t.Errorf("expected resp.Name to be empty (zero-value), found %q", resp.Name) } } func TestClientErrorsCanBeCaused(t *testing.T) { rootErr := fmt.Errorf("some root cause") httpClient := &http.Client{ Transport: &failingTransport{rootErr}, } client := NewHaberdasherJSONClient("", httpClient) _, err := client.MakeHat(context.Background(), &Size{Inches: 1}) if err == nil { t.Errorf("JSON MakeHat err is unexpectedly nil") } cause := errCause(err) if cause != rootErr { t.Errorf("JSON MakeHat err cause is %q, want %q", cause, rootErr) } client = NewHaberdasherProtobufClient("", httpClient) _, err = client.MakeHat(context.Background(), &Size{Inches: 1}) if err == nil { t.Errorf("Protobuf MakeHat err is unexpectedly nil") } cause = errCause(err) if cause != rootErr { t.Errorf("Protobuf MakeHat err cause is %q, want %q", cause, rootErr) } } func TestCustomHTTPClientInterface(t *testing.T) { // Start up a server just so we can make a working client later. h := PickyHatmaker(1) s := httptest.NewServer(NewHaberdasherServer(h, nil)) defer s.Close() // Create a custom wrapper to wrap our default client httpClient := &wrappedHTTPClient{ client: http.DefaultClient, wasCalled: false, } // Test the JSON client and the Protobuf client with a custom http.Client interface client := NewHaberdasherJSONClient(s.URL, httpClient) _, err := client.MakeHat(context.Background(), &Size{Inches: 1}) if err != nil { t.Errorf("MakeHat err=%s", err) } // Check if the Do function within the http.Client wrapper gets actually called if !httpClient.wasCalled { t.Errorf("HTTPClient.Do function was not called within the JSONClient") } // Reset bool for second test httpClient.wasCalled = false client = NewHaberdasherProtobufClient(s.URL, httpClient) _, err = client.MakeHat(context.Background(), &Size{Inches: 1}) if err != nil { t.Errorf("MakeHat err=%s", err) } // Check if the Do function within the http.Client wrapper gets actually called if !httpClient.wasCalled { t.Errorf("HTTPClient.Do function was not called within the ProtobufClient") } } // failingTransport is a http.RoundTripper which always returns an error. type failingTransport struct { err error // the error to return } func (t failingTransport) RoundTrip(*http.Request) (*http.Response, error) { return nil, t.err } func errCause(err error) error { cause := errors.Cause(err) if uerr, ok := cause.(*url.Error); ok { // in go1.8+, http.Client errors are wrapped in *url.Error cause = uerr.Err } return cause } // wrappedHTTPClient implements HTTPClient, but can be inspected during tests. type wrappedHTTPClient struct { client *http.Client wasCalled bool } func (c *wrappedHTTPClient) Do(req *http.Request) (resp *http.Response, err error) { c.wasCalled = true return c.client.Do(req) } func TestClientReturnsCloseErrors(t *testing.T) { h := PickyHatmaker(1) s := httptest.NewServer(NewHaberdasherServer(h, nil)) defer s.Close() httpClient := &bodyCloseErrClient{base: http.DefaultClient} testcase := func(client Haberdasher) func(*testing.T) { return func(t *testing.T) { _, err := client.MakeHat(context.Background(), &Size{Inches: 1}) if err == nil { t.Error("expected an error when body fails to close, have nil") } else { if errors.Cause(err) != bodyCloseErr { t.Errorf("got wrong root cause for error, have=%v, want=%v", err, bodyCloseErr) } } } } t.Run("json client", testcase(NewHaberdasherJSONClient(s.URL, httpClient))) t.Run("protobuf client", testcase(NewHaberdasherProtobufClient(s.URL, httpClient))) } // bodyCloseErrClient implements HTTPClient, but the response bodies it returns // give an error when they are closed. type bodyCloseErrClient struct { base HTTPClient } func (c *bodyCloseErrClient) Do(req *http.Request) (*http.Response, error) { resp, err := c.base.Do(req) if resp == nil { return resp, err } resp.Body = &errBodyCloser{resp.Body} return resp, nil } var bodyCloseErr = errors.New("failed closing") type errBodyCloser struct { base io.ReadCloser } func (ec *errBodyCloser) Read(p []byte) (int, error) { return ec.base.Read(p) } func (ec *errBodyCloser) Close() error { return bodyCloseErr }
t.Errorf("expected error message to mention the status code, but its missing: %q", twerr) } // error message should mention the redirect location if !strings.Contains(twerr.Error(), "http://bogus/notreal") {
taskdestblb.xo.go
// Package billmodel contains the types for schema 'equinox'. package billmodel // GENERATED BY XO. DO NOT EDIT. import "database/sql" // TaskdestBlb represents a row from 'equinox.taskdest_blb'. type TaskdestBlb struct { BlbLrn int64 `json:"blb_lrn"` // blb_lrn BlbData []byte `json:"blb_data"` // blb_data BlbText sql.NullString `json:"blb_text"` // blb_text } func AllTaskdestBlb(db XODB, callback func(x TaskdestBlb) bool) error { // sql query const sqlstr = `SELECT ` + `blb_lrn, blb_data, blb_text ` + `FROM equinox.taskdest_blb ` q, err := db.Query(sqlstr) if err != nil { return err } defer q.Close() // load results for q.Next() { tb := TaskdestBlb{} // scan err = q.Scan(&tb.BlbLrn, &tb.BlbData, &tb.BlbText) if err != nil { return err } if !callback(tb) { return nil } } return nil } // TaskdestBlbByBlbLrn retrieves a row from 'equinox.taskdest_blb' as a TaskdestBlb. // // Generated from index 'taskdest_blb_pkey'. func TaskdestBlbByBlbLrn(db XODB, blbLrn int64) (*TaskdestBlb, error) { var err error // sql query const sqlstr = `SELECT ` + `blb_lrn, blb_data, blb_text ` + `FROM equinox.taskdest_blb ` + `WHERE blb_lrn = $1` // run query XOLog(sqlstr, blbLrn) tb := TaskdestBlb{} err = db.QueryRow(sqlstr, blbLrn).Scan(&tb.BlbLrn, &tb.BlbData, &tb.BlbText) if err != nil
return &tb, nil }
{ return nil, err }
util_test.go
/* Copyright 2018 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. */ package controller import ( crdv1 "github.com/kubernetes-csi/external-snapshotter/pkg/apis/volumesnapshot/v1beta1" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "reflect" "testing" ) func TestGetSecretReference(t *testing.T) { testcases := map[string]struct { params map[string]string snapContentName string snapshot *crdv1.VolumeSnapshot expectRef *v1.SecretReference expectErr bool }{ "no params": { params: nil, expectRef: nil, }, "empty err": { params: map[string]string{snapshotterSecretNameKey: "", snapshotterSecretNamespaceKey: ""}, expectErr: true, }, "[deprecated] name, no namespace": { params: map[string]string{snapshotterSecretNameKey: "foo"}, expectErr: true, }, "namespace, no name": { params: map[string]string{prefixedSnapshotterSecretNamespaceKey: "foo"}, expectErr: true, }, "simple - valid": { params: map[string]string{prefixedSnapshotterSecretNameKey: "name", prefixedSnapshotterSecretNamespaceKey: "ns"}, snapshot: &crdv1.VolumeSnapshot{}, expectRef: &v1.SecretReference{Name: "name", Namespace: "ns"}, }, "[deprecated] simple - valid, no pvc": { params: map[string]string{snapshotterSecretNameKey: "name", snapshotterSecretNamespaceKey: "ns"}, snapshot: nil, expectRef: &v1.SecretReference{Name: "name", Namespace: "ns"}, }, "simple - invalid name": { params: map[string]string{prefixedSnapshotterSecretNameKey: "bad name", prefixedSnapshotterSecretNamespaceKey: "ns"}, snapshot: &crdv1.VolumeSnapshot{}, expectRef: nil, expectErr: true, }, "[deprecated] simple - invalid namespace": { params: map[string]string{snapshotterSecretNameKey: "name", snapshotterSecretNamespaceKey: "bad ns"}, snapshot: &crdv1.VolumeSnapshot{}, expectRef: nil, expectErr: true, }, "template - invalid": { params: map[string]string{ prefixedSnapshotterSecretNameKey: "static-${volumesnapshotcontent.name}-${volumesnapshot.namespace}-${volumesnapshot.name}-${volumesnapshot.annotations['akey']}", prefixedSnapshotterSecretNamespaceKey: "static-${volumesnapshotcontent.name}-${volumesnapshot.namespace}", }, snapContentName: "snapcontentname", snapshot: &crdv1.VolumeSnapshot{ ObjectMeta: metav1.ObjectMeta{ Name: "snapshotname", Namespace: "snapshotnamespace", Annotations: map[string]string{"akey": "avalue"}, }, }, expectRef: nil, expectErr: true, }, "template - invalid namespace tokens": { params: map[string]string{ snapshotterSecretNameKey: "myname", snapshotterSecretNamespaceKey: "mynamespace${bar}", }, snapshot: &crdv1.VolumeSnapshot{}, expectRef: nil, expectErr: true, }, "template - invalid name tokens": { params: map[string]string{ snapshotterSecretNameKey: "myname${foo}", snapshotterSecretNamespaceKey: "mynamespace", }, snapshot: &crdv1.VolumeSnapshot{}, expectRef: nil, expectErr: true, }, } for k, tc := range testcases { t.Run(k, func(t *testing.T) { ref, err := getSecretReference(tc.params, tc.snapContentName, tc.snapshot) if err != nil { if tc.expectErr { return } t.Fatalf("Did not expect error but got: %v", err) } else { if tc.expectErr { t.Fatalf("Expected error but got none") } } if !reflect.DeepEqual(ref, tc.expectRef) { t.Errorf("Expected %v, got %v", tc.expectRef, ref) } }) } } func TestRemovePrefixedCSIParams(t *testing.T) { testcases := []struct { name string params map[string]string expectedParams map[string]string expectErr bool }{ { name: "no prefix", params: map[string]string{"csiFoo": "bar", "bim": "baz"}, expectedParams: map[string]string{"csiFoo": "bar", "bim": "baz"}, }, { name: "one prefixed", params: map[string]string{prefixedSnapshotterSecretNameKey: "bar", "bim": "baz"}, expectedParams: map[string]string{"bim": "baz"}, }, { name: "all known prefixed", params: map[string]string{ prefixedSnapshotterSecretNameKey: "csiBar", prefixedSnapshotterSecretNamespaceKey: "csiBar", }, expectedParams: map[string]string{}, }, { name: "all known deprecated params not stripped",
snapshotterSecretNamespaceKey: "csiBar", }, expectedParams: map[string]string{ snapshotterSecretNameKey: "csiBar", snapshotterSecretNamespaceKey: "csiBar", }, }, { name: "unknown prefixed var", params: map[string]string{csiParameterPrefix + "bim": "baz"}, expectErr: true, }, { name: "empty", params: map[string]string{}, expectedParams: map[string]string{}, }, } for _, tc := range testcases { t.Logf("test: %v", tc.name) newParams, err := removePrefixedParameters(tc.params) if err != nil { if tc.expectErr { continue } else { t.Fatalf("Encountered unexpected error: %v", err) } } else { if tc.expectErr { t.Fatalf("Did not get error when one was expected") } } eq := reflect.DeepEqual(newParams, tc.expectedParams) if !eq { t.Fatalf("Stripped paramaters: %v not equal to expected paramaters: %v", newParams, tc.expectedParams) } } }
params: map[string]string{ snapshotterSecretNameKey: "csiBar",
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 [email protected]
from mongoengine import connect def load(db): u"""データベースにコネクトする """ connect( db['name'], host=db['host'], port=db['port'] )
#
fake_pivnet_client.go
// Code generated by counterfeiter. DO NOT EDIT. package pivnetversionsfakes import ( "sync" pivnet "github.com/pivotal-cf/go-pivnet/v7" "github.com/pivotal-cf/pivnet-cli/v3/commands/pivnetversions" ) type FakePivnetClient struct { PivnetVersionsStub func() (pivnet.PivnetVersions, error) pivnetVersionsMutex sync.RWMutex pivnetVersionsArgsForCall []struct { } pivnetVersionsReturns struct { result1 pivnet.PivnetVersions result2 error } pivnetVersionsReturnsOnCall map[int]struct { result1 pivnet.PivnetVersions result2 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakePivnetClient) PivnetVersions() (pivnet.PivnetVersions, error) { fake.pivnetVersionsMutex.Lock() ret, specificReturn := fake.pivnetVersionsReturnsOnCall[len(fake.pivnetVersionsArgsForCall)] fake.pivnetVersionsArgsForCall = append(fake.pivnetVersionsArgsForCall, struct { }{}) fake.recordInvocation("PivnetVersions", []interface{}{}) fake.pivnetVersionsMutex.Unlock() if fake.PivnetVersionsStub != nil { return fake.PivnetVersionsStub() } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.pivnetVersionsReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakePivnetClient) PivnetVersionsCallCount() int { fake.pivnetVersionsMutex.RLock() defer fake.pivnetVersionsMutex.RUnlock() return len(fake.pivnetVersionsArgsForCall) }
func (fake *FakePivnetClient) PivnetVersionsCalls(stub func() (pivnet.PivnetVersions, error)) { fake.pivnetVersionsMutex.Lock() defer fake.pivnetVersionsMutex.Unlock() fake.PivnetVersionsStub = stub } func (fake *FakePivnetClient) PivnetVersionsReturns(result1 pivnet.PivnetVersions, result2 error) { fake.pivnetVersionsMutex.Lock() defer fake.pivnetVersionsMutex.Unlock() fake.PivnetVersionsStub = nil fake.pivnetVersionsReturns = struct { result1 pivnet.PivnetVersions result2 error }{result1, result2} } func (fake *FakePivnetClient) PivnetVersionsReturnsOnCall(i int, result1 pivnet.PivnetVersions, result2 error) { fake.pivnetVersionsMutex.Lock() defer fake.pivnetVersionsMutex.Unlock() fake.PivnetVersionsStub = nil if fake.pivnetVersionsReturnsOnCall == nil { fake.pivnetVersionsReturnsOnCall = make(map[int]struct { result1 pivnet.PivnetVersions result2 error }) } fake.pivnetVersionsReturnsOnCall[i] = struct { result1 pivnet.PivnetVersions result2 error }{result1, result2} } func (fake *FakePivnetClient) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.pivnetVersionsMutex.RLock() defer fake.pivnetVersionsMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *FakePivnetClient) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ pivnetversions.PivnetClient = new(FakePivnetClient)
colors.rs
pub fn hex_bytes_to_u32(bytes: &[u8]) -> Result<u32, ()> { fn hex_to_int(c: u8) -> Result<u32, ()> { if c >= 48 && c <= 57 { return Ok((c - 48) as u32); } if c >= 65 && c <= 70 { return Ok((c - 65 + 10) as u32); } if c >= 97 && c <= 102 { return Ok((c - 97 + 10) as u32); } return Err(()); } match bytes.len() { 1 => { // #w let val = hex_to_int(bytes[0])?; return Ok((val<<28) | (val<<24) | (val<<20) | (val<<16) | (val<<12) | (val<<8) | 0xff); } 2 => { //#ww let val = (hex_to_int(bytes[0])? << 4) + hex_to_int(bytes[1]) ?; return Ok((val<<24)|(val<<16)|(val<<8)|0xff) }, 3 => { // #rgb let r = hex_to_int(bytes[0])?;
let g = hex_to_int(bytes[1])?; let b = hex_to_int(bytes[2])?; return Ok((r<<28) | (r<<24) | (g<<20) | (g<<16) | (b<<12) | (b<<8) | 0xff); } 4 => { // #rgba let r = hex_to_int(bytes[0])?; let g = hex_to_int(bytes[1])?; let b = hex_to_int(bytes[2])?; let a = hex_to_int(bytes[3])?; return Ok((r<<28) | (r<<24) | (g<<20) | (g<<16) | (b<<12) | (b<<8) | (a<<4) | a); } 6 => { // #rrggbb let r = (hex_to_int(bytes[0])? << 4) + hex_to_int(bytes[1]) ?; let g = (hex_to_int(bytes[2])? << 4) + hex_to_int(bytes[3]) ?; let b = (hex_to_int(bytes[4])? << 4) + hex_to_int(bytes[5]) ?; return Ok((r<<24)|(g<<16)|(b<<8)|0xff) } 8 => { // #rrggbbaa let r = (hex_to_int(bytes[0])? << 4) + hex_to_int(bytes[1]) ?; let g = (hex_to_int(bytes[2])? << 4) + hex_to_int(bytes[3]) ?; let b = (hex_to_int(bytes[4])? << 4) + hex_to_int(bytes[5]) ?; let a = (hex_to_int(bytes[6])? << 4) + hex_to_int(bytes[7]) ?; return Ok((r<<24)|(g<<16)|(b<<8)|a) } _ => (), } return Err(()); }
bert.py
""" Implementation from: https://raw.githubusercontent.com/Zenglinxiao/OpenNMT-py/bert/onmt/encoders/bert.py @Author: Zenglinxiao """ import torch.nn as nn from onmt.encoders.transformer import TransformerEncoderLayer from onmt.utils.misc import sequence_mask class BertEncoder(nn.Module): """BERT Encoder: A Transformer Encoder with LayerNorm and BertPooler. :cite:`DBLP:journals/corr/abs-1810-04805` Args: embeddings (onmt.modules.BertEmbeddings): embeddings to use num_layers (int): number of encoder layers. d_model (int): size of the model heads (int): number of heads d_ff (int): size of the inner FF layer dropout (float): dropout parameters """ def __init__(self, embeddings, num_layers=12, d_model=768, heads=12, d_ff=3072, dropout=0.1, attention_dropout=0.1, max_relative_positions=0): super(BertEncoder, self).__init__() self.num_layers = num_layers self.d_model = d_model self.heads = heads self.dropout = dropout # Feed-Forward size should be 4*d_model as in paper self.d_ff = d_ff self.embeddings = embeddings # Transformer Encoder Block self.encoder = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff,
self.layer_norm = nn.LayerNorm(d_model, eps=1e-12) self.pooler = BertPooler(d_model) @classmethod def from_opt(cls, opt, embeddings): """Alternate constructor.""" return cls( embeddings, opt.enc_layers, opt.word_vec_size, opt.heads, opt.transformer_ff, opt.dropout[0] if type(opt.dropout) is list else opt.dropout, opt.attention_dropout[0] if type(opt.attention_dropout) is list else opt.attention_dropout, opt.max_relative_positions ) def forward(self, input_ids, lengths, token_type_ids=None): """ Args: input_ids (Tensor): ``(seq_len, batch_size, feature_dim)``, padding ids=0 lengths (Tensor): ``(batch_size)``, record length of sequence token_type_ids (seq_len, batch_size): ``(B, S)``, A(0), B(1), pad(0) Returns: all_encoder_layers (list of Tensor): ``(B, S, H)``, token level pooled_output (Tensor): ``(B, H)``, sequence level """ # remove the feature dimension # seq_len x batch_size emb = self.embeddings(input_ids, token_type_ids) out = emb.transpose(0, 1).contiguous() # [batch, seq] -> [batch, 1, seq] mask = ~sequence_mask(lengths).unsqueeze(1) for layer in self.encoder: out = layer(out, mask) out = self.layer_norm(out) return emb, out.transpose(0, 1).contiguous(), lengths def update_dropout(self, dropout): self.dropout = dropout self.embeddings.update_dropout(dropout) for layer in self.encoder: layer.update_dropout(dropout) class BertPooler(nn.Module): def __init__(self, hidden_size): """A pooling block (Linear layer followed by Tanh activation). Args: hidden_size (int): size of hidden layer. """ super(BertPooler, self).__init__() self.dense = nn.Linear(hidden_size, hidden_size) self.activation_fn = nn.Tanh() def forward(self, hidden_states): """hidden_states[:, 0, :] --> {Linear, Tanh} --> Returns. Args: hidden_states (Tensor): last layer's hidden_states, ``(B, S, H)`` Returns: pooled_output (Tensor): transformed output of last layer's hidden """ first_token_tensor = hidden_states[:, 0, :] # [batch, d_model] pooled_output = self.activation_fn(self.dense(first_token_tensor)) return pooled_output
dropout, attention_dropout, max_relative_positions=max_relative_positions, activation='gelu') for _ in range(num_layers)])
user_registration.go
package requests import ( "github.com/sebastiankennedy/go-web-skeleton/app/models/user" "github.com/thedevsaddam/govalidator" ) // ValidateRegistrationForm 验证表单,返回 errs 长度等于零即通过 func ValidateRegistrationForm(data user.User) map[string][]string { // 1. 定制认证规则
"password": []string{"required", "min:6"}, "password_confirmation": []string{"required"}, } // 2. 定制错误消息 messages := govalidator.MapData{ "email": []string{ "required:Email 为必填项", "min:Email 长度需大于 4", "max:Email 长度需小于 30", "email:Email 格式不正确,请提供有效的邮箱地址", }, "username": []string{ "required:用户名为必填项", "alpha_num:格式错误,只允许数字和英文", "between:用户名长度需在 3~20 之间", }, "password": []string{ "required:密码为必填项", "min:长度需大于 6", }, "password_confirmation": []string{ "required:确认密码框为必填项", }, } // 3. 配置初始化 opts := govalidator.Options{ Data: &data, Rules: rules, TagIdentifier: "valid", // 模型中的 Struct 标签标识符 Messages: messages, } // 4. 开始验证 errs := govalidator.New(opts).ValidateStruct() // 5. 因 govalidator 不支持 password_confirmation 验证,我们自己写一个 if data.Password != data.PasswordConfirmation { errs["password_confirmation"] = append(errs["password_confirmation"], "两次输入密码不匹配!") } return errs }
rules := govalidator.MapData{ "email": []string{"required", "min:4", "max:30", "email", "not_exists:users,email"}, "username": []string{"required", "alpha_num", "between:3,20", "not_exists:users,username"},
Sharing.tsx
import React, {useCallback, useMemo} from 'react'; import {useNavigation} from '@react-navigation/native'; import {ShareablePlatform, shareContent, shareInstagramStory, shareMessages, useShareablePlatforms} from 'bridge/Share'; import {Box, Icon, Text, Toolbar} from 'components'; import {Image, StyleSheet, TouchableOpacity, View, Platform, ScrollView} from 'react-native'; import {SafeAreaView} from 'react-native-safe-area-context'; import {Theme} from 'shared/theme'; import {useI18n} from '@shopify/react-i18n'; import OnboardingBg from 'assets/onboarding-bg.svg'; import {useTheme} from '@shopify/restyle'; const ICONS = { instagram: Platform.select({ android: require('assets/instagram.android.png'), ios: require('assets/instagram.ios.png'), }), messages: Platform.select({ android: require('assets/messages.android.png'), ios: require('assets/messages.ios.png'), }), }; export const SharingScreen = () => { const [i18n] = useI18n(); const navigation = useNavigation(); const theme = useTheme<Theme>(); const close = useCallback(() => navigation.goBack(), [navigation]); const platforms = useShareablePlatforms(); const onShareByPlatform = useMemo(() => { return platforms.reduce( (acc, platform) => ({ ...acc, [platform]: () => { switch (platform) { case 'instagram': { shareInstagramStory( theme.colors.mainBackground, Platform.select({ android: i18n.translate('Sharing.Message'), ios: i18n.translate('Sharing.InstagramImageUrl'), })!, ); break; } case 'messages': { shareMessages(i18n.translate('Sharing.Message')); break; } } }, }), {} as {[key in ShareablePlatform]: () => void}, ); }, [i18n, platforms, theme.colors.mainBackground]); const onShareMore = useCallback(() => { shareContent(i18n.translate('Sharing.Message')); }, [i18n]); return ( <Box backgroundColor="overlayBackground" flex={1}> <SafeAreaView style={styles.flex}> <Toolbar title={i18n.translate('Sharing.Title')} navIcon="icon-back-arrow" navText={i18n.translate('Sharing.Close')} navLabel={i18n.translate('Sharing.Close')} onIconClicked={close} /> <Box flex={1}> <ScrollView> <Box> <OnboardingBg width="100%" viewBox="0 0 375 325" /> </Box> <Box paddingHorizontal="m">
<Box padding="m"> <Box paddingHorizontal="s" paddingRight="m" borderRadius={10} backgroundColor="infoBlockNeutralBackground" > {platforms.map(platform => ( <React.Fragment key={platform}> <TouchableOpacity onPress={onShareByPlatform[platform]} accessibilityRole="button"> <Box paddingVertical="s" flexDirection="row" alignItems="center" justifyContent="space-between"> <Image style={styles.icon} source={ICONS[platform]} /> <Text variant="bodyText" marginVertical="s" marginLeft="s" color="overlayBodyText"> {i18n.translate(`Sharing.Platform-${platform}`)} </Text> <Box flex={1} alignItems="flex-end"> <Icon size={32} name="icon-chevron" /> </Box> </Box> </TouchableOpacity> <Box height={1} marginHorizontal="-m" backgroundColor="overlayBackground" /> </React.Fragment> ))} <TouchableOpacity onPress={onShareMore} accessibilityRole="button"> <Box paddingVertical="s" flexDirection="row" alignItems="center" justifyContent="space-between"> <View style={styles.moreIcon}> <Icon size={16} name="icon-ellipsis" /> </View> <Text variant="bodyText" marginVertical="s" marginLeft="s" color="overlayBodyText"> {i18n.translate('Sharing.More')} </Text> <Box flex={1} alignItems="flex-end"> <Icon size={32} name="icon-chevron" /> </Box> </Box> </TouchableOpacity> </Box> </Box> </ScrollView> </Box> </SafeAreaView> </Box> ); }; const styles = StyleSheet.create({ flex: { flex: 1, }, content: { flexGrow: 1, justifyContent: 'space-between', flexDirection: 'column', }, icon: { height: 30, width: 30, }, moreIcon: { height: 30, width: 30, borderRadius: Platform.select({android: 0, ios: 7}), backgroundColor: 'rgba(196, 196, 196, 0.3)', alignItems: 'center', justifyContent: 'center', }, });
<Text variant="bodyText" fontSize={16} color="overlayBodyText"> {i18n.translate('Sharing.SubTitle')} </Text> </Box>
iServerSideCache.d.ts
// Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> export interface IServerSideCache { }
// Type definitions for ag-grid v18.1.2
controlchildsizing.go
//---------------------------------------- // The code is automatically generated by the GenlibLcl tool. // Copyright © ying32. All Rights Reserved. // // Licensed under Apache License 2.0 // //---------------------------------------- package vcl import ( . "github.com/ying32/govcl/vcl/api" . "github.com/ying32/govcl/vcl/types" "unsafe" ) type TControlChildSizing struct { IObject instance uintptr // 特殊情况下使用,主要应对Go的GC问题,与LCL没有太多关系。 ptr unsafe.Pointer } // 动态转换一个已存在的对象实例。 // // Dynamically convert an existing object instance. func AsControlChildSizing(obj interface{}) *TControlChildSizing { instance, ptr := getInstance(obj) if instance == 0 { return nil } return &TControlChildSizing{instance: instance, ptr: ptr} } // -------------------------- Deprecated begin -------------------------- // 新建一个对象来自已经存在的对象实例指针。 // // Create a new object from an existing object instance pointer. // Deprecated: use AsControlChildSizing. func ControlChildSizingFromInst(inst uintptr) *TControlChildSizing { return AsControlChildSizing(inst) } // 新建一个对象来自已经存在的对象实例。 // // Create a new object from an existing object instance. // Deprecated: use AsControlChildSizing. func ControlChildSizingFromObj(obj IObject) *TControlChildSizing { return AsControlChildSizing(obj) } // 新建一个对象来自不安全的地址。注意:使用此函数可能造成一些不明情况,慎用。 // // Create a new object from an unsecured address. Note: Using this function may cause some unclear situations and be used with caution.. // Deprecated: use AsControlChildSizing. func ControlChildSizingFromUnsafePointer(ptr unsafe.Pointer) *TControlChildSizing { return AsControlChildSizing(ptr) } // -------------------------- Deprecated end -------------------------- // 返回对象实例指针。 // // Return object instance pointer. func (c *TControlChildSizing) Instance() uintptr { return c.instance } // 获取一个不安全的地址。 // // Get an unsafe address. func (c *TControlChildSizing) UnsafeAddr() unsafe.Pointer { return c.ptr } // 检测地址是否为空。 // // Check if the address is empty. func (c *TControlChildSizing) IsValid() bool { return c.instance != 0 } // 检测当前对象是否继承自目标对象。 // // Checks whether the current object is inherited from the target object. func (c *TControlChildSizing) Is() TIs { return TIs(c.instance) } // 动态转换当前对象为目标对象。 // // Dynamically convert the current object to the target object. //func (c *TControlChildSizing) As() TAs { // return TAs(c.instance) //} // 获取类信息指针。 // // Get class information pointer. func TControlChildSizingClass() TClass { return ControlChildSizing_StaticClassType() } // 复制一个对象,如果对象实现了此方法的话。 // // Copy an object, if the object implements this method. func (c *TControlChildSizing) Assign(Source IObject) { ControlChildSizing_Assign(c.instance, CheckPtr(Source)) } // 获取类名路径。 // // Get the class name path. func (c *TControlChildSizing) GetNamePath() string { return ControlChildSizing_GetNamePath(c.instance) } // 获取类的类型信息。 // // Get class type information. func (c *TControlChildSizing) ClassType() TClass { return ControlChildSizing_ClassType(c.instance) } // 获取当前对象类名称。 // // Get the current object class name. func (c *TControlChildSizing) ClassName() string { return ControlChildSizing_ClassName(c.instance) } // 获取当前对象实例大小。 // // Get the current object instance size. func (c *TControlChildSizing) InstanceSize() int32 { return ControlChildSizing_InstanceSize(c.instance) } // 判断当前类是否继承自指定类。 // // Determine whether the current class inherits from the specified class. func (c *TControlChildSizing) InheritsFrom(AClass TClass) bool { return ControlChildSizing_InheritsFrom(c.instance, AClass) } // 与一个对象进行比较。 // // Compare with an object. func (c *TControlChildSizing) Equals(Obj IObject) bool { return ControlChildSizing_Equals(c.instance, CheckPtr(Obj)) } // 获取类的哈希值。 // // Get the hash value of the class. func (c *TControlChildSizing) GetHashCode() int32 { return ControlChildSizing_GetHashCode(c.instance) } // 文本类信息。 // // Text information. func (c *TControlChildSizing) ToString() string { return ControlChildSizing_ToString(c.instance) } func (c *TControlChildSizing) Control() *TWinControl { return AsWinControl(ControlChildSizing_GetControl(c.instance)) } // 设置改变事件。 // // Set changed event. func (c *TControlChildSizing) SetOnChange(fn TNotifyEvent) { ControlChildSizing_SetOnChange(c.instance, fn) } func (c *TControlChildSizing) LeftRightSpacing() int32 { return ControlChildSizing_GetLeftRightSpacing(c.instance) } func (c *TControlChildSizing) SetLeftRightSpacing(value int32) { ControlChildSizing_SetLeftRightSpacing(c.instance, value) } func (c *TControlChildSizing) TopBottomSpacing() int32 { return ControlChildSizing_GetTopBottomSpacing(c.instance) } func (c *TControlChildSizing) SetTopBottomSpacing(value int32) { ControlChildSizing_SetTopBottomSpacing(c.instance, value) } func (c *TControlChildSizing) HorizontalSpacing() int32 { return ControlChildSizing_GetHorizontalSpacing(c.instance) } func (c *TControlChildSizing) SetHorizontalSpacing(value int32) { ControlChildSizing_SetHorizontalSpacing(c.instance, value) } func (c *TControlChildSizing) VerticalSpacing() int32 { return ControlChildSizing_GetVerticalSpacing(c.instance) } func (c *TControlChildSizing) SetVerticalSpacing(value int32) { ControlChildSizing_SetVerticalSpacing(c.instance, value) } func (c *TControlChildSizing) EnlargeHorizontal() TChildControlResizeStyle { return ControlChildSizing_GetEnlargeHorizontal(c.instance) } func (c *TControlChildSizing) SetEnlargeHorizontal(value TChildControlResizeStyle) { ControlChildSizing_SetEnlargeHorizontal(c.instance, value) } func (c *TControlChildSizing) EnlargeVertical() TChildControlResizeStyle { return ControlChildSizing_GetEnlargeVertical(c.instance) } func (c *TControlChildSizing) SetEnlargeVertical(value TChildControlResizeStyle) { ControlChildSizing_SetEnlargeVertical(c.instance, value) } func (c *TControlChildSizing) ShrinkHorizontal() TChildControlResizeStyle { return ControlChildSizing_GetShrinkHorizontal(c.instance) } func (c *TControlChildSizing) SetShrinkHorizontal(value TChildControlResizeStyle) { ControlChildSizing_SetShrinkHorizontal(c.instance, value) } func (c *TControlChildSizing) ShrinkVertical() TChildControlResizeStyle { return ControlChildSizing_GetShrinkVertical(c.instance) } func (c *TControlChildSizing) SetShrinkVertical(value TChildControlResizeStyle) { ControlChildSizing_SetShrinkVertical(c.instance, value) } func (c *TControlChildSizing) Layout() TControlChildrenLayout { return ControlChildSizing_GetLayout(c.instance) } func (c *TControlChildSizing) SetLayout(value TControlChildrenLayout) { ControlChildSizing_SetLayout(c.instance, value) } func (c *TControlChildSizing) ControlsPerLine() int32 { return ControlChildSizing_GetControlsPerLine(c.instance) }
func (c *TControlChildSizing) SetControlsPerLine(value int32) { ControlChildSizing_SetControlsPerLine(c.instance, value) }
use_memo.rs
use std::cell::RefCell; use std::rc::Rc; use crate::functional::{hook, use_state}; /// Get a immutable reference to a memoized value /// /// Memoization means it will only get recalculated when provided dependencies update/change #[hook] pub fn use_memo<T, F, D>(f: F, deps: D) -> Rc<T> where T: 'static, F: FnOnce(&D) -> T, D: 'static + PartialEq, { let val = use_state(|| -> RefCell<Option<Rc<T>>> { RefCell::new(None) }); let last_deps = use_state(|| -> RefCell<Option<D>> { RefCell::new(None) }); let mut val = val.borrow_mut(); let mut last_deps = last_deps.borrow_mut(); match ( val.as_ref(), last_deps.as_ref().and_then(|m| (m != &deps).then(|| ())), ) { // Previous value exists and last_deps == deps (Some(m), None) => m.clone(), _ => { let new_val = Rc::new(f(&deps));
new_val } } }
*last_deps = Some(deps); *val = Some(new_val.clone());
test_cython_1.py
import unittest from test.general_tests import NumericalizationTestSuite from protovoc.numericalization.cython.cython_1 import Numericalization from protovoc.vocab.cython import Vocab class TestCython1Numericalization(unittest.TestCase, NumericalizationTestSuite):
if __name__ == "__main__": unittest.main()
_voc = Vocab _num = Numericalization
api_op_DeleteDomainAssociation.go
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package amplify import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/internal/awsutil" "github.com/aws/aws-sdk-go-v2/private/protocol" ) // Request structure for the delete Domain Association request.
_ struct{} `type:"structure"` // Unique Id for an Amplify App. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` // Name of the domain. // // DomainName is a required field DomainName *string `location:"uri" locationName:"domainName" type:"string" required:"true"` } // String returns the string representation func (s DeleteDomainAssociationInput) String() string { return awsutil.Prettify(s) } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteDomainAssociationInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteDomainAssociationInput"} if s.AppId == nil { invalidParams.Add(aws.NewErrParamRequired("AppId")) } if s.AppId != nil && len(*s.AppId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AppId", 1)) } if s.DomainName == nil { invalidParams.Add(aws.NewErrParamRequired("DomainName")) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteDomainAssociationInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AppId != nil { v := *s.AppId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "appId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DomainName != nil { v := *s.DomainName metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "domainName", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteDomainAssociationResult type DeleteDomainAssociationOutput struct { _ struct{} `type:"structure"` // Structure for Domain Association, which associates a custom domain with an // Amplify App. // // DomainAssociation is a required field DomainAssociation *DomainAssociation `locationName:"domainAssociation" type:"structure" required:"true"` } // String returns the string representation func (s DeleteDomainAssociationOutput) String() string { return awsutil.Prettify(s) } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteDomainAssociationOutput) MarshalFields(e protocol.FieldEncoder) error { if s.DomainAssociation != nil { v := s.DomainAssociation metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "domainAssociation", v, metadata) } return nil } const opDeleteDomainAssociation = "DeleteDomainAssociation" // DeleteDomainAssociationRequest returns a request value for making API operation for // AWS Amplify. // // Deletes a DomainAssociation. // // // Example sending a request using DeleteDomainAssociationRequest. // req := client.DeleteDomainAssociationRequest(params) // resp, err := req.Send(context.TODO()) // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteDomainAssociation func (c *Client) DeleteDomainAssociationRequest(input *DeleteDomainAssociationInput) DeleteDomainAssociationRequest { op := &aws.Operation{ Name: opDeleteDomainAssociation, HTTPMethod: "DELETE", HTTPPath: "/apps/{appId}/domains/{domainName}", } if input == nil { input = &DeleteDomainAssociationInput{} } req := c.newRequest(op, input, &DeleteDomainAssociationOutput{}) return DeleteDomainAssociationRequest{Request: req, Input: input, Copy: c.DeleteDomainAssociationRequest} } // DeleteDomainAssociationRequest is the request type for the // DeleteDomainAssociation API operation. type DeleteDomainAssociationRequest struct { *aws.Request Input *DeleteDomainAssociationInput Copy func(*DeleteDomainAssociationInput) DeleteDomainAssociationRequest } // Send marshals and sends the DeleteDomainAssociation API request. func (r DeleteDomainAssociationRequest) Send(ctx context.Context) (*DeleteDomainAssociationResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &DeleteDomainAssociationResponse{ DeleteDomainAssociationOutput: r.Request.Data.(*DeleteDomainAssociationOutput), response: &aws.Response{Request: r.Request}, } return resp, nil } // DeleteDomainAssociationResponse is the response type for the // DeleteDomainAssociation API operation. type DeleteDomainAssociationResponse struct { *DeleteDomainAssociationOutput response *aws.Response } // SDKResponseMetdata returns the response metadata for the // DeleteDomainAssociation request. func (r *DeleteDomainAssociationResponse) SDKResponseMetdata() *aws.Response { return r.response }
// Please also see https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteDomainAssociationRequest type DeleteDomainAssociationInput struct {
matrix_transform.rs
use na::{Point3, Rotation3, Unit}; use crate::aliases::{TMat, TMat4, TVec, TVec3}; use crate::traits::{Number, RealNumber}; /// The identity matrix. pub fn identity<T: Number, const D: usize>() -> TMat<T, D, D> { TMat::<T, D, D>::identity() } /// Build a look at view matrix based on the right handedness. /// /// # Parameters: /// /// * `eye` − Position of the camera. /// * `center` − Position where the camera is looking at. /// * `u` − Normalized up vector, how the camera is oriented. Typically `(0, 1, 0)`. /// /// # See also: /// /// * [`look_at_lh`](fn.look_at_lh.html) /// * [`look_at_rh`](fn.look_at_rh.html) pub fn look_at<T: RealNumber>(eye: &TVec3<T>, center: &TVec3<T>, up: &TVec3<T>) -> TMat4<T> { look_at_rh(eye, center, up) } /// Build a left handed look at view matrix. /// /// # Parameters: /// /// * `eye` − Position of the camera. /// * `center` − Position where the camera is looking at. /// * `u` − Normalized up vector, how the camera is oriented. Typically `(0, 1, 0)`. /// /// # See also: /// /// * [`look_at`](fn.look_at.html) /// * [`look_at_rh`](fn.look_at_rh.html) pub fn look_at_lh<T: RealNumber>(eye: &TVec3<T>, center: &TVec3<T>, up: &TVec3<T>) -> TMat4<T> { TMat::look_at_lh(&Point3::from(*eye), &Point3::from(*center), up) } /// Build a right handed look at view matrix. /// /// # Parameters: /// /// * `eye` − Position of the camera. /// * `center` − Position where the camera is looking at. /// * `u` − Normalized up vector, how the camera is oriented. Typically `(0, 1, 0)`. /// /// # See also: /// /// * [`look_at`](fn.look_at.html) /// * [`look_at_lh`](fn.look_at_lh.html) pub fn look_at_rh<T: Real
e: &TVec3<T>, center: &TVec3<T>, up: &TVec3<T>) -> TMat4<T> { TMat::look_at_rh(&Point3::from(*eye), &Point3::from(*center), up) } /// Builds a rotation 4 * 4 matrix created from an axis vector and an angle and right-multiply it to `m`. /// /// # Parameters: /// /// * `m` − Input matrix multiplied by this rotation matrix. /// * `angle` − Rotation angle expressed in radians. /// * `axis` − Rotation axis, recommended to be normalized. /// /// # See also: /// /// * [`rotate_x`](fn.rotate_x.html) /// * [`rotate_y`](fn.rotate_y.html) /// * [`rotate_z`](fn.rotate_z.html) /// * [`scale`](fn.scale.html) /// * [`translate`](fn.translate.html) pub fn rotate<T: RealNumber>(m: &TMat4<T>, angle: T, axis: &TVec3<T>) -> TMat4<T> { m * Rotation3::from_axis_angle(&Unit::new_normalize(*axis), angle).to_homogeneous() } /// Builds a rotation 4 * 4 matrix around the X axis and right-multiply it to `m`. /// /// # Parameters: /// /// * `m` − Input matrix multiplied by this rotation matrix. /// * `angle` − Rotation angle expressed in radians. /// /// # See also: /// /// * [`rotate`](fn.rotate.html) /// * [`rotate_y`](fn.rotate_y.html) /// * [`rotate_z`](fn.rotate_z.html) /// * [`scale`](fn.scale.html) /// * [`translate`](fn.translate.html) pub fn rotate_x<T: RealNumber>(m: &TMat4<T>, angle: T) -> TMat4<T> { rotate(m, angle, &TVec::x()) } /// Builds a rotation 4 * 4 matrix around the Y axis and right-multiply it to `m`. /// /// # Parameters: /// /// * `m` − Input matrix multiplied by this rotation matrix. /// * `angle` − Rotation angle expressed in radians. /// /// # See also: /// /// * [`rotate`](fn.rotate.html) /// * [`rotate_x`](fn.rotate_x.html) /// * [`rotate_z`](fn.rotate_z.html) /// * [`scale`](fn.scale.html) /// * [`translate`](fn.translate.html) pub fn rotate_y<T: RealNumber>(m: &TMat4<T>, angle: T) -> TMat4<T> { rotate(m, angle, &TVec::y()) } /// Builds a rotation 4 * 4 matrix around the Z axis and right-multiply it to `m`. /// /// # Parameters: /// /// * `m` − Input matrix multiplied by this rotation matrix. /// * `angle` − Rotation angle expressed in radians. /// /// # See also: /// /// * [`rotate`](fn.rotate.html) /// * [`rotate_x`](fn.rotate_x.html) /// * [`rotate_y`](fn.rotate_y.html) /// * [`scale`](fn.scale.html) /// * [`translate`](fn.translate.html) pub fn rotate_z<T: RealNumber>(m: &TMat4<T>, angle: T) -> TMat4<T> { rotate(m, angle, &TVec::z()) } /// Builds a scale 4 * 4 matrix created from 3 scalars and right-multiply it to `m`. /// /// # Parameters: /// /// * `m` − Input matrix multiplied by this scale matrix. /// * `v` − Ratio of scaling for each axis. /// /// # See also: /// /// * [`rotate`](fn.rotate.html) /// * [`rotate_x`](fn.rotate_x.html) /// * [`rotate_y`](fn.rotate_y.html) /// * [`rotate_z`](fn.rotate_z.html) /// * [`translate`](fn.translate.html) pub fn scale<T: Number>(m: &TMat4<T>, v: &TVec3<T>) -> TMat4<T> { m.prepend_nonuniform_scaling(v) } /// Builds a translation 4 * 4 matrix created from a vector of 3 components and right-multiply it to `m`. /// /// # Parameters: /// /// * `m` − Input matrix multiplied by this translation matrix. /// * `v` − Coordinates of a translation vector. /// /// # See also: /// /// * [`rotate`](fn.rotate.html) /// * [`rotate_x`](fn.rotate_x.html) /// * [`rotate_y`](fn.rotate_y.html) /// * [`rotate_z`](fn.rotate_z.html) /// * [`scale`](fn.scale.html) pub fn translate<T: Number>(m: &TMat4<T>, v: &TVec3<T>) -> TMat4<T> { m.prepend_translation(v) }
Number>(ey
watcher.js
/*jslint regexp: true */ (function () { 'use strict';
window.requirejs(['//127.0.0.1:4344/socket.io/socket.io.js'], function (io) { var socket = io('https://127.0.0.1:4344'); socket.on('changeCss', function (data) { var links = document.querySelectorAll('link[href*="' + data.path + '"]'); Array.prototype.forEach.call(links, function (link) { var tmp = link.href; link.href = tmp; }); }); socket.on('changeJs', function (data) { var scripts = document.querySelectorAll('script[src*="' + data.path + '"]'), moduleName = data.path; Array.prototype.forEach.call(scripts, function (script) { var tmp = script.src; window.requirejs([tmp.replace(/\.js.*/, '.js?' + Math.random())], function (Module) { window.require.undef(moduleName); define(moduleName, [], function () { return Module; }); }); }); }); }); }());
bundle.ts
/** * 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. * * @format */ import {Command} from '@oclif/command'; import {args} from '@oclif/parser'; import fs from 'fs-extra'; import path from 'path'; import {runBuild, getPluginDetails} from 'flipper-pkg-lib'; export default class
extends Command { public static description = 'transpiles and bundles plugin'; public static examples = [`$ flipper-pkg bundle path/to/plugin`]; public static args: args.IArg[] = [ { name: 'directory', required: false, default: '.', description: 'Path to plugin package directory for bundling. Defaults to the current working directory.', }, ]; public async run() { const {args} = this.parse(Bundle); const inputDirectory: string = path.resolve(process.cwd(), args.directory); const stat = await fs.lstat(inputDirectory); if (!stat.isDirectory()) { this.error(`Plugin source ${inputDirectory} is not a directory.`); } const packageJsonPath = path.join(inputDirectory, 'package.json'); if (!(await fs.pathExists(packageJsonPath))) { this.error( `package.json is not found in plugin source directory ${inputDirectory}.`, ); } const plugin = await getPluginDetails(inputDirectory); const out = path.resolve(inputDirectory, plugin.main); await fs.ensureDir(path.dirname(out)); await runBuild(inputDirectory, plugin.source, out); } }
Bundle
utils.go
package utils import ( "bytes" "encoding/json" "fmt" "github.com/jfrog/gofrog/stringutils" "io/ioutil" "net/url" "os" "path" "path/filepath" "regexp" "runtime" "strconv" "strings" "github.com/jfrog/jfrog-client-go/utils/io/fileutils" "github.com/jfrog/jfrog-client-go/utils/errorutils" "github.com/jfrog/jfrog-client-go/utils/log" ) const ( Development = "development" Agent = "jfrog-client-go" Version = "1.6.0" ) // In order to limit the number of items loaded from a reader into the memory, we use a buffers with this size limit. var MaxBufferSize = 50000 var userAgent = getDefaultUserAgent() func getVersion() string { return Version } func GetUserAgent() string { return userAgent } func SetUserAgent(newUserAgent string) { userAgent = newUserAgent } func getDefaultUserAgent() string { return fmt.Sprintf("%s/%s", Agent, getVersion()) } // Get the local root path, from which to start collecting artifacts to be used for: // 1. Uploaded to Artifactory, // 2. Adding to the local build-info, to be later published to Artifactory. func GetRootPath(path string, patternType PatternType, parentheses ParenthesesSlice) string { // The first step is to split the local path pattern into sections, by the file separator. separator := "/" sections := strings.Split(path, separator) if len(sections) == 1 { separator = "\\" sections = strings.Split(path, separator) } // Now we start building the root path, making sure to leave out the sub-directory that includes the pattern. rootPath := "" for _, section := range sections { if section == "" { continue } if patternType == RegExp { if strings.Index(section, "(") != -1 { break } } else { if strings.Index(section, "*") != -1 { break } if strings.Index(section, "(") != -1 { temp := rootPath + section if isWildcardParentheses(temp, parentheses) { break } } if patternType == AntPattern { if strings.Index(section, "?") != -1 { break } } } if rootPath != "" { rootPath += separator } if section == "~" { rootPath += GetUserHomeDir() } else { rootPath += section } } if len(sections) > 0 && sections[0] == "" { rootPath = separator + rootPath } if rootPath == "" { return "." } return rootPath } // Return true if the ‘str’ argument contains open parentasis, that is related to a placeholder. // The ‘parentheses’ argument contains all the indexes of placeholder parentheses. func isWildcardParentheses(str string, parentheses ParenthesesSlice) bool { toFind := "(" currStart := 0 for { idx := strings.Index(str, toFind) if idx == -1 { break } if parentheses.IsPresent(idx) { return true } currStart += idx + len(toFind) str = str[idx+len(toFind):] } return false } func StringToBool(boolVal string, defaultValue bool) (bool, error) { if len(boolVal) > 0 { result, err := strconv.ParseBool(boolVal) errorutils.CheckError(err) return result, err } return defaultValue, nil } func AddTrailingSlashIfNeeded(url string) string { if url != "" && !strings.HasSuffix(url, "/") { url += "/" } return url } func IndentJson(jsonStr []byte) string { return doIndentJson(jsonStr, "", " ") } func IndentJsonArray(jsonStr []byte) string { return doIndentJson(jsonStr, " ", " ") } func doIndentJson(jsonStr []byte, prefix, indent string) string { var content bytes.Buffer err := json.Indent(&content, jsonStr, prefix, indent) if err == nil { return content.String() } return string(jsonStr) } func MergeMaps(src map[string]string, dst map[string]string) { for k, v := range src { dst[k] = v } } func CopyMap(src map[string]string) (dst map[string]string) { dst = make(map[string]string) for k, v := range src { dst[k] = v } return } func ConvertLocalPatternToRegexp(localPath string, patternType PatternType) string { if localPath == "./" || localPath == ".\\" { return "^.*$" } if strings.HasPrefix(localPath, "./") { localPath = localPath[2:] } else if strings.HasPrefix(localPath, ".\\") { localPath = localPath[3:] } if patternType == AntPattern { localPath = antPatternToRegExp(cleanPath(localPath)) } else if patternType == WildCardPattern { localPath = stringutils.WildcardPatternToRegExp(cleanPath(localPath)) } return localPath } // Clean /../ | /./ using filepath.Clean. func cleanPath(path string) string { temp := path[len(path)-1:] path = filepath.Clean(path) if temp == `\` || temp == "/" { path += temp } // Since filepath.Clean replaces \\ with \, we revert this action. path = strings.Replace(path, `\`, `\\`, -1) return path } func antPatternToRegExp(localPath string) string { localPath = stringutils.EscapeSpecialChars(localPath) separator := getFileSeparator() var wildcard = ".*" // ant `*` ~ regexp `([^/]*)` : `*` matches zero or more characters except from `/`. var regAsterisk = "([^" + separator + "]*)" // ant `**` ~ regexp `(.*)?` : `**` matches zero or more 'directories' in a path. var doubleRegAsterisk = "(" + wildcard + ")?" // `?` => `.{1}` : `?` matches one character. localPath = strings.Replace(localPath, `?`, ".{1}", -1) // `*` => `([^/]*)` localPath = strings.Replace(localPath, `*`, regAsterisk, -1) // `**` => `(.*)?` localPath = strings.Replace(localPath, regAsterisk+regAsterisk, doubleRegAsterisk, -1) // Remove slashes near `**` localPath = strings.Replace(localPath, doubleRegAsterisk+separator, doubleRegAsterisk, -1) localPath = strings.Replace(localPath, separator+doubleRegAsterisk, doubleRegAsterisk, -1) if strings.HasSuffix(localPath, "/") || strings.HasSuffix(localPath, "\\") { localPath += wildcard } return "^" + localPath + "$" } func getFileSeparator() string { if IsWindows() { return "\\\\" } return "/" } // Replaces matched regular expression from path to corresponding placeholder {i} at target. // Example 1: // pattern = "repoA/1(.*)234" ; path = "repoA/1hello234" ; target = "{1}" ; ignoreRepo = false // returns "hello" // Example 2: // pattern = "repoA/1(.*)234" ; path = "repoB/1hello234" ; target = "{1}" ; ignoreRepo = true // returns "hello" // return (parsed target, placeholders replaced in target, error) func BuildTargetPath(pattern, path, target string, ignoreRepo bool) (string, bool, error) { asteriskIndex := strings.Index(pattern, "*") slashIndex := strings.Index(pattern, "/") if shouldRemoveRepo(ignoreRepo, asteriskIndex, slashIndex) { // Removing the repository part of the path is required when working with virtual repositories, as the pattern // may contain the virtual-repository name, but the path contains the local-repository name. pattern = removeRepoFromPath(pattern) path = removeRepoFromPath(path) } pattern = addEscapingParentheses(pattern, target) pattern = stringutils.WildcardPatternToRegExp(pattern) if slashIndex < 0 { // If '/' doesn't exist, add an optional trailing-slash to support cases in which the provided pattern // is only the repository name. dollarIndex := strings.LastIndex(pattern, "$") pattern = pattern[:dollarIndex] pattern += "(/.*)?$" } r, err := regexp.Compile(pattern) err = errorutils.CheckError(err) if err != nil { return "", false, err } groups := r.FindStringSubmatch(path) if len(groups) > 0 { target, replaceOccurred := ReplacePlaceHolders(groups, target) return target, replaceOccurred, nil } return target, false, nil } // group - regular expression matched group to replace with placeholders // toReplace - target pattern to replace // Return - (parsed placeholders string, placeholders were replaced) func ReplacePlaceHolders(groups []string, toReplace string) (string, bool) { preReplaced := toReplace for i := 1; i < len(groups); i++ { group := strings.Replace(groups[i], "\\", "/", -1) toReplace = strings.Replace(toReplace, "{"+strconv.Itoa(i)+"}", group, -1) } replaceOccurred := preReplaced != toReplace return toReplace, replaceOccurred }
var strDryRun string if dryRun { strDryRun = "[Dry run] " } return "[Thread " + strconv.Itoa(threadId) + "] " + strDryRun } func TrimPath(path string) string { path = strings.Replace(path, "\\", "/", -1) path = strings.Replace(path, "//", "/", -1) path = strings.Replace(path, "../", "", -1) path = strings.Replace(path, "./", "", -1) return path } func Bool2Int(b bool) int { if b { return 1 } return 0 } func ReplaceTildeWithUserHome(path string) string { if len(path) > 1 && path[0:1] == "~" { return GetUserHomeDir() + path[1:] } return path } func GetUserHomeDir() string { if IsWindows() { home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") if home == "" { home = os.Getenv("USERPROFILE") } return strings.Replace(home, "\\", "\\\\", -1) } return os.Getenv("HOME") } func GetBoolEnvValue(flagName string, defValue bool) (bool, error) { envVarValue := os.Getenv(flagName) if envVarValue == "" { return defValue, nil } val, err := strconv.ParseBool(envVarValue) err = CheckErrorWithMessage(err, "can't parse environment variable "+flagName) return val, err } func CheckErrorWithMessage(err error, message string) error { if err != nil { log.Error(message) err = errorutils.CheckError(err) } return err } func ConvertSliceToMap(slice []string) map[string]bool { mapFromSlice := make(map[string]bool) for _, value := range slice { mapFromSlice[value] = true } return mapFromSlice } func removeRepoFromPath(path string) string { if idx := strings.Index(path, "/"); idx != -1 { return path[idx:] } return path } func shouldRemoveRepo(ignoreRepo bool, asteriskIndex, slashIndex int) bool { if !ignoreRepo || slashIndex < 0 { return false } if asteriskIndex < 0 { return true } return IsSlashPrecedeAsterisk(asteriskIndex, slashIndex) } func IsSlashPrecedeAsterisk(asteriskIndex, slashIndex int) bool { return slashIndex < asteriskIndex && slashIndex >= 0 } // Split str by the provided separator, escaping the separator if it is prefixed by a back-slash. func SplitWithEscape(str string, separator rune) []string { var parts []string var current bytes.Buffer escaped := false for _, char := range str { if char == '\\' { if escaped { current.WriteRune(char) } escaped = true } else if char == separator && !escaped { parts = append(parts, current.String()) current.Reset() } else { escaped = false current.WriteRune(char) } } parts = append(parts, current.String()) return parts } func AddProps(oldProps, additionalProps string) string { if len(oldProps) > 0 && !strings.HasSuffix(oldProps, ";") && len(additionalProps) > 0 { oldProps += ";" } return oldProps + additionalProps } func IsWindows() bool { return runtime.GOOS == "windows" } func IsMacOS() bool { return runtime.GOOS == "darwin" } type Artifact struct { LocalPath string TargetPath string SymlinkTargetPath string } const ( WildCardPattern PatternType = "wildcard" RegExp PatternType = "regexp" AntPattern PatternType = "ant" ) type PatternType string type PatternTypes struct { RegExp bool Ant bool } func GetPatternType(patternTypes PatternTypes) PatternType { if patternTypes.RegExp { return RegExp } if patternTypes.Ant { return AntPattern } return WildCardPattern } type Sha256Summary struct { sha256 string succeeded bool } func NewSha256Summary() *Sha256Summary { return &Sha256Summary{} } func (bps *Sha256Summary) IsSucceeded() bool { return bps.succeeded } func (bps *Sha256Summary) SetSucceeded(succeeded bool) *Sha256Summary { bps.succeeded = succeeded return bps } func (bps *Sha256Summary) GetSha256() string { return bps.sha256 } func (bps *Sha256Summary) SetSha256(sha256 string) *Sha256Summary { bps.sha256 = sha256 return bps } // Represents a file transfer from SourcePath to TargetPath. // Each of the paths can be on the local machine (full or relative) or in Artifactory (full URL). // The file's Sha256 is calculated by Artifactory during the upload. we read the sha256 from the HTTP's response body. type FileTransferDetails struct { SourcePath string `json:"sourcePath,omitempty"` TargetPath string `json:"targetPath,omitempty"` Sha256 string `json:"sha256,omitempty"` } // Represent deployed artifact's details returned from build-info project for maven and gradle. type DeployableArtifactDetails struct { SourcePath string `json:"sourcePath,omitempty"` ArtifactDest string `json:"artifactDest,omitempty"` Sha256 string `json:"sha256,omitempty"` DeploySucceeded bool `json:"deploySucceeded,omitempty"` TargetRepository string `json:"targetRepository,omitempty"` } func (details *DeployableArtifactDetails) CreateFileTransferDetails(rtUrl, targetRepository string) (FileTransferDetails, error) { // The function path.Join expects a path, not a URL. // Therefore we first parse the URL to get a path. url, err := url.Parse(rtUrl + targetRepository) if err != nil { return FileTransferDetails{}, err } // The path.join will always use a single slash (forward) to separate between the two vars. url.Path = path.Join(url.Path, details.ArtifactDest) targetPath := url.String() return FileTransferDetails{SourcePath: details.SourcePath, TargetPath: targetPath, Sha256: details.Sha256}, nil } type UploadResponseBody struct { Checksums ChecksumDetails `json:"checksums,omitempty"` } type ChecksumDetails struct { Md5 string Sha1 string Sha256 string } func SaveFileTransferDetailsInTempFile(filesDetails *[]FileTransferDetails) (string, error) { tempFile, err := fileutils.CreateTempFile() if err != nil { return "", err } filePath := tempFile.Name() return filePath, SaveFileTransferDetailsInFile(filePath, filesDetails) } func SaveFileTransferDetailsInFile(filePath string, details *[]FileTransferDetails) error { // Marshal and save files details to a file. // The details will be saved in a json format in an array with key "files" for printing later finalResult := struct { Files *[]FileTransferDetails `json:"files"` }{} finalResult.Files = details files, err := json.Marshal(finalResult) if err != nil { return errorutils.CheckError(err) } return errorutils.CheckError(ioutil.WriteFile(filePath, files, 0700)) } // Extract sha256 of the uploaded file (calculated by artifactory) from the response's body. // In case of uploading archive with "--explode" the response body will be empty and sha256 won't be shown at // the detailed summary. func ExtractSha256FromResponseBody(body []byte) (string, error) { if len(body) > 0 { responseBody := new(UploadResponseBody) err := json.Unmarshal(body, &responseBody) if errorutils.CheckError(err) != nil { return "", err } return responseBody.Checksums.Sha256, nil } return "", nil }
func GetLogMsgPrefix(threadId int, dryRun bool) string {
pgncheck.go
package main import ( "errors" "io" "log" "os" "github.com/anastasop/gochess" ) var ErrGamesLimit = errors.New("too much games") func
() { parsePGN(os.Stdin, 50) } func parsePGN(pgnReader io.Reader, limit int) error { parser := gochess.NewParser(pgnReader) var err error var pgngame *gochess.Game ngames := 0 for { if pgngame, err = parser.NextGame(); err == nil && pgngame != nil { ngames++; // log.Printf("%s", pgngame.PGNText) if err = pgngame.ParseMovesText(); err == nil { board := gochess.NewBoard() for _, ply := range pgngame.Moves.Plies { if err = board.MakeMove(ply.SAN); err != nil { log.Printf("Move Error: %s", err) return err } } if ngames >= limit { return ErrGamesLimit } } log.Println("Parsed", pgngame.Tags["White"], " - ", pgngame.Tags["Black"]) } if err != nil || pgngame == nil { break } } if err != nil { log.Printf("PGN parser error: game %d error \"%s\"", ngames, err) } return err }
main
parse_comments.rs
use crate::data::tokens::*; use nom::{ branch::alt, bytes::complete::{tag, take_until, take_while}, combinator::opt, error::ParseError, multi::many0, IResult, *, }; fn comment_single_line<'a, E: ParseError<Span<'a>>>(s: Span<'a>) -> IResult<Span<'a>, Span<'a>, E> { let (s, _) = tag(INLINE_COMMENT)(s)?; let val: IResult<Span<'a>, Span<'a>, E> = take_until("\n")(s); let val2: IResult<Span<'a>, Span<'a>, E> = take_until("\r\n")(s); if let Ok((s, v)) = val { Ok((s, v)) } else if let Ok((s, v)) = val2 { Ok((s, v)) } else { // if new line is not found the rest of the file is commented Ok((Span::new(""), Span::new(""))) } } fn comment_delimited<'a, E: ParseError<Span<'a>>>(s: Span<'a>) -> IResult<Span<'a>, Span<'a>, E> { let (s, _) = tag(START_COMMENT)(s)?; let val: IResult<Span<'a>, Span<'a>, E> = take_until(END_COMMENT)(s); match val { Ok((s, _)) => tag(END_COMMENT)(s), // Error in comment_delimited is if '*/' is not found so all the rest of the file is commented Err(Err::Error(_e)) | Err(Err::Failure(_e)) => Ok((Span::new(""), Span::new(""))), Err(Err::Incomplete(_)) => unimplemented!(), } } fn all_comments<'a, E: ParseError<Span<'a>>>(s: Span<'a>) -> IResult<Span<'a>, Span<'a>, E> { let (s, _) = opt(sp)(s)?; alt((comment_delimited, comment_single_line))(s) } pub fn comment<'a, E: ParseError<Span<'a>>>(s: Span<'a>) -> IResult<Span<'a>, Span<'a>, E> { let val = many0(all_comments)(s); let (s, _) = match val { Ok(val) => val, Err(Err::Error((s, _val))) | Err(Err::Failure((s, _val))) => return Ok((s, s)), Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)), }; // Ok((s, s)) sp(s) } fn sp<'a, E: ParseError<Span<'a>>>(s: Span<'a>) -> IResult<Span<'a>, Span<'a>, E>
{ // nom combinators like `take_while` return a function. That function is the // parser,to which we can pass the input take_while(move |c| WHITE_SPACE.contains(c))(s) }
models.py
from django.conf import settings from django.db import models class TaskTransaction(models.Model): "Generated Model" status = models.CharField( max_length=10, ) timestamp_completed = models.DateTimeField( null=True, blank=True, ) task = models.ForeignKey( "task.Task", null=True, blank=True, on_delete=models.CASCADE, related_name="tasktransaction_task", ) date = models.DateField( null=True, blank=True, ) timestamp_started = models.DateTimeField( null=True, blank=True, ) class Message(models.Model): "Generated Model" customer = models.ForeignKey( "task_profile.CustomerProfile", on_delete=models.CASCADE, related_name="message_customer", ) tasker = models.ForeignKey( "task_profile.TaskerProfile", on_delete=models.CASCADE, related_name="message_tasker", ) message = models.TextField() timestamp_created = models.DateTimeField( auto_now_add=True, ) task = models.ForeignKey( "task.Task", null=True, blank=True, on_delete=models.SET_NULL, related_name="message_task", ) class Rating(models.Model): "Generated Model" tasker = models.ForeignKey( "task_profile.TaskerProfile", on_delete=models.CASCADE, related_name="rating_tasker", ) rating = models.FloatField() timestamp_created = models.DateTimeField( auto_now_add=True, ) review = models.TextField( null=True, blank=True, ) customer = models.ForeignKey( "task_profile.CustomerProfile", null=True, blank=True, on_delete=models.SET_NULL, related_name="rating_customer", ) class
(models.Model): "Generated Model" customer = models.ForeignKey( "task_profile.CustomerProfile", on_delete=models.CASCADE, related_name="task_customer", ) tasker = models.ForeignKey( "task_profile.TaskerProfile", on_delete=models.CASCADE, related_name="task_tasker", ) category = models.ForeignKey( "task_category.Category", on_delete=models.CASCADE, related_name="task_category", ) details = models.TextField() frequency = models.CharField( max_length=7, ) size = models.CharField( max_length=6, ) location = models.OneToOneField( "location.TaskLocation", on_delete=models.CASCADE, related_name="task_location", ) is_confirmed = models.BooleanField() status = models.CharField( max_length=10, ) timestamp_created = models.DateTimeField( auto_now_add=True, ) timestamp_confirmed = models.DateTimeField( null=True, blank=True, ) subcategory = models.ForeignKey( "task_category.Subcategory", null=True, blank=True, on_delete=models.CASCADE, related_name="task_subcategory", ) # Create your models here.
Task
utils_test.go
// // (C) Copyright 2021 Intel Corporation. // // SPDX-License-Identifier: BSD-2-Clause-Patent // package engine import ( "testing" "github.com/daos-stack/daos/src/control/common" "github.com/pkg/errors" ) func TestValidateLogMasks(t *testing.T)
{ for name, tc := range map[string]struct { masks string expErr error }{ "empty": {}, "single level; no prefix": { masks: "DEBUG", }, "single level; no prefix; unknown level": { masks: "WARNING", expErr: errors.New("unknown log level"), }, "single assignment": { masks: "mgmt=DEBUG", }, "single level; single assignment": { masks: "ERR,mgmt=DEBUG", }, "single level; single assignment; mixed caae": { masks: "err,mgmt=debuG", }, "single level; single assignment; with space": { masks: "ERR, mgmt=DEBUG", expErr: errors.New("illegal characters"), }, "single level; single assignment; bad level": { masks: "ERR,mgmt=DEG", expErr: errors.New("unknown log level"), }, "single assignment; single level": { masks: "mgmt=DEBUG,ERR", expErr: errors.New("want PREFIX=LEVEL"), }, "multiple assignments": { masks: "mgmt=DEBUG,bio=ERR", }, "multiple assignments; bad format": { masks: "mgmt=DEBUG,bio=ERR=", expErr: errors.New("want PREFIX=LEVEL"), }, "multiple assignments; bad chars": { masks: "mgmt=DEBUG,bio!=ERR", expErr: errors.New("illegal characters"), }, "too long": { masks: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", expErr: errors.New("exceeds maximum length (1024>1023)"), }, } { t.Run(name, func(t *testing.T) { gotErr := ValidateLogMasks(tc.masks) common.CmpErr(t, tc.expErr, gotErr) }) } }
get_health_gateway.rs
use crate::error::Result; use dytp_component::health_resp_gateway::HealthRespGateway; use dytp_connection::prelude::*; use dytp_protocol::delim::Delim; use dytp_protocol::method::plain; use failure::Error; use futures::prelude::*; use std::net::SocketAddr; use tokio::prelude::*; #[derive(Debug)] pub struct GetHealthGateway { pub addr: SocketAddr, upstream: Upstream, } impl GetHealthGateway { pub fn new(gateway_addr: SocketAddr) -> Result<GetHealthGateway> { let mut upstream = Upstream::new(gateway_addr.clone())?; let buf: Vec<u8> = plain::Common::HEALTH.into(); upstream.set_write_delim(Delim::Http); upstream.set_read_delim(Delim::Http); upstream.write(&buf)?; upstream.flush()?; Ok(GetHealthGateway { addr: gateway_addr, upstream, }) } } impl Future for GetHealthGateway { type Item = Option<HealthRespGateway>; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error>
}
{ match self.upstream.poll() { Ok(Async::Ready(Some(payload))) => { let health = HealthRespGateway::from(&payload as &[u8]); return Ok(Async::Ready(Some(health))); } Ok(Async::Ready(None)) => { log::warn!("failed to get gateway health on {}", self.addr); return Ok(Async::Ready(None)); } Ok(Async::NotReady) => { task::current().notify(); return Ok(Async::NotReady); } Err(e) => { log::warn!( "failed to get gateway health on {} due to error={:?}", self.addr, e ); return Ok(Async::Ready(None)); } } }
__init__.py
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbind.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ from . import config from . import state class switched_vlan(PybindBase):
""" This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-interfaces - based on the path /interfaces/interface/ethernet/switched-vlan. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Enclosing container for VLAN interface-specific data on Ethernet interfaces. These are for standard L2, switched-style VLANs. """ __slots__ = ("_path_helper", "_extmethods", "__config", "__state") _yang_name = "switched-vlan" _pybind_generated_by = "container" def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__config = YANGDynClass( base=config.config, is_container="container", yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/vlan", defining_module="openconfig-vlan", yang_type="container", is_config=True, ) self.__state = YANGDynClass( base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/vlan", defining_module="openconfig-vlan", yang_type="container", is_config=True, ) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path() + [self._yang_name] else: return ["interfaces", "interface", "ethernet", "switched-vlan"] def _get_config(self): """ Getter method for config, mapped from YANG variable /interfaces/interface/ethernet/switched_vlan/config (container) YANG Description: Configuration parameters for VLANs """ return self.__config def _set_config(self, v, load=False): """ Setter method for config, mapped from YANG variable /interfaces/interface/ethernet/switched_vlan/config (container) If this variable is read-only (config: false) in the source YANG file, then _set_config is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_config() directly. YANG Description: Configuration parameters for VLANs """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=config.config, is_container="container", yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/vlan", defining_module="openconfig-vlan", yang_type="container", is_config=True, ) except (TypeError, ValueError): raise ValueError( { "error-string": """config must be of a type compatible with container""", "defined-type": "container", "generated-type": """YANGDynClass(base=config.config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/vlan', defining_module='openconfig-vlan', yang_type='container', is_config=True)""", } ) self.__config = t if hasattr(self, "_set"): self._set() def _unset_config(self): self.__config = YANGDynClass( base=config.config, is_container="container", yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/vlan", defining_module="openconfig-vlan", yang_type="container", is_config=True, ) def _get_state(self): """ Getter method for state, mapped from YANG variable /interfaces/interface/ethernet/switched_vlan/state (container) YANG Description: State variables for VLANs """ return self.__state def _set_state(self, v, load=False): """ Setter method for state, mapped from YANG variable /interfaces/interface/ethernet/switched_vlan/state (container) If this variable is read-only (config: false) in the source YANG file, then _set_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_state() directly. YANG Description: State variables for VLANs """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/vlan", defining_module="openconfig-vlan", yang_type="container", is_config=True, ) except (TypeError, ValueError): raise ValueError( { "error-string": """state must be of a type compatible with container""", "defined-type": "container", "generated-type": """YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/vlan', defining_module='openconfig-vlan', yang_type='container', is_config=True)""", } ) self.__state = t if hasattr(self, "_set"): self._set() def _unset_state(self): self.__state = YANGDynClass( base=state.state, is_container="container", yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/vlan", defining_module="openconfig-vlan", yang_type="container", is_config=True, ) config = __builtin__.property(_get_config, _set_config) state = __builtin__.property(_get_state, _set_state) _pyangbind_elements = OrderedDict([("config", config), ("state", state)])